From 65ec7b78ac8af2ec4d80193b8864c8c269d166d0 Mon Sep 17 00:00:00 2001 From: roberf Date: Tue, 24 Mar 2026 23:27:25 -0400 Subject: [PATCH 1/8] feat: add hierarchical workspace groups with templates, scripts, and project management - Workspaces can have child workspaces (max 3 levels deep) - Collapsible hierarchy with color-coded card backgrounds - Templates system for multi-tab project setups with startup commands - Script repository for reusable shell scripts - Scripts menu bar with Run Script, Open Template, Manage Templates/Scripts - Template Manager and Script Manager editor windows - Startup commands persist and re-run on session restore (lightning bolt indicator) - Finder "Open in cmux" service - Context menu: Add Child, Make Child, Raise Level, Run Script - Socket API: group.*, project.open, project.open_template, script.*, template.* - CLI: cmux open command - Prompt-ready detection for reliable command execution via sendInteractiveText Co-Authored-By: Claude Opus 4.6 (1M context) --- CLI/cmux.swift | 48 ++- GhosttyTabs.xcodeproj/project.pbxproj | 118 +++++- Resources/Info.plist | 24 +- Sources/AppDelegate.swift | 132 +++++- Sources/CmuxConfigError.swift | 33 ++ Sources/CmuxConfigParser.swift | 261 ++++++++++++ Sources/CmuxConfigParserGroups.swift | 60 +++ Sources/ContentView.swift | 378 +++++++++++++++--- Sources/GroupHeaderView.swift | 17 + Sources/GroupItem.swift | 6 + Sources/MonospaceTextEditor.swift | 51 +++ Sources/NewWorkspaceDialog.swift | 84 ++++ Sources/Panels/TerminalPanel.swift | 50 +++ Sources/ScriptManagerViewModel.swift | 101 +++++ Sources/ScriptManagerWindow.swift | 225 +++++++++++ Sources/ScriptRepository.swift | 117 ++++++ Sources/ScriptsMenu.swift | 86 ++++ Sources/SessionPersistence.swift | 10 + Sources/SessionWorkspaceGroupSnapshot.swift | 102 +++++ Sources/StartupScriptRunner.swift | 95 +++++ Sources/TabManager.swift | 292 +++++++++++++- Sources/TemplateManagerHelpSidebar.swift | 217 ++++++++++ Sources/TemplateManagerViewModel.swift | 129 ++++++ Sources/TemplateManagerWindow.swift | 242 +++++++++++ Sources/TemplateRepository.swift | 162 ++++++++ Sources/TemplateYamlParser.swift | 282 +++++++++++++ Sources/TerminalController.swift | 75 +++- Sources/TerminalControllerGroupCommands.swift | 188 +++++++++ .../TerminalControllerProjectCommands.swift | 271 +++++++++++++ ...inalControllerScriptTemplateCommands.swift | 119 ++++++ Sources/Update/UpdateTitlebarAccessory.swift | 4 +- Sources/Workspace.swift | 28 +- Sources/WorkspaceGroup.swift | 3 + Sources/WorkspaceGroupManager.swift | 206 ++++++++++ Sources/cmuxApp.swift | 4 + cmuxTests/CmuxConfigParserTests.swift | 127 ++++++ cmuxTests/ScriptRepositoryTests.swift | 144 +++++++ cmuxTests/SessionGroupPersistenceTests.swift | 198 +++++++++ cmuxTests/TemplateRepositoryTests.swift | 101 +++++ cmuxTests/WorkspaceGroupManagerTests.swift | 312 +++++++++++++++ cmuxTests/WorkspaceGroupTests.swift | 42 ++ 41 files changed, 5036 insertions(+), 108 deletions(-) create mode 100644 Sources/CmuxConfigError.swift create mode 100644 Sources/CmuxConfigParser.swift create mode 100644 Sources/CmuxConfigParserGroups.swift create mode 100644 Sources/GroupHeaderView.swift create mode 100644 Sources/GroupItem.swift create mode 100644 Sources/MonospaceTextEditor.swift create mode 100644 Sources/NewWorkspaceDialog.swift create mode 100644 Sources/ScriptManagerViewModel.swift create mode 100644 Sources/ScriptManagerWindow.swift create mode 100644 Sources/ScriptRepository.swift create mode 100644 Sources/ScriptsMenu.swift create mode 100644 Sources/SessionWorkspaceGroupSnapshot.swift create mode 100644 Sources/StartupScriptRunner.swift create mode 100644 Sources/TemplateManagerHelpSidebar.swift create mode 100644 Sources/TemplateManagerViewModel.swift create mode 100644 Sources/TemplateManagerWindow.swift create mode 100644 Sources/TemplateRepository.swift create mode 100644 Sources/TemplateYamlParser.swift create mode 100644 Sources/TerminalControllerGroupCommands.swift create mode 100644 Sources/TerminalControllerProjectCommands.swift create mode 100644 Sources/TerminalControllerScriptTemplateCommands.swift create mode 100644 Sources/WorkspaceGroup.swift create mode 100644 Sources/WorkspaceGroupManager.swift create mode 100644 cmuxTests/CmuxConfigParserTests.swift create mode 100644 cmuxTests/ScriptRepositoryTests.swift create mode 100644 cmuxTests/SessionGroupPersistenceTests.swift create mode 100644 cmuxTests/TemplateRepositoryTests.swift create mode 100644 cmuxTests/WorkspaceGroupManagerTests.swift create mode 100644 cmuxTests/WorkspaceGroupTests.swift diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 2d762f0a5b74..dbd50796bbbc 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -1403,9 +1403,16 @@ struct CMUXCLI { return } + // Explicit `open` command: cmux open /path/to/folder [--window ] + if command == "open" { + let openPath = commandArgs.first ?? "." + try openProjectPath(openPath, socketPath: resolvedSocketPath, windowId: windowId) + return + } + // If the argument looks like a path (not a known command), open a workspace there. if looksLikePath(command) { - try openPath(command, socketPath: resolvedSocketPath) + try openProjectPath(command, socketPath: resolvedSocketPath, windowId: windowId) return } @@ -2490,6 +2497,45 @@ struct CMUXCLI { try activateApp() } + /// Open a project via the project.open socket command (supports .cmux.yaml). + private func openProjectPath(_ path: String, socketPath: String, windowId: String?) throws { + let resolved = resolvePath(path) + var isDir: ObjCBool = false + let exists = FileManager.default.fileExists(atPath: resolved, isDirectory: &isDir) + + let directory: String + if exists && isDir.boolValue { + directory = resolved + } else if exists { + directory = (resolved as NSString).deletingLastPathComponent + } else { + throw CLIError(message: "Path does not exist: \(resolved)") + } + + let client = SocketClient(path: socketPath) + if (try? client.connect()) == nil { + client.close() + try launchApp() + let launchedClient = try SocketClient.waitForConnectableSocket(path: socketPath, timeout: 10) + defer { launchedClient.close() } + var params: [String: Any] = ["path": directory] + if let windowId { params["window_id"] = windowId } + let response = try launchedClient.sendV2(method: "project.open", params: params) + let groupId = (response["group_id"] as? String) ?? "" + if !groupId.isEmpty { print("OK \(groupId)") } + try activateApp() + return + } + defer { client.close() } + + var params: [String: Any] = ["path": directory] + if let windowId { params["window_id"] = windowId } + let response = try client.sendV2(method: "project.open", params: params) + let groupId = (response["group_id"] as? String) ?? "" + if !groupId.isEmpty { print("OK \(groupId)") } + try activateApp() + } + private func runFeedback( commandArgs: [String], socketPath: String, diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index deeb15460252..6edf7d6907a2 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -119,7 +119,36 @@ CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */; }; 8C4BBF2DEF6DF93F395A9EE7 /* TerminalControllerSocketSecurityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */; }; 2BB56A710BB1FC50367E5BCF /* TabManagerSessionSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10D684CFFB8CDEF89CE2D9E1 /* TabManagerSessionSnapshotTests.swift */; }; - /* End PBXBuildFile section */ + WG000001A1B2C3D4E5F60001 /* GroupItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000011A1B2C3D4E5F60001 /* GroupItem.swift */; }; + WG000002A1B2C3D4E5F60001 /* WorkspaceGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000012A1B2C3D4E5F60001 /* WorkspaceGroup.swift */; }; + WG000003A1B2C3D4E5F60001 /* WorkspaceGroupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000013A1B2C3D4E5F60001 /* WorkspaceGroupTests.swift */; }; + WG000004A1B2C3D4E5F60001 /* WorkspaceGroupManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000014A1B2C3D4E5F60001 /* WorkspaceGroupManager.swift */; }; + WG000005A1B2C3D4E5F60001 /* WorkspaceGroupManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000015A1B2C3D4E5F60001 /* WorkspaceGroupManagerTests.swift */; }; + WG000006A1B2C3D4E5F60001 /* SessionWorkspaceGroupSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000016A1B2C3D4E5F60001 /* SessionWorkspaceGroupSnapshot.swift */; }; + WG000007A1B2C3D4E5F60001 /* SessionGroupPersistenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000017A1B2C3D4E5F60001 /* SessionGroupPersistenceTests.swift */; }; + WG000008A1B2C3D4E5F60001 /* CmuxConfigError.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000018A1B2C3D4E5F60001 /* CmuxConfigError.swift */; }; + WG000009A1B2C3D4E5F60001 /* CmuxConfigParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000019A1B2C3D4E5F60001 /* CmuxConfigParser.swift */; }; + WG00000AA1B2C3D4E5F60001 /* ScriptRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001AA1B2C3D4E5F60001 /* ScriptRepository.swift */; }; + WG00000BA1B2C3D4E5F60001 /* TemplateRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001BA1B2C3D4E5F60001 /* TemplateRepository.swift */; }; + WG00000BA1B2C3D4E5F60002 /* TemplateYamlParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001BA1B2C3D4E5F60002 /* TemplateYamlParser.swift */; }; + WG00000CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift */; }; + WG00000DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift */; }; + WG00000EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift */; }; + WG00000FA1B2C3D4E5F60001 /* GroupHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001FA1B2C3D4E5F60001 /* GroupHeaderView.swift */; }; + WG000010A1B2C3D4E5F60001 /* StartupScriptRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000020A1B2C3D4E5F60001 /* StartupScriptRunner.swift */; }; + WG000021A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000022A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift */; }; + WG000023A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000024A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift */; }; + WG000025A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000026A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift */; }; + WG000027A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000028A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift */; }; + WG000029A1B2C3D4E5F60001 /* NewWorkspaceDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */; }; + WG00002BA1B2C3D4E5F60001 /* ScriptsMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */; }; + WG00002DA1B2C3D4E5F60001 /* TemplateManagerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */; }; + WG00002FA1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */; }; + WG000031A1B2C3D4E5F60001 /* ScriptManagerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */; }; + WG000033A1B2C3D4E5F60001 /* MonospaceTextEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000034A1B2C3D4E5F60001 /* MonospaceTextEditor.swift */; }; + WG000035A1B2C3D4E5F60001 /* TemplateManagerViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000036A1B2C3D4E5F60001 /* TemplateManagerViewModel.swift */; }; + WG000037A1B2C3D4E5F60001 /* ScriptManagerViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000038A1B2C3D4E5F60001 /* ScriptManagerViewModel.swift */; }; + /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ A5001020 /* Embed Frameworks */ = { @@ -231,6 +260,35 @@ A5001223 /* UpdateLogStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/UpdateLogStore.swift; sourceTree = ""; }; A5001241 /* WindowDecorationsController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowDecorationsController.swift; sourceTree = ""; }; A5001611 /* SessionPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionPersistence.swift; sourceTree = ""; }; + WG000011A1B2C3D4E5F60001 /* GroupItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupItem.swift; sourceTree = ""; }; + WG000012A1B2C3D4E5F60001 /* WorkspaceGroup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGroup.swift; sourceTree = ""; }; + WG000013A1B2C3D4E5F60001 /* WorkspaceGroupTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGroupTests.swift; sourceTree = ""; }; + WG000014A1B2C3D4E5F60001 /* WorkspaceGroupManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGroupManager.swift; sourceTree = ""; }; + WG000015A1B2C3D4E5F60001 /* WorkspaceGroupManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGroupManagerTests.swift; sourceTree = ""; }; + WG000016A1B2C3D4E5F60001 /* SessionWorkspaceGroupSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionWorkspaceGroupSnapshot.swift; sourceTree = ""; }; + WG000017A1B2C3D4E5F60001 /* SessionGroupPersistenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionGroupPersistenceTests.swift; sourceTree = ""; }; + WG000018A1B2C3D4E5F60001 /* CmuxConfigError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigError.swift; sourceTree = ""; }; + WG000019A1B2C3D4E5F60001 /* CmuxConfigParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigParser.swift; sourceTree = ""; }; + WG00001AA1B2C3D4E5F60001 /* ScriptRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptRepository.swift; sourceTree = ""; }; + WG00001BA1B2C3D4E5F60001 /* TemplateRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateRepository.swift; sourceTree = ""; }; + WG00001BA1B2C3D4E5F60002 /* TemplateYamlParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateYamlParser.swift; sourceTree = ""; }; + WG00001CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigParserTests.swift; sourceTree = ""; }; + WG00001DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptRepositoryTests.swift; sourceTree = ""; }; + WG00001EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateRepositoryTests.swift; sourceTree = ""; }; + WG00001FA1B2C3D4E5F60001 /* GroupHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupHeaderView.swift; sourceTree = ""; }; + WG000020A1B2C3D4E5F60001 /* StartupScriptRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StartupScriptRunner.swift; sourceTree = ""; }; + WG000022A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerGroupCommands.swift; sourceTree = ""; }; + WG000024A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerScriptTemplateCommands.swift; sourceTree = ""; }; + WG000026A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigParserGroups.swift; sourceTree = ""; }; + WG000028A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerProjectCommands.swift; sourceTree = ""; }; + WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewWorkspaceDialog.swift; sourceTree = ""; }; + WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptsMenu.swift; sourceTree = ""; }; + WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerWindow.swift; sourceTree = ""; }; + WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerHelpSidebar.swift; sourceTree = ""; }; + WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptManagerWindow.swift; sourceTree = ""; }; + WG000034A1B2C3D4E5F60001 /* MonospaceTextEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MonospaceTextEditor.swift; sourceTree = ""; }; + WG000036A1B2C3D4E5F60001 /* TemplateManagerViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerViewModel.swift; sourceTree = ""; }; + WG000038A1B2C3D4E5F60001 /* ScriptManagerViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptManagerViewModel.swift; sourceTree = ""; }; 818DBCD4AB69EB72573E8138 /* SidebarResizeUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarResizeUITests.swift; sourceTree = ""; }; B8F266256A1A3D9A45BD840F /* SidebarHelpMenuUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarHelpMenuUITests.swift; sourceTree = ""; }; B8F266276A1A3D9A45BD840F /* DisplayResolutionRegressionUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DisplayResolutionRegressionUITests.swift; sourceTree = ""; }; @@ -448,6 +506,29 @@ A5001241 /* WindowDecorationsController.swift */, A5001222 /* WindowAccessor.swift */, A5001611 /* SessionPersistence.swift */, + WG000011A1B2C3D4E5F60001 /* GroupItem.swift */, + WG000012A1B2C3D4E5F60001 /* WorkspaceGroup.swift */, + WG000014A1B2C3D4E5F60001 /* WorkspaceGroupManager.swift */, + WG000016A1B2C3D4E5F60001 /* SessionWorkspaceGroupSnapshot.swift */, + WG000018A1B2C3D4E5F60001 /* CmuxConfigError.swift */, + WG000019A1B2C3D4E5F60001 /* CmuxConfigParser.swift */, + WG00001AA1B2C3D4E5F60001 /* ScriptRepository.swift */, + WG00001BA1B2C3D4E5F60001 /* TemplateRepository.swift */, + WG00001BA1B2C3D4E5F60002 /* TemplateYamlParser.swift */, + WG00001FA1B2C3D4E5F60001 /* GroupHeaderView.swift */, + WG000020A1B2C3D4E5F60001 /* StartupScriptRunner.swift */, + WG000022A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift */, + WG000026A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift */, + WG000028A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift */, + WG000024A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift */, + WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */, + WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */, + WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */, + WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */, + WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */, + WG000034A1B2C3D4E5F60001 /* MonospaceTextEditor.swift */, + WG000036A1B2C3D4E5F60001 /* TemplateManagerViewModel.swift */, + WG000038A1B2C3D4E5F60001 /* ScriptManagerViewModel.swift */, ); path = Sources; sourceTree = ""; @@ -537,6 +618,12 @@ EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */, 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */, 10D684CFFB8CDEF89CE2D9E1 /* TabManagerSessionSnapshotTests.swift */, + WG000013A1B2C3D4E5F60001 /* WorkspaceGroupTests.swift */, + WG000015A1B2C3D4E5F60001 /* WorkspaceGroupManagerTests.swift */, + WG000017A1B2C3D4E5F60001 /* SessionGroupPersistenceTests.swift */, + WG00001CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift */, + WG00001DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift */, + WG00001EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift */, ); path = cmuxTests; sourceTree = ""; @@ -740,6 +827,29 @@ A5001240 /* WindowDecorationsController.swift in Sources */, A500120C /* WindowAccessor.swift in Sources */, A5001610 /* SessionPersistence.swift in Sources */, + WG000001A1B2C3D4E5F60001 /* GroupItem.swift in Sources */, + WG000002A1B2C3D4E5F60001 /* WorkspaceGroup.swift in Sources */, + WG000004A1B2C3D4E5F60001 /* WorkspaceGroupManager.swift in Sources */, + WG000006A1B2C3D4E5F60001 /* SessionWorkspaceGroupSnapshot.swift in Sources */, + WG000008A1B2C3D4E5F60001 /* CmuxConfigError.swift in Sources */, + WG000009A1B2C3D4E5F60001 /* CmuxConfigParser.swift in Sources */, + WG00000AA1B2C3D4E5F60001 /* ScriptRepository.swift in Sources */, + WG00000BA1B2C3D4E5F60001 /* TemplateRepository.swift in Sources */, + WG00000BA1B2C3D4E5F60002 /* TemplateYamlParser.swift in Sources */, + WG00000FA1B2C3D4E5F60001 /* GroupHeaderView.swift in Sources */, + WG000010A1B2C3D4E5F60001 /* StartupScriptRunner.swift in Sources */, + WG000021A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift in Sources */, + WG000023A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift in Sources */, + WG000025A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift in Sources */, + WG000027A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift in Sources */, + WG000029A1B2C3D4E5F60001 /* NewWorkspaceDialog.swift in Sources */, + WG00002BA1B2C3D4E5F60001 /* ScriptsMenu.swift in Sources */, + WG00002DA1B2C3D4E5F60001 /* TemplateManagerWindow.swift in Sources */, + WG00002FA1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift in Sources */, + WG000031A1B2C3D4E5F60001 /* ScriptManagerWindow.swift in Sources */, + WG000033A1B2C3D4E5F60001 /* MonospaceTextEditor.swift in Sources */, + WG000035A1B2C3D4E5F60001 /* TemplateManagerViewModel.swift in Sources */, + WG000037A1B2C3D4E5F60001 /* ScriptManagerViewModel.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -797,6 +907,12 @@ CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */, 8C4BBF2DEF6DF93F395A9EE7 /* TerminalControllerSocketSecurityTests.swift in Sources */, 2BB56A710BB1FC50367E5BCF /* TabManagerSessionSnapshotTests.swift in Sources */, + WG000003A1B2C3D4E5F60001 /* WorkspaceGroupTests.swift in Sources */, + WG000005A1B2C3D4E5F60001 /* WorkspaceGroupManagerTests.swift in Sources */, + WG000007A1B2C3D4E5F60001 /* SessionGroupPersistenceTests.swift in Sources */, + WG00000CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift in Sources */, + WG00000DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift in Sources */, + WG00000EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Resources/Info.plist b/Resources/Info.plist index c96a632f9c1f..0ba92bdcd1ab 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -73,10 +73,10 @@ NSMenuItem default - New $(PRODUCT_NAME) Workspace Here + Open in $(PRODUCT_NAME) NSMessage - openTab + openInCmux NSRequiredContext NSTextContent @@ -85,26 +85,6 @@ NSSendTypes NSFilenamesPboardType - public.plain-text - - - - NSMenuItem - - default - New $(PRODUCT_NAME) Window Here - - NSMessage - openWindow - NSRequiredContext - - NSTextContent - FilePath - - NSSendTypes - - NSFilenamesPboardType - public.plain-text diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index a6794e5cad1e..80d2e59141a6 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -2331,6 +2331,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent installMenuBarVisibilityObserver() syncMenuBarExtraVisibility() updateController.startUpdaterIfNeeded() + NSApp.servicesProvider = self + ScriptRepository.shared.seedDefaultScripts() + TemplateRepository.shared.seedDefaultTemplates() } titlebarAccessoryController.start() windowDecorationsController.start() @@ -4231,6 +4234,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent mainWindowContexts.values.first(where: { $0.windowId == windowId })?.tabManager } + /// Returns all TabManagers across all windows. + func allTabManagers() -> [TabManager] { + mainWindowContexts.values.map(\.tabManager) + } + func windowId(for tabManager: TabManager) -> UUID? { mainWindowContexts.values.first(where: { $0.tabManager === tabManager })?.windowId } @@ -11330,6 +11338,129 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } #endif + // MARK: - Finder Services + + /// macOS Services handler: "Open in cmux" + /// Accepts folder paths from Finder right-click > Services. + @objc func openInCmux( + _ pasteboard: NSPasteboard, + userData: String, + error: AutoreleasingUnsafeMutablePointer + ) { + guard let items = pasteboard.readObjects(forClasses: [NSURL.self], options: [ + .urlReadingFileURLsOnly: true + ]) as? [URL] else { return } + + // Use the first window's tab manager, or create a window if none exists + let tm: TabManager + if let firstWindowSummary = listMainWindowSummaries().first, + let existingTm = tabManagerFor(windowId: firstWindowSummary.windowId) { + tm = existingTm + } else if let firstURL = items.first { + let path = resolvedDirectoryPath(for: firstURL) + _ = createMainWindow(initialWorkingDirectory: path) + NSApp.activate(ignoringOtherApps: true) + return + } else { + return + } + + for url in items { + var isDir: ObjCBool = false + let path: String + if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir), isDir.boolValue { + path = url.path + } else { + path = url.deletingLastPathComponent().path + } + + let dirURL = URL(fileURLWithPath: path) + let canonicalPath = dirURL.resolvingSymlinksInPath().path + + // Dedupe: check if a parent workspace already targets this directory + var found = false + for wsId in tm.items { + guard let ws = tm.workspace(for: wsId), + ws.hasChildren else { continue } + let wsPath = URL(fileURLWithPath: ws.currentDirectory) + .resolvingSymlinksInPath().path + if wsPath == canonicalPath { + tm.selectedTabId = ws.id + found = true + break + } + } + if found { continue } + + // Create project workspace + let projectName = dirURL.lastPathComponent + let ws = tm.addWorkspace(workingDirectory: path, select: true) + ws.title = projectName + } + + NSApp.activate(ignoringOtherApps: true) + } + + // MARK: - Finder Services (Builder / Fixer) + + @objc func openInCmuxBuilder( + _ pasteboard: NSPasteboard, + userData: String, + error: AutoreleasingUnsafeMutablePointer + ) { + openInCmuxWithTemplate(pasteboard, templateName: "Builder", error: error) + } + + @objc func openInCmuxFixer( + _ pasteboard: NSPasteboard, + userData: String, + error: AutoreleasingUnsafeMutablePointer + ) { + openInCmuxWithTemplate(pasteboard, templateName: "Fixer", error: error) + } + + private func openInCmuxWithTemplate( + _ pasteboard: NSPasteboard, + templateName: String, + error: AutoreleasingUnsafeMutablePointer + ) { + guard let items = pasteboard.readObjects(forClasses: [NSURL.self], options: [ + .urlReadingFileURLsOnly: true + ]) as? [URL] else { return } + + guard let firstWindowSummary = listMainWindowSummaries().first, + let tm = tabManagerFor(windowId: firstWindowSummary.windowId) else { + // No window exists — create one for the first directory + if let firstURL = items.first { + let path = resolvedDirectoryPath(for: firstURL) + _ = createMainWindow(initialWorkingDirectory: path) + } + return + } + + let template = try? TemplateRepository.shared.getTemplate(named: templateName) + + for url in items { + let path = resolvedDirectoryPath(for: url) + if let template { + tm.openTemplate(template, directory: path) + } else { + // Fallback: plain workspace if template not found + let ws = tm.addWorkspace(workingDirectory: path, select: true) + ws.title = URL(fileURLWithPath: path).lastPathComponent + } + } + + NSApp.activate(ignoringOtherApps: true) + } + + private func resolvedDirectoryPath(for url: URL) -> String { + var isDir: ObjCBool = false + if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir), isDir.boolValue { + return url.path + } + return url.deletingLastPathComponent().path + } } @MainActor @@ -12673,5 +12804,4 @@ private extension NSWindow { } return hitWebView === webView } - } diff --git a/Sources/CmuxConfigError.swift b/Sources/CmuxConfigError.swift new file mode 100644 index 000000000000..fa7c0fbd7567 --- /dev/null +++ b/Sources/CmuxConfigError.swift @@ -0,0 +1,33 @@ +import Foundation + +/// Fatal errors during `.cmux.yaml` parsing. Thrown for unrecoverable failures. +enum CmuxConfigError: Error, Equatable { + case invalidYaml(details: String) + case fileNotReadable(path: String) +} + +/// Non-fatal warnings during `.cmux.yaml` parsing. +/// The config is still applied, but with the warned items degraded. +enum CmuxConfigWarning: Equatable { + /// A referenced startup script was not found in the script repository. + case scriptNotFound(name: String) + /// A sub-group tried to nest groups beyond the 2-level limit. + case maxDepthExceeded(groupName: String) +} + +/// Result of parsing a `.cmux.yaml` file. +/// Contains the project definition plus any non-fatal warnings. +struct ConfigParseResult { + let projectName: String + let projectColor: String? + let warnings: [CmuxConfigWarning] + /// Tab definitions with their startup script names (to be resolved later). + let tabDefinitions: [ConfigTabDefinition] +} + +/// A tab definition from `.cmux.yaml`, not yet resolved to a workspace. +struct ConfigTabDefinition { + let title: String + let startupScript: String? + let groupPath: [String] // empty = top-level, ["sub"] = inside sub-group "sub" +} diff --git a/Sources/CmuxConfigParser.swift b/Sources/CmuxConfigParser.swift new file mode 100644 index 000000000000..9594be794754 --- /dev/null +++ b/Sources/CmuxConfigParser.swift @@ -0,0 +1,261 @@ +import Foundation + +/// Protocol for script existence checking, injectable for testing. +protocol ScriptRepositoryProtocol { + func hasScript(named name: String) -> Bool +} + +/// Parses `.cmux.yaml` project configuration files. +/// Returns a `ConfigParseResult` with best-effort parsed group and any warnings. +/// Throws `CmuxConfigError` for fatal parse errors (invalid YAML syntax). +enum CmuxConfigParser { + + /// Parse a YAML string into a workspace group definition. + /// - Parameters: + /// - yaml: The raw YAML content + /// - projectDirectory: The project root URL (for resolving relative paths) + /// - scriptRepository: Optional script repo for validating script references + /// - Returns: ConfigParseResult with the parsed group tree and warnings + /// - Throws: CmuxConfigError.invalidYaml for fatal parse failures + @MainActor + static func parse( + yaml: String, + projectDirectory: URL, + scriptRepository: ScriptRepositoryProtocol? = nil + ) throws -> ConfigParseResult { + let lines = yaml.components(separatedBy: .newlines) + var warnings: [CmuxConfigWarning] = [] + + let topLevel = try parseTopLevelMap(lines: lines) + + let name = topLevel["name"] ?? projectDirectory.lastPathComponent + let color = topLevel["color"] + + // Parse top-level tabs + var tabDefs: [ConfigTabDefinition] = [] + let topTabs = try parseTabsList( + from: topLevel, + key: "tabs", + lines: lines, + groupPath: [], + scriptRepository: scriptRepository, + warnings: &warnings + ) + tabDefs.append(contentsOf: topTabs) + + // Parse groups (legacy groups become additional tab definitions) + _ = try parseGroupsList( + lines: lines, + projectDirectory: projectDirectory, + scriptRepository: scriptRepository, + warnings: &warnings, + tabDefs: &tabDefs, + currentDepth: 1 + ) + + return ConfigParseResult( + projectName: name, + projectColor: color, + warnings: warnings, + tabDefinitions: tabDefs + ) + } + + // MARK: - Private Parsing Helpers + + /// Extracts top-level key-value pairs from simple YAML. + private static func parseTopLevelMap(lines: [String]) throws -> [String: String] { + var result: [String: String] = [:] + for line in lines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty, !trimmed.hasPrefix("#") else { continue } + // Only parse top-level (no leading whitespace) key: value pairs + guard !line.hasPrefix(" "), !line.hasPrefix("\t") else { continue } + guard let colonIdx = trimmed.firstIndex(of: ":") else { continue } + let key = String(trimmed[trimmed.startIndex.. [ConfigTabDefinition] { + var defs: [ConfigTabDefinition] = [] + var inSection = false + var sectionIndent = 0 + var entryIndent = 0 + var currentEntryLines: [String] = [] + + func flushEntry() { + guard !currentEntryLines.isEmpty else { return } + if let tabDef = parseTabEntry( + entryLines: currentEntryLines, + groupPath: groupPath, + scriptRepository: scriptRepository, + warnings: &warnings + ) { + defs.append(tabDef) + } + currentEntryLines = [] + } + + for line in lines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { continue } + + let indent = line.prefix(while: { $0 == " " }).count + + if !inSection { + if trimmed == "\(key):" || trimmed.hasPrefix("\(key):") { + inSection = true + sectionIndent = indent + } + continue + } + + // We're inside the tabs section + if indent <= sectionIndent && !trimmed.hasPrefix("-") { + break // Left the section + } + + if trimmed.hasPrefix("- ") { + flushEntry() + currentEntryLines.append(String(trimmed.dropFirst(2))) + entryIndent = indent + } else if indent > entryIndent { + // Continuation line for current entry + currentEntryLines.append(trimmed) + } + } + flushEntry() + return defs + } + + static func parseTabEntry( + entryLines: [String], + groupPath: [String], + scriptRepository: ScriptRepositoryProtocol?, + warnings: inout [CmuxConfigWarning] + ) -> ConfigTabDefinition? { + var title: String? + var startupScript: String? + + for line in entryLines { + guard let colonIdx = line.firstIndex(of: ":") else { continue } + let key = String(line[line.startIndex.. [String] { + var groupNames: [String] = [] + var inGroupsSection = false + var groupsSectionIndent = 0 + var currentGroupName: String? + var currentGroupDir: String? + var currentGroupLines: [String] = [] + + func finalizeGroup() { + guard let name = currentGroupName else { return } + let groupTabs = parseGroupTabs( + groupLines: currentGroupLines, + groupName: name, + scriptRepository: scriptRepository, + warnings: &warnings + ) + tabDefs.append(contentsOf: groupTabs) + groupNames.append(name) + currentGroupName = nil + currentGroupDir = nil + currentGroupLines = [] + } + + for line in lines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { continue } + + let indent = line.prefix(while: { $0 == " " }).count + + if !inGroupsSection { + if trimmed == "groups:" { + inGroupsSection = true + groupsSectionIndent = indent + } + continue + } + + if indent <= groupsSectionIndent && !trimmed.hasPrefix("-") && trimmed != "groups:" { + finalizeGroup() + break + } + + if trimmed.hasPrefix("- name:") { + finalizeGroup() + currentGroupName = extractValue(from: trimmed, key: "- name") + } else if trimmed.hasPrefix("workingDirectory:") { + currentGroupDir = extractValue(from: trimmed, key: "workingDirectory") + } else if trimmed == "groups:" && indent > groupsSectionIndent { + if let name = currentGroupName { + warnings.append(.maxDepthExceeded(groupName: name)) + } + } + currentGroupLines.append(line) + } + finalizeGroup() + + return groupNames + } + + private static func extractValue(from line: String, key: String) -> String? { + guard let colonIdx = line.range(of: ":") else { return nil } + let value = String(line[colonIdx.upperBound...]).trimmingCharacters(in: .whitespaces) + return value.isEmpty ? nil : value.trimmingCharacters(in: CharacterSet(charactersIn: "\"'")) + } + + private static func resolveWorkingDirectory( + _ relative: String?, + projectDirectory: URL + ) -> URL { + guard let relative, !relative.isEmpty else { return projectDirectory } + let cleaned = relative.hasPrefix("./") ? String(relative.dropFirst(2)) : relative + return projectDirectory.appendingPathComponent(cleaned) + } +} diff --git a/Sources/CmuxConfigParserGroups.swift b/Sources/CmuxConfigParserGroups.swift new file mode 100644 index 000000000000..ea2f2df38633 --- /dev/null +++ b/Sources/CmuxConfigParserGroups.swift @@ -0,0 +1,60 @@ +import Foundation + +/// Group and tab-within-group parsing helpers for CmuxConfigParser. +extension CmuxConfigParser { + + /// Extract tabs from lines belonging to a single group entry. + static func parseGroupTabs( + groupLines: [String], + groupName: String, + scriptRepository: ScriptRepositoryProtocol?, + warnings: inout [CmuxConfigWarning] + ) -> [ConfigTabDefinition] { + var defs: [ConfigTabDefinition] = [] + var inTabs = false + var tabsSectionIndent = 0 + var entryIndent = 0 + var currentEntryLines: [String] = [] + + func flushEntry() { + guard !currentEntryLines.isEmpty else { return } + if let tabDef = parseTabEntry( + entryLines: currentEntryLines, + groupPath: [groupName], + scriptRepository: scriptRepository, + warnings: &warnings + ) { + defs.append(tabDef) + } + currentEntryLines = [] + } + + for line in groupLines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { continue } + let indent = line.prefix(while: { $0 == " " }).count + + if !inTabs { + if trimmed == "tabs:" { + inTabs = true + tabsSectionIndent = indent + } + continue + } + + if indent <= tabsSectionIndent && !trimmed.hasPrefix("-") { + break + } + + if trimmed.hasPrefix("- ") { + flushEntry() + currentEntryLines.append(String(trimmed.dropFirst(2))) + entryIndent = indent + } else if indent > entryIndent { + currentEntryLines.append(trimmed) + } + } + flushEntry() + return defs + } +} diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 15d51723175f..75382fb696d2 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -7,17 +7,7 @@ import ObjectiveC import UniformTypeIdentifiers import WebKit -private extension Color { - init?(hex: String) { - let hex = hex.trimmingCharacters(in: .init(charactersIn: "#")) - guard hex.count == 6, let value = UInt64(hex, radix: 16) else { return nil } - self.init( - red: Double((value >> 16) & 0xFF) / 255.0, - green: Double((value >> 8) & 0xFF) / 255.0, - blue: Double( value & 0xFF) / 255.0 - ) - } -} +// Color(hex:) extension is defined in GroupHeaderView.swift (module-scoped) private func coloredCircleImage(color: NSColor) -> NSImage { let size = NSSize(width: 14, height: 14) @@ -2200,7 +2190,7 @@ struct ContentView: View { anchorView: fullscreenControlsViewModel.notificationsAnchorView ) }, - onNewTab: { tabManager.addTab() }, + onNewTab: { addTab() }, visibilityMode: .alwaysVisible ) } @@ -3152,7 +3142,7 @@ struct ContentView: View { } private func addTab() { - tabManager.addTab() + guard tabManager.addWorkspaceViaDialog() != nil else { return } sidebarSelectionState.selection = .tabs } @@ -8217,49 +8207,31 @@ struct VerticalTabsSidebar: View { .frame(height: trafficLightPadding) LazyVStack(spacing: tabRowSpacing) { - ForEach(Array(tabManager.tabs.enumerated()), id: \.element.id) { index, tab in - let selectedContextIds: Set = selectedTabIds.contains(tab.id) ? selectedTabIds : [tab.id] - let contextTargetIds = tabManager.tabs.compactMap { workspace in - selectedContextIds.contains(workspace.id) ? workspace.id : nil - } - let remoteContextMenuTargets = tabManager.tabs.filter { workspace in - contextTargetIds.contains(workspace.id) && workspace.isRemoteWorkspace + let visibleWorkspaces = tabManager.groupManager.visibleWorkspaces() + let visibleCount = visibleWorkspaces.count + ForEach(tabManager.items, id: \.self) { wsId in + if let tab = tabManager.workspace(for: wsId) { + let visibleIndex = visibleWorkspaces.firstIndex(where: { $0.id == wsId }) ?? 0 + sidebarTabItemView( + tab: tab, + visibleIndex: visibleIndex, + visibleCount: visibleCount, + workspaceCount: workspaceCount, + canCloseWorkspace: canCloseWorkspace, + depth: 0 + ) + if tab.hasChildren && !tab.isCollapsed { + sidebarChildWorkspaces( + parentIds: tab.childWorkspaceIds, + depth: 1, + visibleWorkspaces: visibleWorkspaces, + visibleCount: visibleCount, + workspaceCount: workspaceCount, + canCloseWorkspace: canCloseWorkspace, + parentCustomColorHex: tab.customColor + ) + } } - TabItemView( - tabManager: tabManager, - notificationStore: notificationStore, - tab: tab, - index: index, - isActive: tabManager.selectedTabId == tab.id, - workspaceShortcutDigit: WorkspaceShortcutMapper.commandDigitForWorkspace( - at: index, - workspaceCount: workspaceCount - ), - canCloseWorkspace: canCloseWorkspace, - accessibilityWorkspaceCount: workspaceCount, - unreadCount: notificationStore.unreadCount(forTabId: tab.id), - latestNotificationText: { - guard showsSidebarNotificationMessage, - let notification = notificationStore.latestNotification(forTabId: tab.id) else { - return nil - } - let text = notification.body.isEmpty ? notification.title : notification.body - let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? nil : trimmed - }(), - rowSpacing: tabRowSpacing, - setSelectionToTabs: { selection = .tabs }, - selectedTabIds: $selectedTabIds, - lastSidebarSelectionIndex: $lastSidebarSelectionIndex, - showsModifierShortcutHints: modifierKeyMonitor.isModifierPressed, - dragAutoScrollController: dragAutoScrollController, - draggedTabId: $draggedTabId, - dropIndicator: $dropIndicator, - remoteContextMenuWorkspaceIds: remoteContextMenuTargets.map(\.id), - allRemoteContextMenuTargetsConnecting: !remoteContextMenuTargets.isEmpty && remoteContextMenuTargets.allSatisfy { $0.remoteConnectionState == .connecting }, - allRemoteContextMenuTargetsDisconnected: !remoteContextMenuTargets.isEmpty && remoteContextMenuTargets.allSatisfy { $0.remoteConnectionState == .disconnected } - ) - .equatable() } } .padding(.vertical, 8) @@ -8364,6 +8336,112 @@ struct VerticalTabsSidebar: View { .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } + // MARK: - Group-Aware Sidebar Helpers + + @ViewBuilder + private func sidebarTabItemView( + tab: Workspace, + visibleIndex: Int, + visibleCount: Int, + workspaceCount: Int, + canCloseWorkspace: Bool, + depth: Int, + parentCustomColorHex: String? = nil + ) -> some View { + let selectedContextIds: Set = selectedTabIds.contains(tab.id) ? selectedTabIds : [tab.id] + let contextTargetIds = tabManager.tabs.compactMap { workspace in + selectedContextIds.contains(workspace.id) ? workspace.id : nil + } + let remoteContextMenuTargets = tabManager.tabs.filter { workspace in + contextTargetIds.contains(workspace.id) && workspace.isRemoteWorkspace + } + TabItemView( + tabManager: tabManager, + notificationStore: notificationStore, + tab: tab, + index: visibleIndex, + isActive: tabManager.selectedTabId == tab.id, + workspaceShortcutDigit: WorkspaceShortcutMapper.commandDigitForWorkspace( + at: visibleIndex, + workspaceCount: visibleCount + ), + canCloseWorkspace: canCloseWorkspace, + accessibilityWorkspaceCount: workspaceCount, + unreadCount: notificationStore.unreadCount(forTabId: tab.id), + latestNotificationText: { + guard showsSidebarNotificationMessage, + let notification = notificationStore.latestNotification(forTabId: tab.id) else { + return nil + } + let text = notification.body.isEmpty ? notification.title : notification.body + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + }(), + rowSpacing: tabRowSpacing, + setSelectionToTabs: { selection = .tabs }, + selectedTabIds: $selectedTabIds, + lastSidebarSelectionIndex: $lastSidebarSelectionIndex, + showsModifierShortcutHints: modifierKeyMonitor.isModifierPressed, + dragAutoScrollController: dragAutoScrollController, + draggedTabId: $draggedTabId, + dropIndicator: $dropIndicator, + remoteContextMenuWorkspaceIds: remoteContextMenuTargets.map(\.id), + allRemoteContextMenuTargetsConnecting: !remoteContextMenuTargets.isEmpty && remoteContextMenuTargets.allSatisfy { $0.remoteConnectionState == .connecting }, + allRemoteContextMenuTargetsDisconnected: !remoteContextMenuTargets.isEmpty && remoteContextMenuTargets.allSatisfy { $0.remoteConnectionState == .disconnected }, + depth: depth, + hasChildren: tab.hasChildren, + isCollapsed: tab.isCollapsed, + parentCustomColorHex: parentCustomColorHex, + hasStartupCommand: tab.startupCommand != nil + ) + .equatable() + } + + /// Renders child workspaces (max 3 levels deep, no recursion needed). + @ViewBuilder + private func sidebarChildWorkspaces( + parentIds: [UUID], + depth: Int, + visibleWorkspaces: [Workspace], + visibleCount: Int, + workspaceCount: Int, + canCloseWorkspace: Bool, + parentCustomColorHex: String? + ) -> some View { + ForEach(parentIds, id: \.self) { childId in + if let childTab = tabManager.workspace(for: childId) { + let visibleIndex = visibleWorkspaces.firstIndex(where: { $0.id == childId }) ?? 0 + sidebarTabItemView( + tab: childTab, + visibleIndex: visibleIndex, + visibleCount: visibleCount, + workspaceCount: workspaceCount, + canCloseWorkspace: canCloseWorkspace, + depth: depth, + parentCustomColorHex: parentCustomColorHex + ) + // Level 3 children (depth+1 == 2 means grandchildren at depth 3) + if childTab.hasChildren && !childTab.isCollapsed { + let grandparentColorHex = childTab.customColor ?? parentCustomColorHex + ForEach(childTab.childWorkspaceIds, id: \.self) { grandchildId in + if let grandchildTab = tabManager.workspace(for: grandchildId) { + let gcIndex = visibleWorkspaces.firstIndex(where: { $0.id == grandchildId }) ?? 0 + sidebarTabItemView( + tab: grandchildTab, + visibleIndex: gcIndex, + visibleCount: visibleCount, + workspaceCount: workspaceCount, + canCloseWorkspace: canCloseWorkspace, + depth: depth + 1, + parentCustomColorHex: grandparentColorHex + ) + } + } + } + } + } + } + private func debugShortSidebarTabId(_ id: UUID?) -> String { guard let id else { return "nil" } return String(id.uuidString.prefix(5)) @@ -10519,6 +10597,33 @@ private struct SidebarEmptyArea: View { .offset(y: -(rowSpacing / 2)) } } + .contextMenu { + let templates = TemplateRepository.shared.listTemplates() + Menu(String(localized: "contextMenu.openTemplate", defaultValue: "Open Template")) { + ForEach(templates, id: \.self) { templateName in + Button(templateName) { + let panel = NSOpenPanel() + panel.canChooseDirectories = true + panel.canChooseFiles = false + panel.allowsMultipleSelection = false + panel.prompt = String(localized: "dialog.openTemplate.open", defaultValue: "Open") + guard panel.runModal() == .OK, let url = panel.url else { return } + if let template = try? TemplateRepository.shared.getTemplate(named: templateName) { + tabManager.openTemplate(template, directory: url.path) + } + } + } + if !templates.isEmpty { + Divider() + } + Button(String(localized: "contextMenu.openTemplatesFolder", defaultValue: "Open Templates Folder…")) { + NSWorkspace.shared.open(TemplateRepository.shared.directory) + } + } + Button(String(localized: "contextMenu.newWorkspace", defaultValue: "New Workspace")) { + tabManager.addWorkspaceViaDialog() + } + } } private var shouldShowTopDropIndicator: Bool { @@ -10645,7 +10750,12 @@ private struct TabItemView: View, Equatable { lhs.showsModifierShortcutHints == rhs.showsModifierShortcutHints && lhs.remoteContextMenuWorkspaceIds == rhs.remoteContextMenuWorkspaceIds && lhs.allRemoteContextMenuTargetsConnecting == rhs.allRemoteContextMenuTargetsConnecting && - lhs.allRemoteContextMenuTargetsDisconnected == rhs.allRemoteContextMenuTargetsDisconnected + lhs.allRemoteContextMenuTargetsDisconnected == rhs.allRemoteContextMenuTargetsDisconnected && + lhs.depth == rhs.depth && + lhs.hasChildren == rhs.hasChildren && + lhs.isCollapsed == rhs.isCollapsed && + lhs.parentCustomColorHex == rhs.parentCustomColorHex && + lhs.hasStartupCommand == rhs.hasStartupCommand } // Use plain references instead of @EnvironmentObject to avoid subscribing @@ -10673,6 +10783,11 @@ private struct TabItemView: View, Equatable { let remoteContextMenuWorkspaceIds: [UUID] let allRemoteContextMenuTargetsConnecting: Bool let allRemoteContextMenuTargetsDisconnected: Bool + var depth: Int = 0 + var hasChildren: Bool = false + var isCollapsed: Bool = false + var parentCustomColorHex: String? + var hasStartupCommand: Bool = false @State private var isHovering = false @State private var rowHeight: CGFloat = 1 @AppStorage(ShortcutHintDebugSettings.sidebarHintXKey) private var sidebarShortcutHintXOffset = ShortcutHintDebugSettings.defaultSidebarHintX @@ -10712,7 +10827,9 @@ private struct TabItemView: View, Equatable { } private var showsLeadingRail: Bool { - explicitRailColor != nil + // Hide the rail for children that have a parent color card background + if resolvedCardColor != nil && !isActive { return false } + return explicitRailColor != nil } private var activeBorderLineWidth: CGFloat { @@ -10927,6 +11044,18 @@ private struct TabItemView: View, Equatable { VStack(alignment: .leading, spacing: 4) { HStack(spacing: 8) { + if hasChildren { + Image(systemName: "chevron.right") + .font(.system(size: 9, weight: .bold)) + .rotationEffect(.degrees(isCollapsed ? 0 : 90)) + .foregroundColor(.secondary) + .frame(width: 12, height: 12) + .contentShape(Rectangle()) + .onTapGesture { + tabManager.toggleWorkspaceCollapsed(tab.id) + } + } + if unreadCount > 0 { ZStack { Circle() @@ -10944,6 +11073,13 @@ private struct TabItemView: View, Equatable { .foregroundColor(activeSecondaryColor(0.8)) } + if hasStartupCommand { + Image(systemName: "bolt.fill") + .font(.system(size: 8)) + .foregroundColor(activeSecondaryColor(0.6)) + .accessibilityLabel(String(localized: "accessibility.startupCommand", defaultValue: "Has startup command")) + } + Text(tab.title) .font(.system(size: 12.5, weight: titleFontWeight)) .foregroundColor(activePrimaryTextColor) @@ -11178,6 +11314,7 @@ private struct TabItemView: View, Equatable { } ) .padding(.horizontal, 6) + .padding(.leading, CGFloat(depth) * 16) .background { GeometryReader { proxy in Color.clear @@ -11383,6 +11520,31 @@ private struct TabItemView: View, Equatable { Divider() + runScriptSubmenu + + if depth < 2 { + Button(String(localized: "contextMenu.addChildWorkspace", defaultValue: "Add Child Workspace")) { + tabManager.addChildWorkspace(for: tab.id) + } + } + + Button(String(localized: "contextMenu.makeChild", defaultValue: "Make Child")) { + if tabManager.groupManager.indentWorkspace(tab.id) { + tabManager.items = tabManager.groupManager.items + } + } + .disabled(!canMakeChild) + + if depth > 0 { + Button(String(localized: "contextMenu.raiseLevel", defaultValue: "Raise Level")) { + if tabManager.groupManager.outdentWorkspace(tab.id) { + tabManager.items = tabManager.groupManager.items + } + } + } + + Divider() + Button(String(localized: "contextMenu.moveUp", defaultValue: "Move Up")) { moveBy(-1) } @@ -11469,8 +11631,13 @@ private struct TabItemView: View, Equatable { private var backgroundColor: Color { switch activeTabIndicatorStyle { case .leftRail: + // Active/selected always gets standard blue selection if isActive { return Color(nsColor: sidebarSelectedWorkspaceBackgroundNSColor(for: colorScheme)) } if isMultiSelected { return cmuxAccentColor().opacity(0.25) } + // At rest: children of a colored parent show parent color as card background + if let parentColor = resolvedCardColor { + return parentColor.opacity(colorScheme == .dark ? 0.55 : 0.40) + } return Color.clear case .solidFill: if isActive { return Color(nsColor: sidebarSelectedWorkspaceBackgroundNSColor(for: colorScheme)) } @@ -11479,6 +11646,10 @@ private struct TabItemView: View, Equatable { return custom.opacity(0.7) } if isMultiSelected { return cmuxAccentColor().opacity(0.25) } + // At rest: children of a colored parent show parent color as card background + if let parentColor = resolvedCardColor { + return parentColor.opacity(colorScheme == .dark ? 0.55 : 0.40) + } return Color.clear } } @@ -11504,6 +11675,25 @@ private struct TabItemView: View, Equatable { ) } + /// Color for the card background: workspace's own color first, then parent's color as fallback. + private var resolvedCardColor: Color? { + // Own color takes priority + if let ownHex = tab.customColor { + return WorkspaceTabColorSettings.displayColor( + hex: ownHex, + colorScheme: colorScheme, + forceBright: false + ) + } + // Fall back to parent's color only for children + guard depth > 0, let hex = parentCustomColorHex else { return nil } + return WorkspaceTabColorSettings.displayColor( + hex: hex, + colorScheme: colorScheme, + forceBright: false + ) + } + private func tabColorSwatchColor(for hex: String) -> NSColor { WorkspaceTabColorSettings.displayNSColor( hex: hex, @@ -11527,6 +11717,25 @@ private struct TabItemView: View, Equatable { return tabManager.tabs[currentIndex - 1].id == indicator.tabId } + /// Whether this workspace can be nested under the sibling above it. + private var canMakeChild: Bool { + // Check depth constraint (max 3 levels) + let currentDepth = tabManager.groupManager.depthOf(workspaceId: tab.id) + guard currentDepth < 3 else { return false } + // Must have a sibling above at the same level to nest under + if currentDepth <= 1 { + // Top-level: check if there's a top-level item above this one + guard let idx = tabManager.groupManager.items.firstIndex(of: tab.id), + idx > 0 else { return false } + } else { + // Child: check if there's a sibling above in the parent's children + guard let parent = tabManager.groupManager.parentWorkspace(of: tab.id), + let idx = parent.childWorkspaceIds.firstIndex(of: tab.id), + idx > 0 else { return false } + } + return true + } + private var accessibilityTitle: String { String(localized: "accessibility.workspacePosition", defaultValue: "\(tab.title), workspace \(index + 1) of \(accessibilityWorkspaceCount)") } @@ -12078,6 +12287,61 @@ private struct TabItemView: View, Equatable { guard response == .alertFirstButtonReturn else { return } tabManager.setCustomTitle(tabId: tab.id, title: input.stringValue) } + + @ViewBuilder + private var runScriptSubmenu: some View { + let isAtPrompt = tab.isFocusedPanelAtPrompt + let scripts = ScriptRepository.shared.listScripts() + Menu(String(localized: "contextMenu.runScript", defaultValue: "Run Script")) { + ForEach(scripts, id: \.self) { scriptName in + Button(scriptName) { + runScriptInTerminal(named: scriptName) + } + } + if !scripts.isEmpty { + Divider() + } + Button(String(localized: "contextMenu.openScriptsFolder", defaultValue: "Open Scripts Folder…")) { + NSWorkspace.shared.open(ScriptRepository.shared.directory) + } + } + .disabled(!isAtPrompt) + } + + private func runScriptInTerminal(named scriptName: String) { + guard let scriptContent = ScriptRepository.shared.getScript(named: scriptName), + let terminalPanel = tab.focusedTerminalPanel else { return } + let lines = StartupScriptRunner.prepareScriptLines(scriptContent) + guard !lines.isEmpty else { return } + let text = lines.joined(separator: "\n") + "\n" + terminalPanel.sendInteractiveText(text) + } + + @ViewBuilder + private var templatesSubmenu: some View { + let hasTerminal = tab.focusedTerminalPanel != nil + let templates = TemplateRepository.shared.listTemplates() + Menu(String(localized: "contextMenu.openTemplate", defaultValue: "Open Template")) { + ForEach(templates, id: \.self) { templateName in + Button(templateName) { + openTemplateInWorkspace(named: templateName) + } + } + if !templates.isEmpty { + Divider() + } + Button(String(localized: "contextMenu.openTemplatesFolder", defaultValue: "Open Templates Folder…")) { + NSWorkspace.shared.open(TemplateRepository.shared.directory) + } + } + .disabled(!hasTerminal) + } + + private func openTemplateInWorkspace(named templateName: String) { + guard let template = try? TemplateRepository.shared.getTemplate(named: templateName) else { return } + let directory = tab.currentDirectory + tabManager.openTemplate(template, directory: directory) + } } private struct SidebarMetadataRows: View { diff --git a/Sources/GroupHeaderView.swift b/Sources/GroupHeaderView.swift new file mode 100644 index 000000000000..97228d437ecd --- /dev/null +++ b/Sources/GroupHeaderView.swift @@ -0,0 +1,17 @@ +// This file is intentionally empty. GroupHeaderView has been replaced by +// collapse chevron rendering directly in TabItemView. +// The file remains to avoid Xcode project reference errors until cleanup. + +import SwiftUI + +extension Color { + init?(hex: String) { + let hex = hex.trimmingCharacters(in: .init(charactersIn: "#")) + guard hex.count == 6, let value = UInt64(hex, radix: 16) else { return nil } + self.init( + red: Double((value >> 16) & 0xFF) / 255.0, + green: Double((value >> 8) & 0xFF) / 255.0, + blue: Double( value & 0xFF) / 255.0 + ) + } +} diff --git a/Sources/GroupItem.swift b/Sources/GroupItem.swift new file mode 100644 index 000000000000..86f9492a7290 --- /dev/null +++ b/Sources/GroupItem.swift @@ -0,0 +1,6 @@ +import Foundation + +/// A top-level sidebar entry is simply a workspace UUID. +/// Workspaces that have children render their own collapse chevron and +/// indented child list — no separate group container is needed. +typealias SidebarItem = UUID diff --git a/Sources/MonospaceTextEditor.swift b/Sources/MonospaceTextEditor.swift new file mode 100644 index 000000000000..4200aa1a0c5e --- /dev/null +++ b/Sources/MonospaceTextEditor.swift @@ -0,0 +1,51 @@ +import AppKit +import SwiftUI + +/// NSViewRepresentable wrapper around NSTextView configured for monospace text editing. +/// Used by Template Manager and Script Manager for YAML/script editing. +struct MonospaceTextEditor: NSViewRepresentable { + let text: String + let onChange: (String) -> Void + + func makeNSView(context: Context) -> NSScrollView { + let scrollView = NSTextView.scrollableTextView() + guard let textView = scrollView.documentView as? NSTextView else { + return scrollView + } + textView.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular) + textView.isAutomaticQuoteSubstitutionEnabled = false + textView.isAutomaticDashSubstitutionEnabled = false + textView.isAutomaticTextReplacementEnabled = false + textView.isRichText = false + textView.allowsUndo = true + textView.delegate = context.coordinator + textView.string = text + return scrollView + } + + func updateNSView(_ nsView: NSScrollView, context: Context) { + guard let textView = nsView.documentView as? NSTextView else { return } + if textView.string != text { + let selectedRanges = textView.selectedRanges + textView.string = text + textView.selectedRanges = selectedRanges + } + } + + func makeCoordinator() -> Coordinator { + Coordinator(onChange: onChange) + } + + final class Coordinator: NSObject, NSTextViewDelegate { + let onChange: (String) -> Void + + init(onChange: @escaping (String) -> Void) { + self.onChange = onChange + } + + func textDidChange(_ notification: Notification) { + guard let textView = notification.object as? NSTextView else { return } + onChange(textView.string) + } + } +} diff --git a/Sources/NewWorkspaceDialog.swift b/Sources/NewWorkspaceDialog.swift new file mode 100644 index 000000000000..0c15daf75963 --- /dev/null +++ b/Sources/NewWorkspaceDialog.swift @@ -0,0 +1,84 @@ +import AppKit +import Foundation + +/// Presents the "New Workspace" dialog with directory picker and template selection. +/// Returns the user's choices, or nil if cancelled. +@MainActor +enum NewWorkspaceDialog { + + struct Result { + let directory: String + let templateName: String? + } + + /// Shows the new-workspace dialog. Returns nil if cancelled. + static func run() -> Result? { + let panel = NSOpenPanel() + panel.canChooseDirectories = true + panel.canChooseFiles = false + panel.allowsMultipleSelection = false + panel.canCreateDirectories = true + panel.prompt = String( + localized: "newWorkspaceDialog.open", + defaultValue: "Open" + ) + panel.message = String( + localized: "newWorkspaceDialog.message", + defaultValue: "Choose a directory for the new workspace." + ) + + let templates = TemplateRepository.shared.listTemplates() + let accessory = buildAccessoryView(templates: templates) + + panel.accessoryView = accessory.container + panel.isAccessoryViewDisclosed = true + + let response = panel.runModal() + guard response == .OK, let url = panel.url else { return nil } + + let selectedIndex = accessory.popup.indexOfSelectedItem + let templateName: String? = selectedIndex == 0 ? nil : templates[selectedIndex - 1] + + return Result(directory: url.path, templateName: templateName) + } + + // MARK: - Private + + private struct AccessoryViews { + let container: NSView + let popup: NSPopUpButton + } + + private static func buildAccessoryView(templates: [String]) -> AccessoryViews { + let container = NSView(frame: NSRect(x: 0, y: 0, width: 340, height: 36)) + + let label = NSTextField(labelWithString: String( + localized: "newWorkspaceDialog.templateLabel", + defaultValue: "Template:" + )) + label.translatesAutoresizingMaskIntoConstraints = false + container.addSubview(label) + + let popup = NSPopUpButton(frame: .zero, pullsDown: false) + popup.translatesAutoresizingMaskIntoConstraints = false + popup.addItem(withTitle: String( + localized: "newWorkspaceDialog.noTemplate", + defaultValue: "None (plain terminal)" + )) + for template in templates { + popup.addItem(withTitle: template) + } + container.addSubview(popup) + + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 12), + label.centerYAnchor.constraint(equalTo: container.centerYAnchor), + popup.leadingAnchor.constraint(equalTo: label.trailingAnchor, constant: 8), + popup.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -12), + popup.centerYAnchor.constraint(equalTo: container.centerYAnchor), + popup.widthAnchor.constraint(greaterThanOrEqualToConstant: 200), + ]) + + return AccessoryViews(container: container, popup: popup) + } +} diff --git a/Sources/Panels/TerminalPanel.swift b/Sources/Panels/TerminalPanel.swift index 3df74b9c4bb7..ff6fc9504bec 100644 --- a/Sources/Panels/TerminalPanel.swift +++ b/Sources/Panels/TerminalPanel.swift @@ -1,6 +1,7 @@ import Foundation import Combine import AppKit +import Carbon.HIToolbox import Bonsplit /// TerminalPanel wraps an existing TerminalSurface and conforms to the Panel protocol. @@ -182,6 +183,55 @@ final class TerminalPanel: Panel, ObservableObject { surface.sendText(text) } + /// Send text as interactive terminal input, properly handling control characters + /// (\r as Enter, \t as Tab, \x1b as Escape, etc.) via Ghostty key events. + /// This is the correct path for commands, scripts, and automation — NOT raw PTY writes. + func sendInteractiveText(_ text: String) { + guard let ghosttySurface = surface.surface else { + // Surface not initialized yet — fall back to raw sendText + surface.sendText(text) + return + } + let chunks = TerminalController.socketTextChunks(text) + for chunk in chunks { + switch chunk { + case .text(let value): + var keyEvent = ghostty_input_key_s() + keyEvent.action = GHOSTTY_ACTION_PRESS + keyEvent.keycode = 0 + keyEvent.mods = GHOSTTY_MODS_NONE + keyEvent.consumed_mods = GHOSTTY_MODS_NONE + keyEvent.unshifted_codepoint = 0 + keyEvent.composing = false + value.withCString { ptr in + keyEvent.text = ptr + _ = ghostty_surface_key(ghosttySurface, keyEvent) + } + case .control(let scalar): + var keyEvent = ghostty_input_key_s() + keyEvent.action = GHOSTTY_ACTION_PRESS + keyEvent.mods = GHOSTTY_MODS_NONE + keyEvent.consumed_mods = GHOSTTY_MODS_NONE + keyEvent.unshifted_codepoint = 0 + keyEvent.composing = false + keyEvent.text = nil + switch scalar.value { + case 0x0A, 0x0D: + keyEvent.keycode = UInt32(kVK_Return) + case 0x09: + keyEvent.keycode = UInt32(kVK_Tab) + case 0x1B: + keyEvent.keycode = UInt32(kVK_Escape) + case 0x7F: + keyEvent.keycode = UInt32(kVK_Delete) + default: + continue + } + _ = ghostty_surface_key(ghosttySurface, keyEvent) + } + } + } + func performBindingAction(_ action: String) -> Bool { surface.performBindingAction(action) } diff --git a/Sources/ScriptManagerViewModel.swift b/Sources/ScriptManagerViewModel.swift new file mode 100644 index 000000000000..bb1410d49612 --- /dev/null +++ b/Sources/ScriptManagerViewModel.swift @@ -0,0 +1,101 @@ +import Foundation + +/// View model for the Script Manager window. +/// Manages script list, selection, and editing state. +@MainActor +final class ScriptManagerViewModel: ObservableObject { + @Published var scriptNames: [String] = [] + @Published var selectedName: String? + @Published var editorText: String = "" + @Published private(set) var isDirty: Bool = false + + private var loadedText: String = "" + private let repo = ScriptRepository.shared + + func reload() { + scriptNames = repo.listScripts() + if let selected = selectedName, scriptNames.contains(selected) { + loadScript(named: selected) + } else if let first = scriptNames.first { + selectScript(named: first) + } else { + selectedName = nil + editorText = "" + loadedText = "" + isDirty = false + } + } + + func selectScript(named name: String) { + selectedName = name + loadScript(named: name) + } + + func save() { + guard let name = selectedName else { return } + try? repo.saveScript(named: name, content: editorText) + loadedText = editorText + isDirty = false + } + + func revert() { + guard let name = selectedName else { return } + loadScript(named: name) + } + + func addScript() { + var baseName = String( + localized: "scriptManager.newScriptName", + defaultValue: "New Script" + ) + var counter = 1 + while repo.hasScript(named: baseName) { + counter += 1 + baseName = String( + localized: "scriptManager.newScriptNameNumbered", + defaultValue: "New Script \(counter)" + ) + } + let defaultContent = "#!/bin/bash\n# New script\n" + try? repo.saveScript(named: baseName, content: defaultContent) + reload() + selectScript(named: baseName) + } + + func duplicateSelected() { + guard let name = selectedName, + let content = repo.getScript(named: name) else { return } + var copyName = "\(name) Copy" + var counter = 1 + while repo.hasScript(named: copyName) { + counter += 1 + copyName = "\(name) Copy \(counter)" + } + try? repo.saveScript(named: copyName, content: content) + reload() + selectScript(named: copyName) + } + + func deleteSelected() { + guard let name = selectedName else { return } + try? repo.deleteScript(named: name) + selectedName = nil + editorText = "" + loadedText = "" + isDirty = false + reload() + } + + func textDidChange(_ newText: String) { + editorText = newText + isDirty = newText != loadedText + } + + // MARK: - Private + + private func loadScript(named name: String) { + editorText = repo.getScript(named: name) ?? "" + loadedText = editorText + isDirty = false + } +} diff --git a/Sources/ScriptManagerWindow.swift b/Sources/ScriptManagerWindow.swift new file mode 100644 index 000000000000..b24b8818d4da --- /dev/null +++ b/Sources/ScriptManagerWindow.swift @@ -0,0 +1,225 @@ +import AppKit +import SwiftUI + +// MARK: - Window Controller + +@MainActor +final class ScriptManagerWindowController: NSWindowController, NSWindowDelegate { + static let shared = ScriptManagerWindowController() + + private let viewModel = ScriptManagerViewModel() + + private init() { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 700, height: 480), + styleMask: [.titled, .closable, .resizable, .miniaturizable], + backing: .buffered, + defer: false + ) + window.title = String( + localized: "scriptManager.windowTitle", + defaultValue: "Script Manager" + ) + window.titleVisibility = .visible + window.titlebarAppearsTransparent = false + window.isReleasedWhenClosed = false + window.minSize = NSSize(width: 500, height: 350) + window.identifier = NSUserInterfaceItemIdentifier("cmux.scriptManager") + window.setFrameAutosaveName("cmux.scriptManager") + window.center() + super.init(window: window) + window.contentView = NSHostingView(rootView: ScriptManagerView(viewModel: viewModel)) + window.delegate = self + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func show() { + viewModel.reload() + window?.makeKeyAndOrderFront(nil) + } + + func windowShouldClose(_ sender: NSWindow) -> Bool { + if viewModel.isDirty { + promptUnsavedChanges { [weak self] in + self?.window?.close() + } + return false + } + return true + } + + private func promptUnsavedChanges(onDiscard: @escaping () -> Void) { + guard let window else { return } + let alert = NSAlert() + alert.messageText = String( + localized: "scriptManager.unsavedChanges.title", + defaultValue: "Unsaved Changes" + ) + alert.informativeText = String( + localized: "scriptManager.unsavedChanges.message", + defaultValue: "Do you want to save your changes before closing?" + ) + alert.addButton(withTitle: String(localized: "common.save", defaultValue: "Save")) + alert.addButton(withTitle: String(localized: "common.discard", defaultValue: "Discard")) + alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) + alert.beginSheetModal(for: window) { [weak self] response in + switch response { + case .alertFirstButtonReturn: + self?.viewModel.save() + onDiscard() + case .alertSecondButtonReturn: + self?.viewModel.revert() + onDiscard() + default: + break + } + } + } +} + +// MARK: - SwiftUI View + +struct ScriptManagerView: View { + @ObservedObject var viewModel: ScriptManagerViewModel + + @State private var pendingSelection: String? + + var body: some View { + HSplitView { + scriptList + .frame(minWidth: 150, maxWidth: 200) + + editorPane + .frame(minWidth: 300) + } + } + + // MARK: - Script List + + private var scriptList: some View { + VStack(spacing: 0) { + List(viewModel.scriptNames, id: \.self, selection: $pendingSelection) { name in + Text(name) + } + .onChange(of: pendingSelection) { newValue in + guard let newValue, newValue != viewModel.selectedName else { return } + if viewModel.isDirty { + promptDirtySwitch(to: newValue) + } else { + viewModel.selectScript(named: newValue) + } + } + + HStack(spacing: 4) { + Button(action: viewModel.addScript) { + Image(systemName: "plus") + } + .buttonStyle(.borderless) + + Button(action: viewModel.duplicateSelected) { + Image(systemName: "doc.on.doc") + } + .buttonStyle(.borderless) + .disabled(viewModel.selectedName == nil) + + Button(action: confirmDelete) { + Image(systemName: "minus") + } + .buttonStyle(.borderless) + .disabled(viewModel.selectedName == nil) + + Spacer() + } + .padding(6) + } + } + + // MARK: - Editor + + private var editorPane: some View { + VStack(spacing: 0) { + if viewModel.selectedName != nil { + MonospaceTextEditor( + text: viewModel.editorText, + onChange: viewModel.textDidChange + ) + + HStack { + Spacer() + Button(String(localized: "common.revert", defaultValue: "Revert")) { + viewModel.revert() + } + .disabled(!viewModel.isDirty) + + Button(String(localized: "common.save", defaultValue: "Save")) { + viewModel.save() + } + .disabled(!viewModel.isDirty) + .keyboardShortcut("s", modifiers: .command) + } + .padding(8) + } else { + Text(String( + localized: "scriptManager.noSelection", + defaultValue: "Select a script to edit" + )) + .foregroundColor(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + + // MARK: - Actions + + private func confirmDelete() { + guard let name = viewModel.selectedName else { return } + DispatchQueue.main.async { + let alert = NSAlert() + alert.messageText = String( + localized: "scriptManager.deleteConfirm.title", + defaultValue: "Delete Script?" + ) + alert.informativeText = String( + localized: "scriptManager.deleteConfirm.message", + defaultValue: "Are you sure you want to delete \"\(name)\"? This cannot be undone." + ) + alert.addButton(withTitle: String(localized: "common.delete", defaultValue: "Delete")) + alert.buttons.first?.hasDestructiveAction = true + alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) + alert.alertStyle = .warning + if alert.runModal() == .alertFirstButtonReturn { + self.viewModel.deleteSelected() + self.pendingSelection = self.viewModel.selectedName + } + } + } + + private func promptDirtySwitch(to newName: String) { + let alert = NSAlert() + alert.messageText = String( + localized: "scriptManager.unsavedChanges.title", + defaultValue: "Unsaved Changes" + ) + alert.informativeText = String( + localized: "scriptManager.unsavedChanges.switchMessage", + defaultValue: "Save changes before switching?" + ) + alert.addButton(withTitle: String(localized: "common.save", defaultValue: "Save")) + alert.addButton(withTitle: String(localized: "common.discard", defaultValue: "Discard")) + alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) + let response = alert.runModal() + switch response { + case .alertFirstButtonReturn: + viewModel.save() + viewModel.selectScript(named: newName) + case .alertSecondButtonReturn: + viewModel.selectScript(named: newName) + default: + pendingSelection = viewModel.selectedName + } + } +} diff --git a/Sources/ScriptRepository.swift b/Sources/ScriptRepository.swift new file mode 100644 index 000000000000..ce530dcbbbaa --- /dev/null +++ b/Sources/ScriptRepository.swift @@ -0,0 +1,117 @@ +import Foundation + +/// Manages startup script files stored in `~/.config/cmux/scripts/`. +/// Each script is a `.sh` file. The filename (without extension) is the script name. +final class ScriptRepository: ScriptRepositoryProtocol { + + let directory: URL + + /// Default script repository at `~/.config/cmux/scripts/`. + static let shared = ScriptRepository( + directory: FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent(".config/cmux/scripts") + ) + + init(directory: URL) { + self.directory = directory + } + + /// Lists all available script names (filenames without `.sh` extension). + func listScripts() -> [String] { + guard let contents = try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: nil + ) else { + return [] + } + return contents + .filter { $0.pathExtension == "sh" } + .map { $0.deletingPathExtension().lastPathComponent } + .sorted() + } + + /// Returns the contents of a script, or nil if not found. + func getScript(named name: String) -> String? { + let path = directory.appendingPathComponent("\(name).sh") + return try? String(contentsOf: path, encoding: .utf8) + } + + /// Saves or updates a script file. Creates the directory if needed. + func saveScript(named name: String, content: String) throws { + try ensureDirectoryExists() + let path = directory.appendingPathComponent("\(name).sh") + try content.write(to: path, atomically: true, encoding: .utf8) + } + + /// Deletes a script file. + func deleteScript(named name: String) throws { + let path = directory.appendingPathComponent("\(name).sh") + try FileManager.default.removeItem(at: path) + } + + /// Returns true if a script with the given name exists. + func hasScript(named name: String) -> Bool { + let path = directory.appendingPathComponent("\(name).sh") + return FileManager.default.fileExists(atPath: path.path) + } + + /// Seeds default scripts on first use. Only writes files that don't already exist. + func seedDefaultScripts() { + for (name, content) in Self.defaultScripts { + guard !hasScript(named: name) else { continue } + try? saveScript(named: name, content: content) + } + } + + // MARK: - Default Script Definitions + + static let defaultScripts: [(name: String, content: String)] = [ + ( + name: "Builder", + content: """ + #!/bin/bash + # Builder: Start Claude Code in Builder/Foreman mode + cd "$CMUX_FOLDER" + claude --model sonnet "You are a BUILDER session. Read CLAUDE.md. You are the Foreman (read agents/foreman.md). Present: (1) Current project state, (2) Available phases/tasks. Ask what to build." + """ + ), + ( + name: "Fixer", + content: """ + #!/bin/bash + # Fixer: Start Claude Code in Fixer/Debugging mode + cd "$CMUX_FOLDER" + claude --model opus "You are a FIXER session. Read CLAUDE.md. You are the Foreman (read agents/foreman.md) in debugging/fixing mode. Ask me to describe the problem." + """ + ), + ( + name: "Claude", + content: """ + #!/bin/bash + # Claude: Start a plain Claude Code session + cd "$CMUX_FOLDER" + claude + """ + ), + ( + name: "Codex", + content: """ + #!/bin/bash + # Codex: Start Codex in the workspace folder + cd "$CMUX_FOLDER" + codex + """ + ), + ] + + // MARK: - Private + + private func ensureDirectoryExists() throws { + if !FileManager.default.fileExists(atPath: directory.path) { + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true + ) + } + } +} diff --git a/Sources/ScriptsMenu.swift b/Sources/ScriptsMenu.swift new file mode 100644 index 000000000000..d070bc6d3d6d --- /dev/null +++ b/Sources/ScriptsMenu.swift @@ -0,0 +1,86 @@ +import SwiftUI + +/// Scripts menu added to the app's main menu bar via CommandMenu. +/// Provides access to run scripts, open templates, and manage both. +struct ScriptsMenuContent: View { + let activeTabManager: TabManager + + var body: some View { + runScriptSubmenu + openTemplateSubmenu + Divider() + Button(String(localized: "menu.scripts.manageTemplates", defaultValue: "Manage Templates…")) { + TemplateManagerWindowController.shared.show() + } + Button(String(localized: "menu.scripts.manageScripts", defaultValue: "Manage Scripts…")) { + ScriptManagerWindowController.shared.show() + } + } + + // MARK: - Run Script + + @ViewBuilder + private var runScriptSubmenu: some View { + let scripts = ScriptRepository.shared.listScripts() + let isAtPrompt = activeTabManager.selectedTab?.isFocusedPanelAtPrompt ?? false + Menu(String(localized: "menu.scripts.runScript", defaultValue: "Run Script")) { + ForEach(scripts, id: \.self) { scriptName in + Button(scriptName) { + runScript(named: scriptName) + } + .disabled(!isAtPrompt) + } + if scripts.isEmpty { + Text(String(localized: "menu.scripts.noScripts", defaultValue: "No Scripts")) + } + } + } + + private func runScript(named scriptName: String) { + guard let scriptContent = ScriptRepository.shared.getScript(named: scriptName), + let terminalPanel = activeTabManager.selectedTab?.focusedTerminalPanel else { return } + let lines = StartupScriptRunner.prepareScriptLines(scriptContent) + guard !lines.isEmpty else { return } + let text = lines.joined(separator: "\n") + "\n" + terminalPanel.sendInteractiveText(text) + } + + // MARK: - Open Template + + @ViewBuilder + private var openTemplateSubmenu: some View { + let templates = TemplateRepository.shared.listTemplates() + Menu(String(localized: "menu.scripts.openTemplate", defaultValue: "Open Template")) { + ForEach(templates, id: \.self) { templateName in + Button(templateName) { + openTemplate(named: templateName) + } + } + if templates.isEmpty { + Text(String(localized: "menu.scripts.noTemplates", defaultValue: "No Templates")) + } + } + } + + private func openTemplate(named templateName: String) { + guard let template = try? TemplateRepository.shared.getTemplate(named: templateName) else { return } + + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.allowsMultipleSelection = false + panel.title = String( + localized: "menu.scripts.openTemplate.panelTitle", + defaultValue: "Choose Directory for Template" + ) + panel.prompt = String(localized: "menu.scripts.openTemplate.panelPrompt", defaultValue: "Open") + + // Default to the focused tab's current directory if available + if let currentDir = activeTabManager.selectedTab?.currentDirectory { + panel.directoryURL = URL(fileURLWithPath: currentDir) + } + + guard panel.runModal() == .OK, let url = panel.url else { return } + activeTabManager.openTemplate(template, directory: url.path) + } +} diff --git a/Sources/SessionPersistence.swift b/Sources/SessionPersistence.swift index 188833d40298..62a577c3616e 100644 --- a/Sources/SessionPersistence.swift +++ b/Sources/SessionPersistence.swift @@ -340,11 +340,21 @@ struct SessionWorkspaceSnapshot: Codable, Sendable { var logEntries: [SessionLogEntrySnapshot] var progress: SessionProgressSnapshot? var gitBranch: SessionGitBranchSnapshot? + /// Indices into the parent snapshot's workspaces array for child workspaces. + var childWorkspaceIndices: [Int]? + /// Whether this workspace's children are collapsed in the sidebar. + var isCollapsed: Bool? + /// The startup command to re-run on session restore. + var startupCommand: String? } struct SessionTabManagerSnapshot: Codable, Sendable { var selectedWorkspaceIndex: Int? var workspaces: [SessionWorkspaceSnapshot] + /// Legacy field for backward compatibility with old group-based layout. + var sidebarLayout: SessionSidebarLayoutSnapshot? + /// Top-level workspace indices for the new parent-child model. + var topLevelWorkspaceIndices: [Int]? } struct SessionWindowSnapshot: Codable, Sendable { diff --git a/Sources/SessionWorkspaceGroupSnapshot.swift b/Sources/SessionWorkspaceGroupSnapshot.swift new file mode 100644 index 000000000000..09827b1b6d0f --- /dev/null +++ b/Sources/SessionWorkspaceGroupSnapshot.swift @@ -0,0 +1,102 @@ +import Foundation + +/// Top-level sidebar layout snapshot for session persistence. +/// Stored as an optional field on `SessionTabManagerSnapshot` for backward compatibility. +struct SessionSidebarLayoutSnapshot: Codable, Sendable { + var items: [SessionSidebarItemSnapshot] +} + +/// A single entry in the top-level sidebar layout. +enum SessionSidebarItemSnapshot: Codable, Sendable { + case standalone(workspaceIndex: Int) + case group(SessionWorkspaceGroupSnapshot) + + private enum CodingKeys: String, CodingKey { + case type + case workspaceIndex + case group + } + + private enum ItemType: String, Codable { + case standalone + case group + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .standalone(let index): + try container.encode(ItemType.standalone, forKey: .type) + try container.encode(index, forKey: .workspaceIndex) + case .group(let snapshot): + try container.encode(ItemType.group, forKey: .type) + try container.encode(snapshot, forKey: .group) + } + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let type = try container.decode(ItemType.self, forKey: .type) + switch type { + case .standalone: + let index = try container.decode(Int.self, forKey: .workspaceIndex) + self = .standalone(workspaceIndex: index) + case .group: + let snapshot = try container.decode(SessionWorkspaceGroupSnapshot.self, forKey: .group) + self = .group(snapshot) + } + } +} + +/// Snapshot of a workspace group for session persistence. +/// References workspaces by positional index into the workspaces array (not UUID). +struct SessionWorkspaceGroupSnapshot: Codable, Sendable { + var title: String + var color: String? + var isCollapsed: Bool + var isPinned: Bool + var workingDirectory: String + var items: [SessionGroupItemSnapshot] +} + +/// A child item within a group snapshot. +enum SessionGroupItemSnapshot: Codable, Sendable { + case workspace(workspaceIndex: Int) + case group(SessionWorkspaceGroupSnapshot) + + private enum CodingKeys: String, CodingKey { + case type + case workspaceIndex + case group + } + + private enum ItemType: String, Codable { + case workspace + case group + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .workspace(let index): + try container.encode(ItemType.workspace, forKey: .type) + try container.encode(index, forKey: .workspaceIndex) + case .group(let snapshot): + try container.encode(ItemType.group, forKey: .type) + try container.encode(snapshot, forKey: .group) + } + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let type = try container.decode(ItemType.self, forKey: .type) + switch type { + case .workspace: + let index = try container.decode(Int.self, forKey: .workspaceIndex) + self = .workspace(workspaceIndex: index) + case .group: + let snapshot = try container.decode(SessionWorkspaceGroupSnapshot.self, forKey: .group) + self = .group(snapshot) + } + } +} diff --git a/Sources/StartupScriptRunner.swift b/Sources/StartupScriptRunner.swift new file mode 100644 index 000000000000..54ee6d0f251b --- /dev/null +++ b/Sources/StartupScriptRunner.swift @@ -0,0 +1,95 @@ +import Foundation + +/// Manages startup script execution for workspaces created from project configs. +/// Scripts are NOT run during session restore to avoid duplicate execution. +@MainActor +final class StartupScriptRunner { + + /// Default delay before sending script text to the terminal surface (milliseconds). + private static let defaultDelayMs: Int = 5000 + + /// Build environment variables for a workspace's startup script. + func buildEnvironment(workingDirectory: URL) -> [String: String] { + ["CMUX_FOLDER": workingDirectory.path] + } + + /// Whether a startup script should run in this context. + func shouldRunScript(isRestore: Bool) -> Bool { + !isRestore + } + + /// Schedule sending script content to a terminal when the shell prompt is ready. + /// Uses the workspace's onPromptReady callback for reliable detection. + /// Falls back to delay-based sending if shell integration isn't available. + func scheduleScript(content: String, workspace: Workspace, panelId: UUID) { + let lines = Self.prepareScriptLines(content) + guard !lines.isEmpty else { return } + scheduleLines(lines, workspace: workspace, panelId: panelId) + } + + /// Schedule sending a command to a terminal when the shell prompt is ready. + func scheduleCommand(_ command: String, workspace: Workspace, panelId: UUID) { + let lines = Self.prepareScriptLines(command) + guard !lines.isEmpty else { return } + scheduleLines(lines, workspace: workspace, panelId: panelId) + } + + /// Send lines to terminal, waiting for prompt ready signal. + /// Each line is sent individually followed by \r (Enter). + private func scheduleLines(_ lines: [String], workspace: Workspace, panelId: UUID) { + let text = lines.joined(separator: "\n") + "\n" + + let sendOnce: @MainActor () -> Void = { [weak workspace] in + guard let workspace else { return } + // Remove callback to prevent any second firing + workspace.onPromptReady.removeValue(forKey: panelId) + guard let panel = (workspace.focusedTerminalPanel + ?? workspace.terminalPanel(for: panelId)) else { return } + panel.sendInteractiveText(text) + } + + // Primary: wait for shell to report promptIdle + workspace.onPromptReady[panelId] = sendOnce + + // Fallback: if promptIdle never fires (no shell integration), send after delay + let fallbackDelayMs = Self.configuredDelayMs() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(fallbackDelayMs)) { [weak workspace] in + // Only fire if the callback is still pending (promptIdle never arrived) + guard let workspace, workspace.onPromptReady[panelId] != nil else { return } + sendOnce() + } + } + + /// Strip shebang, leading blank lines, and comment-only lines from script content. + /// Returns executable command lines only. + static func prepareScriptLines(_ content: String) -> [String] { + content.components(separatedBy: .newlines) + .drop(while: { line in + let trimmed = line.trimmingCharacters(in: .whitespaces) + return trimmed.isEmpty || trimmed.hasPrefix("#") + }) + .filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty } + } + + // MARK: - Private + + /// Read startup_script_delay_ms from ~/.config/cmux/settings.yaml if it exists. + private static func configuredDelayMs() -> Int { + let settingsPath = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent(".config/cmux/settings.yaml") + guard let content = try? String(contentsOf: settingsPath, encoding: .utf8) else { + return defaultDelayMs + } + for line in content.components(separatedBy: .newlines) { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.hasPrefix("startup_script_delay_ms:") { + let valueStr = String(trimmed.dropFirst("startup_script_delay_ms:".count)) + .trimmingCharacters(in: .whitespaces) + if let value = Int(valueStr), value > 0 { + return value + } + } + } + return defaultDelayMs + } +} diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 6df6abaf3ab2..16d0cb4cefc8 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -693,6 +693,14 @@ class TabManager: ObservableObject { @Published private(set) var pendingBackgroundWorkspaceLoadIds: Set = [] @Published private(set) var debugPinnedWorkspaceLoadIds: Set = [] + /// Manages sidebar layout (parent-child workspace relationships). + /// Initialized lazily after `self` is fully constructed. + private(set) lazy var groupManager = WorkspaceGroupManager(tabManager: self) + + /// Top-level workspace IDs for sidebar rendering order. + /// Each workspace may have children via its own `childWorkspaceIds`. + @Published var items: [SidebarItem] = [] + /// Global monotonically increasing counter for CMUX_PORT ordinal assignment. /// Static so port ranges don't overlap across multiple windows (each window has its own TabManager). private static var nextPortOrdinal: Int = 0 @@ -1051,6 +1059,38 @@ class TabManager: ObservableObject { focusedBrowserPanel?.hideFind() } + /// Look up a workspace by UUID in the tabs array. + func workspace(for id: UUID) -> Workspace? { + tabs.first(where: { $0.id == id }) + } + + // MARK: - Parent-Child Workspace Forwarding + + func toggleWorkspaceCollapsed(_ workspaceId: UUID) { + groupManager.toggleCollapsed(workspaceId) + items = groupManager.items + } + + /// Adds a child workspace under the given parent workspace. + /// The parent workspace keeps its own terminal — it just gains a child. + /// Returns the newly created child workspace, or nil if depth >= 3. + @discardableResult + func addChildWorkspace(for parentId: UUID) -> Workspace? { + guard let parent = tabs.first(where: { $0.id == parentId }) else { return nil } + let depth = groupManager.depthOf(workspaceId: parentId) + guard depth > 0, depth < 3 else { return nil } + + let workingDir = parent.currentDirectory + let ws = addWorkspace( + workingDirectory: workingDir, + select: true, + skipStandaloneRegistration: true + ) + groupManager.addChildId(ws.id, to: parentId) + items = groupManager.items + return ws + } + @discardableResult func addWorkspace( workingDirectory overrideWorkingDirectory: String? = nil, @@ -1059,7 +1099,8 @@ class TabManager: ObservableObject { select: Bool = true, eagerLoadTerminal: Bool = false, placementOverride: NewWorkspacePlacement? = nil, - autoWelcomeIfNeeded: Bool = true + autoWelcomeIfNeeded: Bool = true, + skipStandaloneRegistration: Bool = false ) -> Workspace { // Snapshot current published state once so workspace creation doesn't repeatedly // bounce through Combine-backed accessors while we're preparing the new workspace. @@ -1092,6 +1133,10 @@ class TabManager: ObservableObject { updatedTabs.append(newWorkspace) } tabs = updatedTabs + if !skipStandaloneRegistration { + groupManager.registerWorkspaceAsStandalone(newWorkspace.id) + items = groupManager.items + } if let explicitWorkingDirectory, let terminalPanel = newWorkspace.focusedTerminalPanel { scheduleInitialWorkspaceGitMetadataRefresh( @@ -1817,6 +1862,93 @@ class TabManager: ObservableObject { addWorkspace(select: select, eagerLoadTerminal: eagerLoadTerminal) } + /// Shows the new-workspace dialog and creates a workspace if confirmed. + /// Returns nil if the user cancelled. + @discardableResult + func addWorkspaceViaDialog() -> Workspace? { + guard let result = NewWorkspaceDialog.run() else { return nil } + + // If a template was selected, create the full workspace hierarchy + if let templateName = result.templateName, + let template = try? TemplateRepository.shared.getTemplate(named: templateName) { + return openTemplate(template, directory: result.directory) + } + + // Plain workspace (no template) + let workspace = addWorkspace(workingDirectory: result.directory, select: true) + workspace.title = URL(fileURLWithPath: result.directory).lastPathComponent + return workspace + } + + /// Creates a full workspace hierarchy from a template at the given directory. + @discardableResult + func openTemplate(_ template: WorkspaceTemplate, directory: String) -> Workspace? { + let scriptRunner = StartupScriptRunner() + + // Create root workspace + let rootWs = addWorkspace(workingDirectory: directory, select: true) + rootWs.title = template.root.title + if let color = template.root.color { + rootWs.customColor = color + } + if let command = template.root.command { + rootWs.startupCommand = command + if let panelId = rootWs.focusedPanelId ?? rootWs.panels.values.first(where: { $0 is TerminalPanel })?.id { + scriptRunner.scheduleCommand(command, workspace: rootWs, panelId: panelId) + } + } + + // Create children recursively + createTemplateChildren( + template.root.children, + parentId: rootWs.id, + workingDirectory: directory, + scriptRunner: scriptRunner + ) + + items = groupManager.items + selectedTabId = rootWs.id + return rootWs + } + + /// Recursively create child workspaces from template nodes. + private func createTemplateChildren( + _ children: [TemplateNode], + parentId: UUID, + workingDirectory: String, + scriptRunner: StartupScriptRunner + ) { + for child in children { + let ws = addWorkspace( + workingDirectory: workingDirectory, + select: false, + eagerLoadTerminal: true, + skipStandaloneRegistration: true + ) + ws.title = child.title + if let color = child.color { + ws.customColor = color + } + groupManager.addChildId(ws.id, to: parentId) + + if let command = child.command { + ws.startupCommand = command + if let panelId = ws.focusedPanelId ?? ws.panels.values.first(where: { $0 is TerminalPanel })?.id { + scriptRunner.scheduleCommand(command, workspace: ws, panelId: panelId) + } + } + + if !child.children.isEmpty { + createTemplateChildren( + child.children, + parentId: ws.id, + workingDirectory: workingDirectory, + scriptRunner: scriptRunner + ) + } + } + } + func terminalPanelForWorkspaceConfigInheritanceSource() -> TerminalPanel? { terminalPanelForWorkspaceConfigInheritanceSource(snapshot: workspaceCreationSnapshot()) } @@ -2090,6 +2222,18 @@ class TabManager: ObservableObject { func closeWorkspace(_ workspace: Workspace) { guard tabs.count > 1 else { return } + + // Close children first (recursively) + let childIds = workspace.childWorkspaceIds + for childId in childIds { + if let child = tabs.first(where: { $0.id == childId }) { + closeWorkspace(child) + } + } + + // After closing children, recheck count + guard tabs.count > 1 else { return } + sentryBreadcrumb("workspace.close", data: ["tabCount": tabs.count - 1]) clearWorkspaceGitProbes(workspaceId: workspace.id) sidebarSelectedWorkspaceIds.remove(workspace.id) @@ -2102,11 +2246,10 @@ class TabManager: ObservableObject { if let index = tabs.firstIndex(where: { $0.id == workspace.id }) { tabs.remove(at: index) + groupManager.removeWorkspace(workspace.id) + items = groupManager.items if selectedTabId == workspace.id { - // Keep the "focused index" stable when possible: - // - If we closed workspace i and there is still a workspace at index i, focus it (the one that moved up). - // - Otherwise (we closed the last workspace), focus the new last workspace (i-1). let newIndex = min(index, max(0, tabs.count - 1)) selectedTabId = tabs[newIndex].id } @@ -2122,6 +2265,8 @@ class TabManager: ObservableObject { sidebarSelectedWorkspaceIds.remove(tabId) let removed = tabs.remove(at: index) + groupManager.removeWorkspace(removed.id) + items = groupManager.items unwireClosedBrowserTracking(for: removed) removed.owningTabManager = nil lastFocusedPanelByTab.removeValue(forKey: removed.id) @@ -2149,6 +2294,8 @@ class TabManager: ObservableObject { return max(0, min(index, tabs.count)) }() tabs.insert(workspace, at: insertIndex) + groupManager.registerWorkspaceAsStandalone(workspace.id) + items = groupManager.items if select { selectedTabId = workspace.id } @@ -2933,27 +3080,31 @@ class TabManager: ObservableObject { } func selectNextTab() { - guard let currentId = selectedTabId, - let currentIndex = tabs.firstIndex(where: { $0.id == currentId }) else { return } - let nextIndex = (currentIndex + 1) % tabs.count + let visible = groupManager.visibleWorkspaces() + guard !visible.isEmpty, + let currentId = selectedTabId, + let currentIndex = visible.firstIndex(where: { $0.id == currentId }) else { return } + let nextIndex = (currentIndex + 1) % visible.count #if DEBUG - let nextId = tabs[nextIndex].id + let nextId = visible[nextIndex].id debugPrepareWorkspaceSwitch("next", from: currentId, to: nextId) #endif activateWorkspaceCycleHotWindow() - selectedTabId = tabs[nextIndex].id + selectedTabId = visible[nextIndex].id } func selectPreviousTab() { - guard let currentId = selectedTabId, - let currentIndex = tabs.firstIndex(where: { $0.id == currentId }) else { return } - let prevIndex = (currentIndex - 1 + tabs.count) % tabs.count + let visible = groupManager.visibleWorkspaces() + guard !visible.isEmpty, + let currentId = selectedTabId, + let currentIndex = visible.firstIndex(where: { $0.id == currentId }) else { return } + let prevIndex = (currentIndex - 1 + visible.count) % visible.count #if DEBUG - let prevId = tabs[prevIndex].id + let prevId = visible[prevIndex].id debugPrepareWorkspaceSwitch("prev", from: currentId, to: prevId) #endif activateWorkspaceCycleHotWindow() - selectedTabId = tabs[prevIndex].id + selectedTabId = visible[prevIndex].id } private func activateWorkspaceCycleHotWindow() { @@ -3068,15 +3219,17 @@ class TabManager: ObservableObject { #endif func selectTab(at index: Int) { - guard index >= 0 && index < tabs.count else { return } + let visible = groupManager.visibleWorkspaces() + guard index >= 0 && index < visible.count else { return } #if DEBUG - debugPrimeWorkspaceSwitchTrigger("select_index", to: tabs[index].id) + debugPrimeWorkspaceSwitchTrigger("select_index", to: visible[index].id) #endif - selectedTabId = tabs[index].id + selectedTabId = visible[index].id } func selectLastTab() { - guard let lastTab = tabs.last else { return } + let visible = groupManager.visibleWorkspaces() + guard let lastTab = visible.last else { return } selectedTabId = lastTab.id } @@ -4891,14 +5044,30 @@ extension TabManager { let restorableTabs = tabs .filter { !$0.isRemoteWorkspace } .prefix(SessionPersistencePolicy.maxWorkspacesPerWindow) + // Build UUID → positional index map for child workspace index resolution + var uuidToIndex: [UUID: Int] = [:] + for (index, ws) in restorableTabs.enumerated() { + uuidToIndex[ws.id] = index + } + let workspaceSnapshots = restorableTabs - .map { $0.sessionSnapshot(includeScrollback: includeScrollback) } + .map { ws -> SessionWorkspaceSnapshot in + var snap = ws.sessionSnapshot(includeScrollback: includeScrollback) + let childIndices = ws.childWorkspaceIds.compactMap { uuidToIndex[$0] } + snap.childWorkspaceIndices = childIndices.isEmpty ? nil : childIndices + snap.isCollapsed = ws.isCollapsed ? true : nil + return snap + } let selectedWorkspaceIndex = selectedTabId.flatMap { selectedTabId in restorableTabs.firstIndex(where: { $0.id == selectedTabId }) } + + let topLevelIndices = groupManager.items.compactMap { uuidToIndex[$0] } + return SessionTabManagerSnapshot( selectedWorkspaceIndex: selectedWorkspaceIndex, - workspaces: workspaceSnapshots + workspaces: workspaceSnapshots, + topLevelWorkspaceIndices: topLevelIndices.isEmpty ? nil : topLevelIndices ) } @@ -4963,10 +5132,41 @@ extension TabManager { newSelectedId = newTabs.first?.id } + // Restore child workspace relationships from snapshot + let workspaceSnapArr = Array(snapshot.workspaces.prefix(SessionPersistencePolicy.maxWorkspacesPerWindow)) + for (i, wsSnap) in workspaceSnapArr.enumerated() where newTabs.indices.contains(i) { + if let childIndices = wsSnap.childWorkspaceIndices { + newTabs[i].childWorkspaceIds = childIndices.compactMap { idx in + guard newTabs.indices.contains(idx) else { return nil } + return newTabs[idx].id + } + } + if wsSnap.isCollapsed == true { + newTabs[i].isCollapsed = true + } + } + // Single atomic assignment of @Published properties so SwiftUI observers // never see an intermediate state with empty tabs or nil selection. tabs = newTabs selectedTabId = newSelectedId + + // Rebuild sidebar layout from snapshot + if let topLevelIndices = snapshot.topLevelWorkspaceIndices { + groupManager.items = topLevelIndices.compactMap { index in + guard newTabs.indices.contains(index) else { return nil } + return newTabs[index].id + } + } else if let sidebarLayout = snapshot.sidebarLayout { + // Legacy restore: flatten old group-based layout + restoreLegacySidebarLayout(sidebarLayout, workspaces: newTabs) + } else { + for ws in newTabs { + groupManager.registerWorkspaceAsStandalone(ws.id) + } + } + items = groupManager.items + for workspace in newTabs { let terminalPanels = workspace.panels.values.compactMap { $0 as? TerminalPanel } for terminalPanel in terminalPanels { @@ -4981,6 +5181,17 @@ extension TabManager { } } + // Re-run startup commands for restored workspaces + let scriptRunner = StartupScriptRunner() + for workspace in newTabs { + guard let command = workspace.startupCommand else { continue } + let panelId = workspace.focusedPanelId + ?? workspace.panels.values.first(where: { $0 is TerminalPanel })?.id + guard let panelId else { continue } + requestBackgroundWorkspaceLoad(for: workspace.id) + scriptRunner.scheduleCommand(command, workspace: workspace, panelId: panelId) + } + if let selectedTabId { NotificationCenter.default.post( name: .ghosttyDidFocusTab, @@ -4989,6 +5200,47 @@ extension TabManager { ) } } + + /// Legacy restore for old group-based sidebar layout snapshots. + /// Flattens the group hierarchy into workspace parent-child relationships. + private func restoreLegacySidebarLayout( + _ layout: SessionSidebarLayoutSnapshot, workspaces: [Workspace] + ) { + for item in layout.items { + switch item { + case .standalone(let index): + guard workspaces.indices.contains(index) else { continue } + groupManager.registerWorkspaceAsStandalone(workspaces[index].id) + case .group(let groupSnapshot): + // Legacy groups become the first workspace as parent with rest as children + let childIndices = collectLegacyGroupWorkspaceIndices(groupSnapshot) + guard let firstIndex = childIndices.first, + workspaces.indices.contains(firstIndex) else { continue } + let parentWs = workspaces[firstIndex] + groupManager.registerWorkspaceAsStandalone(parentWs.id) + parentWs.isCollapsed = groupSnapshot.isCollapsed + for childIndex in childIndices.dropFirst() { + guard workspaces.indices.contains(childIndex) else { continue } + parentWs.childWorkspaceIds.append(workspaces[childIndex].id) + } + } + } + } + + private func collectLegacyGroupWorkspaceIndices( + _ snapshot: SessionWorkspaceGroupSnapshot + ) -> [Int] { + var indices: [Int] = [] + for item in snapshot.items { + switch item { + case .workspace(let index): + indices.append(index) + case .group(let sub): + indices.append(contentsOf: collectLegacyGroupWorkspaceIndices(sub)) + } + } + return indices + } } // MARK: - Direction Types for Backwards Compatibility diff --git a/Sources/TemplateManagerHelpSidebar.swift b/Sources/TemplateManagerHelpSidebar.swift new file mode 100644 index 000000000000..9cf37d38f088 --- /dev/null +++ b/Sources/TemplateManagerHelpSidebar.swift @@ -0,0 +1,217 @@ +import SwiftUI + +/// Right sidebar for the Template Manager window. +/// Shows YAML format reference and a searchable list of cmux socket commands. +struct TemplateManagerHelpSidebar: View { + @State private var searchText: String = "" + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Text(String( + localized: "templateManager.help.title", + defaultValue: "Reference" + )) + .font(.headline) + .padding(.horizontal, 10) + .padding(.top, 10) + .padding(.bottom, 6) + + Divider() + + ScrollView { + VStack(alignment: .leading, spacing: 12) { + yamlReferenceSection + Divider() + commandListSection + } + .padding(10) + } + } + .background(Color(nsColor: .controlBackgroundColor)) + } + + // MARK: - YAML Reference + + @ViewBuilder + private var yamlReferenceSection: some View { + VStack(alignment: .leading, spacing: 6) { + Text(String( + localized: "templateManager.help.yamlFormat", + defaultValue: "YAML Format" + )) + .font(.subheadline.bold()) + + yamlHint( + "root:", + String(localized: "templateManager.help.rootNode", defaultValue: "Root workspace node") + ) + yamlHint( + " title:", + String(localized: "templateManager.help.title.field", defaultValue: "Workspace title") + ) + yamlHint( + " color:", + String(localized: "templateManager.help.color", defaultValue: "Hex color (e.g. \"#FF0000\")") + ) + yamlHint( + " command:", + String(localized: "templateManager.help.command", defaultValue: "Startup command (string or |)") + ) + yamlHint( + " children:", + String(localized: "templateManager.help.children", defaultValue: "List of child workspaces") + ) + } + } + + private func yamlHint(_ key: String, _ description: String) -> some View { + VStack(alignment: .leading, spacing: 1) { + Text(key) + .font(.system(size: 11, design: .monospaced)) + .foregroundColor(.accentColor) + Text(description) + .font(.caption) + .foregroundColor(.secondary) + } + } + + // MARK: - Command List + + @ViewBuilder + private var commandListSection: some View { + VStack(alignment: .leading, spacing: 6) { + Text(String( + localized: "templateManager.help.commands", + defaultValue: "cmux Commands" + )) + .font(.subheadline.bold()) + + TextField( + String(localized: "templateManager.help.search", defaultValue: "Search commands…"), + text: $searchText + ) + .textFieldStyle(.roundedBorder) + .font(.caption) + + let commands = filteredCommands + ForEach(commands, id: \.self) { command in + Text(command) + .font(.system(size: 10, design: .monospaced)) + .foregroundColor(.primary) + .textSelection(.enabled) + } + + if commands.isEmpty { + Text(String( + localized: "templateManager.help.noResults", + defaultValue: "No matching commands" + )) + .font(.caption) + .foregroundColor(.secondary) + } + } + } + + private var filteredCommands: [String] { + let query = searchText.trimmingCharacters(in: .whitespaces).lowercased() + if query.isEmpty { return Self.allCommands } + return Self.allCommands.filter { $0.lowercased().contains(query) } + } + + // MARK: - Command List Data + + // swiftlint:disable line_length + static let allCommands: [String] = [ + "system.ping", + "system.capabilities", + "system.identify", + "system.tree", + "auth.login", + "window.list", + "window.current", + "window.focus", + "window.create", + "window.close", + "workspace.list", + "workspace.create", + "workspace.select", + "workspace.current", + "workspace.close", + "workspace.move_to_window", + "workspace.reorder", + "workspace.rename", + "workspace.action", + "workspace.next", + "workspace.previous", + "workspace.last", + "workspace.remote.configure", + "workspace.remote.reconnect", + "workspace.remote.disconnect", + "workspace.remote.status", + "surface.list", + "surface.current", + "surface.focus", + "surface.split", + "surface.create", + "surface.close", + "surface.move", + "surface.reorder", + "surface.action", + "surface.send_text", + "surface.send_key", + "surface.read_text", + "surface.clear_history", + "pane.list", + "pane.focus", + "pane.surfaces", + "pane.create", + "pane.resize", + "pane.swap", + "pane.break", + "pane.join", + "pane.last", + "notification.create", + "notification.list", + "notification.clear", + "browser.open_split", + "browser.navigate", + "browser.back", + "browser.forward", + "browser.reload", + "browser.url.get", + "browser.snapshot", + "browser.eval", + "browser.click", + "browser.type", + "browser.fill", + "browser.press", + "browser.screenshot", + "browser.get.text", + "browser.get.html", + "browser.get.title", + "group.create", + "group.list", + "group.delete", + "group.rename", + "group.set_color", + "group.add_workspace", + "group.remove_workspace", + "group.install_template", + "project.open", + "project.open_template", + "script.list", + "script.get", + "script.save", + "script.delete", + "template.list", + "template.get", + "template.save", + "template.delete", + "settings.open", + "feedback.open", + "feedback.submit", + "markdown.open", + "tab.action", + ] + // swiftlint:enable line_length +} diff --git a/Sources/TemplateManagerViewModel.swift b/Sources/TemplateManagerViewModel.swift new file mode 100644 index 000000000000..833c8ebb64ef --- /dev/null +++ b/Sources/TemplateManagerViewModel.swift @@ -0,0 +1,129 @@ +import Foundation + +/// View model for the Template Manager window. +/// Manages template list, selection, editing state, and YAML validation. +@MainActor +final class TemplateManagerViewModel: ObservableObject { + @Published var templateNames: [String] = [] + @Published var selectedName: String? + @Published var editorText: String = "" + @Published var errorMessage: String? + @Published private(set) var isDirty: Bool = false + + private var loadedText: String = "" + private let repo = TemplateRepository.shared + + func reload() { + templateNames = repo.listTemplates() + if let selected = selectedName, templateNames.contains(selected) { + loadTemplate(named: selected) + } else if let first = templateNames.first { + selectTemplate(named: first) + } else { + selectedName = nil + editorText = "" + loadedText = "" + isDirty = false + errorMessage = nil + } + } + + func selectTemplate(named name: String) { + selectedName = name + loadTemplate(named: name) + } + + func save() { + guard let name = selectedName else { return } + // Validate YAML before saving + do { + _ = try TemplateYamlParser.parse(editorText) + } catch { + errorMessage = error.localizedDescription + return + } + do { + try repo.saveTemplate(named: name, rawYaml: editorText) + loadedText = editorText + isDirty = false + errorMessage = nil + } catch { + errorMessage = error.localizedDescription + } + } + + func revert() { + guard let name = selectedName else { return } + loadTemplate(named: name) + } + + func addTemplate() { + var baseName = String( + localized: "templateManager.newTemplateName", + defaultValue: "New Template" + ) + var counter = 1 + while repo.hasTemplate(named: baseName) { + counter += 1 + baseName = String( + localized: "templateManager.newTemplateNameNumbered", + defaultValue: "New Template \(counter)" + ) + } + let defaultContent = """ + root: + title: Terminal + children: + - title: Shell + command: "" + """ + try? repo.saveTemplate(named: baseName, rawYaml: defaultContent) + reload() + selectTemplate(named: baseName) + } + + func duplicateSelected() { + guard let name = selectedName, + let yaml = repo.rawYaml(named: name) else { return } + var copyName = "\(name) Copy" + var counter = 1 + while repo.hasTemplate(named: copyName) { + counter += 1 + copyName = "\(name) Copy \(counter)" + } + try? repo.saveTemplate(named: copyName, rawYaml: yaml) + reload() + selectTemplate(named: copyName) + } + + func deleteSelected() { + guard let name = selectedName else { return } + try? repo.deleteTemplate(named: name) + selectedName = nil + editorText = "" + loadedText = "" + isDirty = false + errorMessage = nil + reload() + } + + func textDidChange(_ newText: String) { + editorText = newText + isDirty = newText != loadedText + errorMessage = nil + } + + // MARK: - Private + + private func loadTemplate(named name: String) { + if let yaml = repo.rawYaml(named: name) { + editorText = yaml + loadedText = yaml + } else { + editorText = "" + loadedText = "" + } + isDirty = false + errorMessage = nil + } +} diff --git a/Sources/TemplateManagerWindow.swift b/Sources/TemplateManagerWindow.swift new file mode 100644 index 000000000000..4ef921bddb61 --- /dev/null +++ b/Sources/TemplateManagerWindow.swift @@ -0,0 +1,242 @@ +import AppKit +import SwiftUI + +// MARK: - Window Controller + +@MainActor +final class TemplateManagerWindowController: NSWindowController, NSWindowDelegate { + static let shared = TemplateManagerWindowController() + + private let viewModel = TemplateManagerViewModel() + + private init() { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 900, height: 560), + styleMask: [.titled, .closable, .resizable, .miniaturizable], + backing: .buffered, + defer: false + ) + window.title = String( + localized: "templateManager.windowTitle", + defaultValue: "Template Manager" + ) + window.titleVisibility = .visible + window.titlebarAppearsTransparent = false + window.isReleasedWhenClosed = false + window.minSize = NSSize(width: 700, height: 400) + window.identifier = NSUserInterfaceItemIdentifier("cmux.templateManager") + window.setFrameAutosaveName("cmux.templateManager") + window.center() + super.init(window: window) + window.contentView = NSHostingView(rootView: TemplateManagerView(viewModel: viewModel)) + window.delegate = self + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func show() { + viewModel.reload() + window?.makeKeyAndOrderFront(nil) + } + + func windowShouldClose(_ sender: NSWindow) -> Bool { + if viewModel.isDirty { + promptUnsavedChanges { [weak self] in + self?.window?.close() + } + return false + } + return true + } + + private func promptUnsavedChanges(onDiscard: @escaping () -> Void) { + guard let window else { return } + let alert = NSAlert() + alert.messageText = String( + localized: "templateManager.unsavedChanges.title", + defaultValue: "Unsaved Changes" + ) + alert.informativeText = String( + localized: "templateManager.unsavedChanges.message", + defaultValue: "Do you want to save your changes before closing?" + ) + alert.addButton(withTitle: String(localized: "common.save", defaultValue: "Save")) + alert.addButton(withTitle: String(localized: "common.discard", defaultValue: "Discard")) + alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) + alert.beginSheetModal(for: window) { [weak self] response in + switch response { + case .alertFirstButtonReturn: + self?.viewModel.save() + onDiscard() + case .alertSecondButtonReturn: + self?.viewModel.revert() + onDiscard() + default: + break + } + } + } +} + +// MARK: - SwiftUI View + +struct TemplateManagerView: View { + @ObservedObject var viewModel: TemplateManagerViewModel + + @State private var pendingSelection: String? + + var body: some View { + HSplitView { + templateList + .frame(minWidth: 160, maxWidth: 220) + + editorPane + .frame(minWidth: 300) + + TemplateManagerHelpSidebar() + .frame(minWidth: 200, maxWidth: 260) + } + } + + // MARK: - Template List + + private var templateList: some View { + VStack(spacing: 0) { + List(viewModel.templateNames, id: \.self, selection: $pendingSelection) { name in + Text(name) + } + .onChange(of: pendingSelection) { newValue in + guard let newValue, newValue != viewModel.selectedName else { return } + if viewModel.isDirty { + promptDirtySwitch(to: newValue) + } else { + viewModel.selectTemplate(named: newValue) + } + } + + HStack(spacing: 4) { + Button(action: viewModel.addTemplate) { + Image(systemName: "plus") + } + .buttonStyle(.borderless) + + Button(action: viewModel.duplicateSelected) { + Image(systemName: "doc.on.doc") + } + .buttonStyle(.borderless) + .disabled(viewModel.selectedName == nil) + + Button(action: confirmDelete) { + Image(systemName: "minus") + } + .buttonStyle(.borderless) + .disabled(viewModel.selectedName == nil) + + Spacer() + } + .padding(6) + } + } + + // MARK: - Editor + + private var editorPane: some View { + VStack(spacing: 0) { + if viewModel.selectedName != nil { + MonospaceTextEditor( + text: viewModel.editorText, + onChange: viewModel.textDidChange + ) + + if let error = viewModel.errorMessage { + HStack { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundColor(.red) + Text(error) + .foregroundColor(.red) + .font(.caption) + .lineLimit(2) + Spacer() + } + .padding(.horizontal, 8) + .padding(.vertical, 4) + } + + HStack { + Spacer() + Button(String(localized: "common.revert", defaultValue: "Revert")) { + viewModel.revert() + } + .disabled(!viewModel.isDirty) + + Button(String(localized: "common.save", defaultValue: "Save")) { + viewModel.save() + } + .disabled(!viewModel.isDirty) + .keyboardShortcut("s", modifiers: .command) + } + .padding(8) + } else { + Text(String( + localized: "templateManager.noSelection", + defaultValue: "Select a template to edit" + )) + .foregroundColor(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + + // MARK: - Actions + + private func confirmDelete() { + guard let name = viewModel.selectedName else { return } + DispatchQueue.main.async { + let alert = NSAlert() + alert.messageText = String( + localized: "templateManager.deleteConfirm.title", + defaultValue: "Delete Template?" + ) + alert.informativeText = String( + localized: "templateManager.deleteConfirm.message", + defaultValue: "Are you sure you want to delete \"\(name)\"? This cannot be undone." + ) + alert.addButton(withTitle: String(localized: "common.delete", defaultValue: "Delete")) + alert.buttons.first?.hasDestructiveAction = true + alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) + alert.alertStyle = .warning + if alert.runModal() == .alertFirstButtonReturn { + self.viewModel.deleteSelected() + self.pendingSelection = self.viewModel.selectedName + } + } + } + + private func promptDirtySwitch(to newName: String) { + let alert = NSAlert() + alert.messageText = String( + localized: "templateManager.unsavedChanges.title", + defaultValue: "Unsaved Changes" + ) + alert.informativeText = String( + localized: "templateManager.unsavedChanges.switchMessage", + defaultValue: "Save changes before switching?" + ) + alert.addButton(withTitle: String(localized: "common.save", defaultValue: "Save")) + alert.addButton(withTitle: String(localized: "common.discard", defaultValue: "Discard")) + alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) + let response = alert.runModal() + switch response { + case .alertFirstButtonReturn: + viewModel.save() + viewModel.selectTemplate(named: newName) + case .alertSecondButtonReturn: + viewModel.selectTemplate(named: newName) + default: + pendingSelection = viewModel.selectedName + } + } +} diff --git a/Sources/TemplateRepository.swift b/Sources/TemplateRepository.swift new file mode 100644 index 000000000000..3a8544452942 --- /dev/null +++ b/Sources/TemplateRepository.swift @@ -0,0 +1,162 @@ +import Foundation + +/// A node in the template tree. Represents a workspace with optional children. +struct TemplateNode: Equatable { + let title: String + let color: String? + let command: String? + let children: [TemplateNode] +} + +/// A parsed workspace template with a root node containing children. +struct WorkspaceTemplate: Equatable { + let root: TemplateNode +} + +/// Legacy tab definition for backward compatibility with old `tabs:` format. +struct TemplateTabDefinition: Equatable { + let title: String + let startupScript: String? +} + +/// Manages workspace template files stored in `~/.config/cmux/templates/`. +/// Each template is a `.yaml` file with a `root:` tree of workspace definitions. +final class TemplateRepository { + + let directory: URL + + /// Default template repository at `~/.config/cmux/templates/`. + static let shared = TemplateRepository( + directory: FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent(".config/cmux/templates") + ) + + init(directory: URL) { + self.directory = directory + } + + /// Lists all available template names (filenames without `.yaml` extension). + func listTemplates() -> [String] { + guard let contents = try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: nil + ) else { + return [] + } + return contents + .filter { $0.pathExtension == "yaml" } + .map { $0.deletingPathExtension().lastPathComponent } + .sorted() + } + + /// Parses and returns a template by name. + func getTemplate(named name: String) throws -> WorkspaceTemplate { + let path = directory.appendingPathComponent("\(name).yaml") + let content = try String(contentsOf: path, encoding: .utf8) + return try TemplateYamlParser.parse(content) + } + + /// Returns the raw YAML string for a template, or nil if not found. + func rawYaml(named name: String) -> String? { + let path = directory.appendingPathComponent("\(name).yaml") + return try? String(contentsOf: path, encoding: .utf8) + } + + /// Saves a template definition to a file. Creates the directory if needed. + func saveTemplate(named name: String, template: WorkspaceTemplate) throws { + try ensureDirectoryExists() + let yaml = TemplateYamlParser.serialize(template) + let path = directory.appendingPathComponent("\(name).yaml") + try yaml.write(to: path, atomically: true, encoding: .utf8) + } + + /// Saves raw YAML content as a template file. Creates the directory if needed. + func saveTemplate(named name: String, rawYaml: String) throws { + try ensureDirectoryExists() + let path = directory.appendingPathComponent("\(name).yaml") + try rawYaml.write(to: path, atomically: true, encoding: .utf8) + } + + /// Deletes a template file. + func deleteTemplate(named name: String) throws { + let path = directory.appendingPathComponent("\(name).yaml") + try FileManager.default.removeItem(at: path) + } + + /// Returns true if a template with the given name exists. + func hasTemplate(named name: String) -> Bool { + let path = directory.appendingPathComponent("\(name).yaml") + return FileManager.default.fileExists(atPath: path.path) + } + + /// Seeds default templates on first use. Only writes files that don't already exist. + func seedDefaultTemplates() { + for (name, content) in Self.defaultTemplates { + guard !hasTemplate(named: name) else { continue } + try? ensureDirectoryExists() + let path = directory.appendingPathComponent("\(name).yaml") + try? content.write(to: path, atomically: true, encoding: .utf8) + } + } + + // MARK: - Default Template Definitions + + // swiftlint:disable line_length + static let defaultTemplates: [(name: String, content: String)] = [ + ( + name: "AI Dev", + content: """ + root: + title: Terminal + children: + - title: Builder + color: "#00CC00" + command: | + claude --model sonnet "You are a BUILDER session — the Session Role section in CLAUDE.md does not apply to you. Use the Read tool (not bash) to read CLAUDE.md. You are the Foreman (use Read tool on agents/foreman.md). Start a new building session. Use Glob and Read to find and read any project spec. Use Glob to check for STATE.md or CONTINUE.md. IMPORTANT: use Read/Glob/Grep tools for all file exploration — never use compound bash commands. Present: (1) Current project state, (2) Available phases/tasks. Ask what to build." + - title: Fixer + color: "#FF0000" + command: | + claude --model opus "You are a FIXER session — the Session Role section in CLAUDE.md does not apply to you. Use the Read tool (not bash) to read CLAUDE.md. You are the Foreman (use Read tool on agents/foreman.md) in debugging/fixing mode. Use Glob to explore the project structure. Use 'git log --oneline -10' and 'git diff' (single simple commands, never compound) to check recent changes. IMPORTANT: use Read/Glob/Grep tools for all file exploration — never use compound bash commands. Ask me to describe the problem. When I do, use the 'Give me problem status' format: (1) Current bad behavior, (2) Log results, (3) What you think is wrong, (4) Proposed solution. Fix one thing at a time." + - title: Codex + color: "#9900FF" + command: codex --approval-mode full-auto + """ + ), + ( + name: "Builder", + content: """ + root: + title: Terminal + children: + - title: Builder + color: "#00CC00" + command: | + claude --model sonnet "You are a BUILDER session — the Session Role section in CLAUDE.md does not apply to you. Use the Read tool (not bash) to read CLAUDE.md. You are the Foreman (use Read tool on agents/foreman.md). Start a new building session. Use Glob and Read to find and read any project spec. Use Glob to check for STATE.md or CONTINUE.md. IMPORTANT: use Read/Glob/Grep tools for all file exploration — never use compound bash commands. Present: (1) Current project state, (2) Available phases/tasks. Ask what to build." + """ + ), + ( + name: "Fixer", + content: """ + root: + title: Terminal + children: + - title: Fixer + color: "#FF0000" + command: | + claude --model opus "You are a FIXER session — the Session Role section in CLAUDE.md does not apply to you. Use the Read tool (not bash) to read CLAUDE.md. You are the Foreman (use Read tool on agents/foreman.md) in debugging/fixing mode. Use Glob to explore the project structure. Use 'git log --oneline -10' and 'git diff' (single simple commands, never compound) to check recent changes. IMPORTANT: use Read/Glob/Grep tools for all file exploration — never use compound bash commands. Ask me to describe the problem. When I do, use the 'Give me problem status' format: (1) Current bad behavior, (2) Log results, (3) What you think is wrong, (4) Proposed solution. Fix one thing at a time." + """ + ), + ] + // swiftlint:enable line_length + + // MARK: - Private + + private func ensureDirectoryExists() throws { + if !FileManager.default.fileExists(atPath: directory.path) { + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true + ) + } + } +} diff --git a/Sources/TemplateYamlParser.swift b/Sources/TemplateYamlParser.swift new file mode 100644 index 000000000000..c174384091ea --- /dev/null +++ b/Sources/TemplateYamlParser.swift @@ -0,0 +1,282 @@ +import Foundation + +/// Parses workspace template YAML files into `WorkspaceTemplate` structures. +/// Supports both the new `root:` tree format and legacy `tabs:` format. +enum TemplateYamlParser { + + /// Parse a template YAML string into a WorkspaceTemplate. + static func parse(_ content: String) throws -> WorkspaceTemplate { + let lines = content.components(separatedBy: .newlines) + let hasRoot = lines.contains { $0.trimmingCharacters(in: .whitespaces).hasPrefix("root:") } + if hasRoot { + return try parseNewFormat(lines) + } + return try parseLegacyFormat(lines) + } + + // MARK: - New Format + + private static func parseNewFormat(_ lines: [String]) throws -> WorkspaceTemplate { + let root = try parseNodeBlock(lines: lines, startKey: "root:") + return WorkspaceTemplate(root: root) + } + + private static func parseNodeBlock(lines: [String], startKey: String) throws -> TemplateNode { + guard let rootLineIdx = lines.firstIndex(where: { + $0.trimmingCharacters(in: .whitespaces) == startKey || + $0.trimmingCharacters(in: .whitespaces).hasPrefix(startKey) + }) else { + throw TemplateParseError.missingRoot + } + + let rootIndent = indentLevel(of: lines[rootLineIdx]) + let childIndent = rootIndent + 2 + + var title = "Terminal" + var color: String? + var command: String? + var children: [TemplateNode] = [] + + var idx = rootLineIdx + 1 + while idx < lines.count { + let line = lines[idx] + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { idx += 1; continue } + + let lineIndent = indentLevel(of: line) + if lineIndent <= rootIndent { break } + + if trimmed.hasPrefix("title:") { + title = extractYamlValue(trimmed, key: "title:") ?? "Terminal" + } else if trimmed.hasPrefix("color:") { + color = extractYamlValue(trimmed, key: "color:") + } else if trimmed.hasPrefix("command:") { + let inlineValue = extractYamlValue(trimmed, key: "command:") + if inlineValue == "|" || inlineValue == nil { + let (block, nextIdx) = readBlockScalar(lines: lines, from: idx + 1, baseIndent: lineIndent + 2) + command = block + idx = nextIdx + continue + } else { + command = inlineValue + } + } else if trimmed == "children:" { + let (parsed, nextIdx) = parseChildrenList( + lines: lines, from: idx + 1, listIndent: childIndent + 2 + ) + children = parsed + idx = nextIdx + continue + } + idx += 1 + } + + return TemplateNode(title: title, color: color, command: command, children: children) + } + + private static func parseChildrenList( + lines: [String], from startIdx: Int, listIndent: Int + ) -> ([TemplateNode], Int) { + var children: [TemplateNode] = [] + var idx = startIdx + + while idx < lines.count { + let line = lines[idx] + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { idx += 1; continue } + + let lineIndent = indentLevel(of: line) + if lineIndent < listIndent { break } + + if trimmed.hasPrefix("- title:") { + let (node, nextIdx) = parseChildNode(lines: lines, from: idx, itemIndent: lineIndent) + children.append(node) + idx = nextIdx + continue + } + idx += 1 + } + return (children, idx) + } + + private static func parseChildNode( + lines: [String], from startIdx: Int, itemIndent: Int + ) -> (TemplateNode, Int) { + let firstLine = lines[startIdx].trimmingCharacters(in: .whitespaces) + var title = extractYamlValue(firstLine, key: "- title:") ?? "Workspace" + var color: String? + var command: String? + var children: [TemplateNode] = [] + + let propIndent = itemIndent + 2 + var idx = startIdx + 1 + + while idx < lines.count { + let line = lines[idx] + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { idx += 1; continue } + + let lineIndent = indentLevel(of: line) + if lineIndent < propIndent { break } + if lineIndent == itemIndent && trimmed.hasPrefix("- ") { break } + + if trimmed.hasPrefix("title:") { + title = extractYamlValue(trimmed, key: "title:") ?? title + } else if trimmed.hasPrefix("color:") { + color = extractYamlValue(trimmed, key: "color:") + } else if trimmed.hasPrefix("command:") { + let inlineValue = extractYamlValue(trimmed, key: "command:") + if inlineValue == "|" || inlineValue == nil { + let (block, nextIdx) = readBlockScalar(lines: lines, from: idx + 1, baseIndent: lineIndent + 2) + command = block + idx = nextIdx + continue + } else { + command = inlineValue + } + } else if trimmed == "children:" { + let (parsed, nextIdx) = parseChildrenList( + lines: lines, from: idx + 1, listIndent: lineIndent + 2 + ) + children = parsed + idx = nextIdx + continue + } + idx += 1 + } + + return (TemplateNode(title: title, color: color, command: command, children: children), idx) + } + + // MARK: - Block Scalar + + private static func readBlockScalar( + lines: [String], from startIdx: Int, baseIndent: Int + ) -> (String, Int) { + var result: [String] = [] + var idx = startIdx + + while idx < lines.count { + let line = lines[idx] + if line.trimmingCharacters(in: .whitespaces).isEmpty { + var nextNonEmpty = idx + 1 + while nextNonEmpty < lines.count && + lines[nextNonEmpty].trimmingCharacters(in: .whitespaces).isEmpty { + nextNonEmpty += 1 + } + if nextNonEmpty < lines.count && indentLevel(of: lines[nextNonEmpty]) >= baseIndent { + result.append("") + idx += 1 + continue + } + break + } + let lineIndent = indentLevel(of: line) + if lineIndent < baseIndent { break } + let content = String(line.dropFirst(min(baseIndent, line.count))) + result.append(content) + idx += 1 + } + + return (result.joined(separator: "\n").trimmingCharacters(in: .newlines), idx) + } + + // MARK: - Legacy Format + + private static func parseLegacyFormat(_ lines: [String]) throws -> WorkspaceTemplate { + var tabs: [TemplateTabDefinition] = [] + var inTabs = false + var currentTitle: String? + var currentScript: String? + + for line in lines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { continue } + + if trimmed == "tabs:" { + inTabs = true + continue + } + guard inTabs else { continue } + + if trimmed.hasPrefix("- title:") { + if let title = currentTitle { + tabs.append(TemplateTabDefinition(title: title, startupScript: currentScript)) + } + currentTitle = extractYamlValue(trimmed, key: "- title:") + currentScript = nil + } else if trimmed.hasPrefix("startupScript:") { + currentScript = extractYamlValue(trimmed, key: "startupScript:") + } + } + if let title = currentTitle { + tabs.append(TemplateTabDefinition(title: title, startupScript: currentScript)) + } + + let children = tabs.map { tab in + TemplateNode(title: tab.title, color: nil, command: nil, children: []) + } + return WorkspaceTemplate(root: TemplateNode( + title: "Terminal", color: nil, command: nil, children: children + )) + } + + // MARK: - Serialization + + static func serialize(_ template: WorkspaceTemplate) -> String { + var lines: [String] = [] + lines.append("root:") + serializeNode(template.root, indent: 2, lines: &lines, isList: false) + return lines.joined(separator: "\n") + "\n" + } + + private static func serializeNode( + _ node: TemplateNode, indent: Int, lines: inout [String], isList: Bool + ) { + let pad = String(repeating: " ", count: indent) + let prefix = isList ? "- " : "" + lines.append("\(pad)\(prefix)title: \(node.title)") + let propPad = isList ? pad + " " : pad + if let color = node.color { + lines.append("\(propPad)color: \"\(color)\"") + } + if let command = node.command { + if command.contains("\n") { + lines.append("\(propPad)command: |") + for cmdLine in command.components(separatedBy: .newlines) { + lines.append("\(propPad) \(cmdLine)") + } + } else { + lines.append("\(propPad)command: \(command)") + } + } + if !node.children.isEmpty { + lines.append("\(propPad)children:") + for child in node.children { + serializeNode(child, indent: indent + (isList ? 4 : 2), lines: &lines, isList: true) + } + } + } + + // MARK: - Helpers + + static func indentLevel(of line: String) -> Int { + var count = 0 + for ch in line { + if ch == " " { count += 1 } + else { break } + } + return count + } + + static func extractYamlValue(_ line: String, key: String) -> String? { + guard let range = line.range(of: key) else { return nil } + let value = String(line[range.upperBound...]).trimmingCharacters(in: .whitespaces) + if value.isEmpty { return nil } + return value.trimmingCharacters(in: CharacterSet(charactersIn: "\"'")) + } +} + +enum TemplateParseError: Error { + case missingRoot +} diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index b7e8c8496cb8..33ebac41355d 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -2084,6 +2084,55 @@ class TerminalController { case "workspace.remote.terminal_session_end": return v2Result(id: id, self.v2WorkspaceRemoteTerminalSessionEnd(params: params)) + // Groups + case "group.create": + return v2Result(id: id, self.v2GroupCreate(params: params)) + case "group.list": + return v2Result(id: id, self.v2GroupList(params: params)) + case "group.delete": + return v2Result(id: id, self.v2GroupDelete(params: params)) + case "group.collapse": + return v2Result(id: id, self.v2GroupCollapse(params: params)) + case "group.expand": + return v2Result(id: id, self.v2GroupExpand(params: params)) + case "group.rename": + return v2Result(id: id, self.v2GroupRename(params: params)) + case "group.set_color": + return v2Result(id: id, self.v2GroupSetColor(params: params)) + case "group.add_workspace": + return v2Result(id: id, self.v2GroupAddWorkspace(params: params)) + case "group.remove_workspace": + return v2Result(id: id, self.v2GroupRemoveWorkspace(params: params)) + + case "group.install_template": + return v2Result(id: id, self.v2GroupInstallTemplate(params: params)) + + // Project + case "project.open": + return v2Result(id: id, self.v2ProjectOpen(params: params)) + case "project.open_template": + return v2Result(id: id, self.v2ProjectOpenTemplate(params: params)) + + // Scripts + case "script.list": + return v2Result(id: id, self.v2ScriptList(params: params)) + case "script.get": + return v2Result(id: id, self.v2ScriptGet(params: params)) + case "script.save": + return v2Result(id: id, self.v2ScriptSave(params: params)) + case "script.delete": + return v2Result(id: id, self.v2ScriptDelete(params: params)) + + // Templates + case "template.list": + return v2Result(id: id, self.v2TemplateList(params: params)) + case "template.get": + return v2Result(id: id, self.v2TemplateGet(params: params)) + case "template.save": + return v2Result(id: id, self.v2TemplateSave(params: params)) + case "template.delete": + return v2Result(id: id, self.v2TemplateDelete(params: params)) + // Settings case "settings.open": return v2Result(id: id, self.v2SettingsOpen(params: params)) @@ -2573,6 +2622,26 @@ class TerminalController { "browser.input_mouse", "browser.input_keyboard", "browser.input_touch", + "group.create", + "group.list", + "group.delete", + "group.collapse", + "group.expand", + "group.rename", + "group.set_color", + "group.add_workspace", + "group.remove_workspace", + "group.install_template", + "project.open", + "project.open_template", + "script.list", + "script.get", + "script.save", + "script.delete", + "template.list", + "template.get", + "template.save", + "template.delete", ] #if DEBUG methods.append(contentsOf: [ @@ -2911,7 +2980,7 @@ class TerminalController { return NSNull() } - private func v2MainSync(_ body: () -> T) -> T { + func v2MainSync(_ body: () -> T) -> T { if Thread.isMainThread { return body() } @@ -2938,7 +3007,7 @@ class TerminalController { ]) } - private enum V2CallResult { + enum V2CallResult { case ok(Any) case err(code: String, message: String, data: Any?) } @@ -3174,7 +3243,7 @@ class TerminalController { // MARK: - V2 Context Resolution - private func v2ResolveTabManager(params: [String: Any]) -> TabManager? { + func v2ResolveTabManager(params: [String: Any]) -> TabManager? { // Prefer explicit window_id routing. Fall back to global lookup by workspace_id/surface_id/tab_id, // and finally to the active window's TabManager. if let windowId = v2UUID(params, "window_id") { diff --git a/Sources/TerminalControllerGroupCommands.swift b/Sources/TerminalControllerGroupCommands.swift new file mode 100644 index 000000000000..638189d88c70 --- /dev/null +++ b/Sources/TerminalControllerGroupCommands.swift @@ -0,0 +1,188 @@ +import Foundation + +/// Socket API commands for workspace parent-child management. +/// In the new model, workspaces themselves are groups — a workspace with children +/// is still a clickable workspace with its own terminal. +extension TerminalController { + + // MARK: - Group Commands (workspace-as-group model) + + func v2GroupCreate(params: [String: Any]) -> V2CallResult { + // In the new model, "creating a group" means creating a parent workspace. + // The workspace is a normal workspace that can have children added to it. + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + let ws = tm.addWorkspace(select: false) + if let title = params["title"] as? String { + ws.title = title + } + if let color = params["color"] as? String { + ws.customColor = color + } + return .ok(["workspace_id": ws.id.uuidString]) + } + } + + func v2GroupList(params: [String: Any]) -> V2CallResult { + v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + let tree = tm.items.compactMap { wsId -> [String: Any]? in + guard let ws = tm.workspace(for: wsId) else { return nil } + return serializeWorkspaceTree(ws, tabManager: tm) + } + return .ok(["workspaces": tree]) + } + } + + func v2GroupDelete(params: [String: Any]) -> V2CallResult { + guard let wsIdStr = params["group_id"] as? String ?? params["workspace_id"] as? String, + let wsId = UUID(uuidString: wsIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'workspace_id'", data: nil) + } + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let ws = tm.workspace(for: wsId) else { + return V2CallResult.err(code: "not_found", message: "Workspace not found", data: nil) + } + tm.closeWorkspace(ws) + return .ok(["deleted": true]) + } + } + + func v2GroupCollapse(params: [String: Any]) -> V2CallResult { + guard let wsIdStr = params["group_id"] as? String ?? params["workspace_id"] as? String, + let wsId = UUID(uuidString: wsIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'workspace_id'", data: nil) + } + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let ws = tm.workspace(for: wsId) else { + return V2CallResult.err(code: "not_found", message: "Workspace not found", data: nil) + } + ws.isCollapsed = true + tm.items = tm.groupManager.items + return .ok(["collapsed": true]) + } + } + + func v2GroupExpand(params: [String: Any]) -> V2CallResult { + guard let wsIdStr = params["group_id"] as? String ?? params["workspace_id"] as? String, + let wsId = UUID(uuidString: wsIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'workspace_id'", data: nil) + } + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let ws = tm.workspace(for: wsId) else { + return V2CallResult.err(code: "not_found", message: "Workspace not found", data: nil) + } + ws.isCollapsed = false + tm.items = tm.groupManager.items + return .ok(["expanded": true]) + } + } + + func v2GroupRename(params: [String: Any]) -> V2CallResult { + guard let wsIdStr = params["group_id"] as? String ?? params["workspace_id"] as? String, + let wsId = UUID(uuidString: wsIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'workspace_id'", data: nil) + } + guard let title = params["title"] as? String else { + return .err(code: "missing_param", message: "Missing 'title'", data: nil) + } + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let ws = tm.workspace(for: wsId) else { + return V2CallResult.err(code: "not_found", message: "Workspace not found", data: nil) + } + ws.title = title + return .ok(["renamed": true]) + } + } + + func v2GroupSetColor(params: [String: Any]) -> V2CallResult { + guard let wsIdStr = params["group_id"] as? String ?? params["workspace_id"] as? String, + let wsId = UUID(uuidString: wsIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'workspace_id'", data: nil) + } + let color = params["color"] as? String + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let ws = tm.workspace(for: wsId) else { + return V2CallResult.err(code: "not_found", message: "Workspace not found", data: nil) + } + ws.customColor = color + return .ok(["color_set": true]) + } + } + + func v2GroupAddWorkspace(params: [String: Any]) -> V2CallResult { + guard let parentIdStr = params["group_id"] as? String ?? params["parent_id"] as? String, + let parentId = UUID(uuidString: parentIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'parent_id'", data: nil) + } + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let child = tm.addChildWorkspace(for: parentId) else { + return V2CallResult.err(code: "max_depth", message: "Cannot add child (max depth 3)", data: nil) + } + return .ok(["workspace_id": child.id.uuidString]) + } + } + + func v2GroupRemoveWorkspace(params: [String: Any]) -> V2CallResult { + guard let wsIdStr = params["workspace_id"] as? String, + let wsId = UUID(uuidString: wsIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'workspace_id'", data: nil) + } + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + // Remove from parent's children and promote to top-level + if let parent = tm.groupManager.parentWorkspace(of: wsId) { + tm.groupManager.removeChildId(wsId, from: parent.id) + tm.groupManager.registerWorkspaceAsStandalone(wsId) + tm.items = tm.groupManager.items + } + return .ok(["removed": true]) + } + } + + // MARK: - Serialization + + private func serializeWorkspaceTree( + _ ws: Workspace, tabManager: TabManager + ) -> [String: Any] { + var result: [String: Any] = [ + "id": ws.id.uuidString, + "title": ws.title, + "working_directory": ws.currentDirectory, + "is_collapsed": ws.isCollapsed, + "has_children": ws.hasChildren + ] + if let color = ws.customColor { result["color"] = color } + if ws.hasChildren { + result["children"] = ws.childWorkspaceIds.compactMap { childId -> [String: Any]? in + guard let child = tabManager.workspace(for: childId) else { return nil } + return serializeWorkspaceTree(child, tabManager: tabManager) + } + } + return result + } +} diff --git a/Sources/TerminalControllerProjectCommands.swift b/Sources/TerminalControllerProjectCommands.swift new file mode 100644 index 000000000000..297f462527a8 --- /dev/null +++ b/Sources/TerminalControllerProjectCommands.swift @@ -0,0 +1,271 @@ +import Foundation + +/// Socket API commands for project opening and template-based project creation. +extension TerminalController { + + // MARK: - Project Open + + func v2ProjectOpen(params: [String: Any]) -> V2CallResult { + guard let path = params["path"] as? String else { + return .err(code: "missing_param", message: "Missing 'path'", data: nil) + } + let resolvedPath = (path as NSString).expandingTildeInPath + let dirURL = URL(fileURLWithPath: resolvedPath).standardizedFileURL + + var isDir: ObjCBool = false + guard FileManager.default.fileExists(atPath: dirURL.path, isDirectory: &isDir), + isDir.boolValue else { + return .err(code: "not_directory", message: "Path is not a directory: \(path)", data: nil) + } + + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + + // Dedupe: check all windows for a parent workspace already targeting this directory + let canonicalPath = dirURL.resolvingSymlinksInPath().path + if let existing = findExistingProjectWorkspace(canonicalPath: canonicalPath, targetTm: tm) { + return existing + } + + // Try reading .cmux.yaml + let configURL = dirURL.appendingPathComponent(".cmux.yaml") + if let yamlContent = try? String(contentsOf: configURL, encoding: .utf8) { + do { + let result = try CmuxConfigParser.parse( + yaml: yamlContent, + projectDirectory: dirURL, + scriptRepository: ScriptRepository.shared + ) + // Create parent workspace for the project + let parentWs = tm.addWorkspace( + workingDirectory: dirURL.path, + select: true + ) + parentWs.title = result.projectName + parentWs.customColor = result.projectColor + + let scriptRunner = StartupScriptRunner() + for tabDef in result.tabDefinitions { + let childWs = tm.addWorkspace( + workingDirectory: dirURL.path, + select: false, + skipStandaloneRegistration: true + ) + childWs.title = tabDef.title + tm.groupManager.addChildId(childWs.id, to: parentWs.id) + if let scriptName = tabDef.startupScript, + let scriptContent = ScriptRepository.shared.getScript(named: scriptName), + scriptRunner.shouldRunScript(isRestore: false), + let panelId = childWs.focusedPanelId ?? childWs.panels.values.first(where: { $0 is TerminalPanel })?.id { + scriptRunner.scheduleScript(content: scriptContent, workspace: childWs, panelId: panelId) + } + } + tm.items = tm.groupManager.items + tm.selectedTabId = parentWs.id + return .ok(["workspace_id": parentWs.id.uuidString, "dedupe": false]) + } catch { + // Fall through to single-workspace fallback on parse error + } + } + + // Fallback: create a single workspace with the directory name + let projectName = dirURL.lastPathComponent + let ws = tm.addWorkspace(workingDirectory: dirURL.path, select: true) + ws.title = projectName + return .ok(["workspace_id": ws.id.uuidString, "dedupe": false]) + } + } + + // MARK: - Project Open Template + + func v2ProjectOpenTemplate(params: [String: Any]) -> V2CallResult { + guard let path = params["path"] as? String else { + return .err(code: "missing_param", message: "Missing 'path'", data: nil) + } + guard let templateName = params["template"] as? String else { + return .err(code: "missing_param", message: "Missing 'template'", data: nil) + } + + let resolvedPath = (path as NSString).expandingTildeInPath + let dirURL = URL(fileURLWithPath: resolvedPath).standardizedFileURL + + var isDir: ObjCBool = false + guard FileManager.default.fileExists(atPath: dirURL.path, isDirectory: &isDir), + isDir.boolValue else { + return .err(code: "not_directory", message: "Path is not a directory: \(path)", data: nil) + } + + let template: WorkspaceTemplate + do { + template = try TemplateRepository.shared.getTemplate(named: templateName) + } catch { + return .err(code: "not_found", message: "Template '\(templateName)' not found", data: nil) + } + + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + + // Dedupe: check all windows for a parent workspace already targeting this directory + let canonicalPath = dirURL.resolvingSymlinksInPath().path + if let existing = findExistingProjectWorkspace(canonicalPath: canonicalPath, targetTm: tm) { + return existing + } + + let scriptRunner = StartupScriptRunner() + + // Create root workspace + let rootWs = tm.addWorkspace(workingDirectory: dirURL.path, select: true) + rootWs.title = template.root.title + if let color = template.root.color { + rootWs.customColor = color + } + + // Schedule root command if any + if let command = template.root.command, + let panelId = rootWs.focusedPanelId ?? rootWs.panels.values.first(where: { $0 is TerminalPanel })?.id { + scriptRunner.scheduleCommand(command, workspace: rootWs, panelId: panelId) + } + + // Create children recursively + var createdIds: [String] = [rootWs.id.uuidString] + createChildWorkspaces( + children: template.root.children, + parentId: rootWs.id, + workingDirectory: dirURL.path, + tabManager: tm, + scriptRunner: scriptRunner, + createdIds: &createdIds + ) + + tm.items = tm.groupManager.items + tm.selectedTabId = rootWs.id + return .ok([ + "workspace_id": rootWs.id.uuidString, + "workspace_ids": createdIds, + "dedupe": false + ]) + } + } + + /// Recursively create child workspaces from a template node tree. + private func createChildWorkspaces( + children: [TemplateNode], + parentId: UUID, + workingDirectory: String, + tabManager tm: TabManager, + scriptRunner: StartupScriptRunner, + createdIds: inout [String] + ) { + for child in children { + let ws = tm.addWorkspace( + workingDirectory: workingDirectory, + select: false, + eagerLoadTerminal: true, + skipStandaloneRegistration: true + ) + ws.title = child.title + if let color = child.color { + ws.customColor = color + } + tm.groupManager.addChildId(ws.id, to: parentId) + createdIds.append(ws.id.uuidString) + + if let command = child.command, + let panelId = ws.focusedPanelId ?? ws.panels.values.first(where: { $0 is TerminalPanel })?.id { + scriptRunner.scheduleCommand(command, workspace: ws, panelId: panelId) + } + + // Recurse for nested children (max depth enforced by group manager) + if !child.children.isEmpty { + createChildWorkspaces( + children: child.children, + parentId: ws.id, + workingDirectory: workingDirectory, + tabManager: tm, + scriptRunner: scriptRunner, + createdIds: &createdIds + ) + } + } + } + + // MARK: - Legacy Template Installation + + func v2GroupInstallTemplate(params: [String: Any]) -> V2CallResult { + guard let parentIdStr = params["group_id"] as? String ?? params["workspace_id"] as? String, + let parentId = UUID(uuidString: parentIdStr) else { + return .err(code: "missing_param", message: "Missing or invalid 'group_id'/'workspace_id'", data: nil) + } + guard let templateName = params["template"] as? String else { + return .err(code: "missing_param", message: "Missing 'template'", data: nil) + } + + let template: WorkspaceTemplate + do { + template = try TemplateRepository.shared.getTemplate(named: templateName) + } catch { + return .err(code: "not_found", message: "Template '\(templateName)' not found", data: nil) + } + + return v2MainSync { + guard let tm = v2ResolveTabManager(params: params) else { + return V2CallResult.err(code: "no_window", message: "No window found", data: nil) + } + guard let parentWs = tm.workspace(for: parentId) else { + return V2CallResult.err(code: "not_found", message: "Workspace not found", data: nil) + } + + let workDir = parentWs.currentDirectory + let scriptRunner = StartupScriptRunner() + var createdIds: [String] = [] + + for child in template.root.children { + let ws = tm.addWorkspace( + workingDirectory: workDir, + select: false, + skipStandaloneRegistration: true + ) + ws.title = child.title + if let color = child.color { + ws.customColor = color + } + tm.groupManager.addChildId(ws.id, to: parentId) + createdIds.append(ws.id.uuidString) + + if let command = child.command, + let panelId = ws.focusedPanelId ?? ws.panels.values.first(where: { $0 is TerminalPanel })?.id { + scriptRunner.scheduleCommand(command, workspace: ws, panelId: panelId) + } + } + tm.items = tm.groupManager.items + return .ok(["workspace_id": parentId.uuidString, "workspace_ids": createdIds]) + } + } + + // MARK: - Private + + /// Search all windows' TabManagers for a parent workspace already targeting this directory. + private func findExistingProjectWorkspace( + canonicalPath: String, targetTm: TabManager + ) -> V2CallResult? { + guard let appDelegate = AppDelegate.shared else { return nil } + for tm in appDelegate.allTabManagers() { + for wsId in tm.items { + guard let ws = tm.workspace(for: wsId), + ws.hasChildren else { continue } + let wsPath = URL(fileURLWithPath: ws.currentDirectory) + .resolvingSymlinksInPath().path + if wsPath == canonicalPath { + tm.selectedTabId = ws.id + tm.window?.makeKeyAndOrderFront(nil) + return .ok(["workspace_id": ws.id.uuidString, "dedupe": true]) + } + } + } + return nil + } +} diff --git a/Sources/TerminalControllerScriptTemplateCommands.swift b/Sources/TerminalControllerScriptTemplateCommands.swift new file mode 100644 index 000000000000..1dbaa2801a59 --- /dev/null +++ b/Sources/TerminalControllerScriptTemplateCommands.swift @@ -0,0 +1,119 @@ +import Foundation + +/// Socket API commands for script and template CRUD operations. +extension TerminalController { + + // MARK: - Script CRUD + + func v2ScriptList(params: [String: Any]) -> V2CallResult { + let scripts = ScriptRepository.shared.listScripts() + return .ok(["scripts": scripts]) + } + + func v2ScriptGet(params: [String: Any]) -> V2CallResult { + guard let name = params["name"] as? String else { + return .err(code: "missing_param", message: "Missing 'name'", data: nil) + } + guard let content = ScriptRepository.shared.getScript(named: name) else { + return .err(code: "not_found", message: "Script '\(name)' not found", data: nil) + } + return .ok(["name": name, "content": content]) + } + + func v2ScriptSave(params: [String: Any]) -> V2CallResult { + guard let name = params["name"] as? String else { + return .err(code: "missing_param", message: "Missing 'name'", data: nil) + } + guard let content = params["content"] as? String else { + return .err(code: "missing_param", message: "Missing 'content'", data: nil) + } + do { + try ScriptRepository.shared.saveScript(named: name, content: content) + return .ok(["saved": true]) + } catch { + return .err(code: "write_error", message: error.localizedDescription, data: nil) + } + } + + func v2ScriptDelete(params: [String: Any]) -> V2CallResult { + guard let name = params["name"] as? String else { + return .err(code: "missing_param", message: "Missing 'name'", data: nil) + } + do { + try ScriptRepository.shared.deleteScript(named: name) + return .ok(["deleted": true]) + } catch { + return .err(code: "delete_error", message: error.localizedDescription, data: nil) + } + } + + // MARK: - Template CRUD + + func v2TemplateList(params: [String: Any]) -> V2CallResult { + let templates = TemplateRepository.shared.listTemplates() + return .ok(["templates": templates]) + } + + func v2TemplateGet(params: [String: Any]) -> V2CallResult { + guard let name = params["name"] as? String else { + return .err(code: "missing_param", message: "Missing 'name'", data: nil) + } + do { + let template = try TemplateRepository.shared.getTemplate(named: name) + let result = serializeTemplateNode(template.root) + return .ok(["name": name, "root": result]) + } catch { + return .err(code: "not_found", message: "Template '\(name)' not found", data: nil) + } + } + + func v2TemplateSave(params: [String: Any]) -> V2CallResult { + guard let name = params["name"] as? String else { + return .err(code: "missing_param", message: "Missing 'name'", data: nil) + } + guard let rootDict = params["root"] as? [String: Any] else { + return .err(code: "missing_param", message: "Missing 'root' object", data: nil) + } + let root = deserializeTemplateNode(rootDict) + let template = WorkspaceTemplate(root: root) + do { + try TemplateRepository.shared.saveTemplate(named: name, template: template) + return .ok(["saved": true]) + } catch { + return .err(code: "write_error", message: error.localizedDescription, data: nil) + } + } + + func v2TemplateDelete(params: [String: Any]) -> V2CallResult { + guard let name = params["name"] as? String else { + return .err(code: "missing_param", message: "Missing 'name'", data: nil) + } + do { + try TemplateRepository.shared.deleteTemplate(named: name) + return .ok(["deleted": true]) + } catch { + return .err(code: "delete_error", message: error.localizedDescription, data: nil) + } + } + + // MARK: - Template Serialization Helpers + + private func serializeTemplateNode(_ node: TemplateNode) -> [String: Any] { + var result: [String: Any] = ["title": node.title] + if let color = node.color { result["color"] = color } + if let command = node.command { result["command"] = command } + if !node.children.isEmpty { + result["children"] = node.children.map { serializeTemplateNode($0) } + } + return result + } + + private func deserializeTemplateNode(_ dict: [String: Any]) -> TemplateNode { + let title = dict["title"] as? String ?? "Workspace" + let color = dict["color"] as? String + let command = dict["command"] as? String + let childDicts = dict["children"] as? [[String: Any]] ?? [] + let children = childDicts.map { deserializeTemplateNode($0) } + return TemplateNode(title: title, color: color, command: command, children: children) + } +} diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 344b3a2bba17..59fdacf61e11 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -565,7 +565,7 @@ struct HiddenTitlebarSidebarControlsView: View { anchorView: viewModel.notificationsAnchorView ) }, - onNewTab: { _ = AppDelegate.shared?.tabManager?.addTab() }, + onNewTab: { _ = AppDelegate.shared?.tabManager?.addWorkspaceViaDialog() }, visibilityMode: .onHover ) .frame(width: hostWidth, height: hostHeight, alignment: .leading) @@ -789,7 +789,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont self.notificationStore = notificationStore let toggleSidebar = { _ = AppDelegate.shared?.sidebarState?.toggle() } let toggleNotifications: () -> Void = { _ = AppDelegate.shared?.toggleNotificationsPopover(animated: true) } - let newTab = { _ = AppDelegate.shared?.tabManager?.addTab() } + let newTab = { _ = AppDelegate.shared?.tabManager?.addWorkspaceViaDialog() } hostingView = NonDraggableHostingView( rootView: TitlebarControlsView( diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index b2c0ca68d2f4..7fafcf803467 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -207,7 +207,8 @@ extension Workspace { statusEntries: statusSnapshots, logEntries: logSnapshots, progress: progressSnapshot, - gitBranch: gitBranchSnapshot + gitBranch: gitBranchSnapshot, + startupCommand: startupCommand ) } @@ -255,6 +256,7 @@ extension Workspace { } progress = snapshot.progress.map { SidebarProgressState(value: $0.value, label: $0.label) } gitBranch = snapshot.gitBranch.map { SidebarGitBranchState(branch: $0.branch, isDirty: $0.isDirty) } + startupCommand = snapshot.startupCommand recomputeListeningPorts() @@ -4964,6 +4966,17 @@ final class Workspace: Identifiable, ObservableObject { @Published var isPinned: Bool = false @Published var customColor: String? // hex string, e.g. "#C0392B" @Published var currentDirectory: String + /// IDs of child workspaces nested under this workspace in the sidebar. + @Published var childWorkspaceIds: [UUID] = [] + /// Whether this workspace's children are collapsed in the sidebar. + @Published var isCollapsed: Bool = false + /// True when this workspace has at least one child workspace. + var hasChildren: Bool { !childWorkspaceIds.isEmpty } + /// Name of a startup script from ScriptRepository to run when this workspace is opened. + var startupScriptName: String? + /// The command text that was run when this workspace was created from a template. + /// Persisted across sessions so it can be re-run on restore. + @Published var startupCommand: String? private(set) var preferredBrowserProfileID: UUID? /// Ordinal for CMUX_PORT range assignment (monotonically increasing per app session) @@ -5072,6 +5085,9 @@ final class Workspace: Identifiable, ObservableObject { return formatter }() private var panelShellActivityStates: [UUID: PanelShellActivityState] = [:] + /// One-shot callback fired when a panel first reaches promptIdle. + /// Keyed by panel ID. Removed after firing. + var onPromptReady: [UUID: () -> Void] = [:] /// PIDs associated with agent status entries (e.g. claude_code), keyed by status key. /// Used for stale-session detection: if the PID is dead, the status entry is cleared. var agentPIDs: [String: pid_t] = [:] @@ -5842,6 +5858,16 @@ final class Workspace: Identifiable, ObservableObject { "panel=\(panelId.uuidString.prefix(5)) from=\(previousState.rawValue) to=\(state.rawValue)" ) #endif + // Fire one-shot prompt-ready callback + if state == .promptIdle, let callback = onPromptReady.removeValue(forKey: panelId) { + callback() + } + } + + /// Whether the focused terminal panel is at a shell prompt (idle), not running a command. + var isFocusedPanelAtPrompt: Bool { + guard let panelId = focusedPanelId else { return false } + return panelShellActivityStates[panelId] == .promptIdle } func panelNeedsConfirmClose(panelId: UUID, fallbackNeedsConfirmClose: Bool) -> Bool { diff --git a/Sources/WorkspaceGroup.swift b/Sources/WorkspaceGroup.swift new file mode 100644 index 000000000000..7d80ed415c5a --- /dev/null +++ b/Sources/WorkspaceGroup.swift @@ -0,0 +1,3 @@ +// This file is intentionally empty. WorkspaceGroup has been replaced by +// parent-child relationships on Workspace itself. +// The file remains to avoid Xcode project reference errors until cleanup. diff --git a/Sources/WorkspaceGroupManager.swift b/Sources/WorkspaceGroupManager.swift new file mode 100644 index 000000000000..3765b4a76e02 --- /dev/null +++ b/Sources/WorkspaceGroupManager.swift @@ -0,0 +1,206 @@ +import Foundation +import Combine + +/// Manages parent-child workspace relationships in the sidebar. +/// Workspaces themselves hold their `childWorkspaceIds` and `isCollapsed` state. +/// This manager maintains the flat `items` array of top-level workspace IDs +/// and provides helper methods for tree operations. +/// +/// Invariants: +/// - Every workspace appears at most once (either in `items` or as a child). +/// - No orphaned children — removing a parent cascades to children. +/// - Maximum nesting depth: 3 levels. +@MainActor +final class WorkspaceGroupManager: ObservableObject { + + @Published var items: [SidebarItem] = [] + private weak var tabManager: TabManager? + + init(tabManager: TabManager) { + self.tabManager = tabManager + } + + // MARK: - Child Workspace Management + + /// Creates a new child workspace under the given parent. + /// Returns nil if the parent is already at max depth (3). + /// The caller is responsible for creating the actual Workspace object + /// and adding it to TabManager.tabs. + func addChildId(_ childId: UUID, to parentId: UUID) { + guard let parent = tabManager?.workspace(for: parentId) else { return } + parent.childWorkspaceIds.append(childId) + } + + func removeChildId(_ childId: UUID, from parentId: UUID) { + guard let parent = tabManager?.workspace(for: parentId) else { return } + parent.childWorkspaceIds.removeAll { $0 == childId } + } + + // MARK: - Top-Level Registration + + func registerWorkspaceAsStandalone(_ workspaceId: UUID) { + guard !items.contains(workspaceId) else { return } + // Don't register if it's already a child of another workspace + guard parentWorkspace(of: workspaceId) == nil else { return } + items.append(workspaceId) + } + + /// Remove a workspace from the sidebar entirely (top-level and as child). + func removeWorkspace(_ workspaceId: UUID) { + items.removeAll { $0 == workspaceId } + // Also remove from any parent's childWorkspaceIds + if let parent = parentWorkspace(of: workspaceId) { + parent.childWorkspaceIds.removeAll { $0 == workspaceId } + } + } + + // MARK: - Collapse + + func toggleCollapsed(_ workspaceId: UUID) { + guard let ws = tabManager?.workspace(for: workspaceId), ws.hasChildren else { return } + ws.isCollapsed.toggle() + } + + // MARK: - Queries + + /// Find the parent workspace of a given workspace ID. + func parentWorkspace(of childId: UUID) -> Workspace? { + guard let tabManager else { return nil } + return tabManager.tabs.first { ws in + ws.childWorkspaceIds.contains(childId) + } + } + + /// Depth of a workspace: 1 for top-level, 2 for child, 3 for grandchild. 0 if not found. + func depthOf(workspaceId: UUID) -> Int { + if items.contains(workspaceId) { return 1 } + guard let parent = parentWorkspace(of: workspaceId) else { return 0 } + if items.contains(parent.id) { return 2 } + if parentWorkspace(of: parent.id) != nil { return 3 } + return 0 + } + + /// Flattened list of visible workspace IDs, skipping collapsed children. + func visibleWorkspaces() -> [Workspace] { + guard let tabManager else { return [] } + var result: [Workspace] = [] + for wsId in items { + guard let ws = tabManager.workspace(for: wsId) else { continue } + result.append(ws) + if ws.hasChildren && !ws.isCollapsed { + collectVisibleChildren(of: ws, into: &result, tabManager: tabManager) + } + } + return result + } + + /// All workspace IDs that are descendants of the given workspace. + func allDescendantIds(of workspaceId: UUID) -> [UUID] { + guard let ws = tabManager?.workspace(for: workspaceId) else { return [] } + var result: [UUID] = [] + collectDescendantIds(of: ws, into: &result) + return result + } + + // MARK: - Indent / Outdent (Tab / Shift-Tab) + + /// Indent: make the workspace a child of the sibling directly above it at the same level. + /// Returns true if the mutation was applied. + @discardableResult + func indentWorkspace(_ workspaceId: UUID) -> Bool { + guard let tabManager else { return false } + + // Case A: workspace is top-level + if let idx = items.firstIndex(of: workspaceId) { + guard idx > 0 else { return false } + let siblingAboveId = items[idx - 1] + guard let siblingAbove = tabManager.workspace(for: siblingAboveId) else { return false } + // Check depth constraint: workspace + its descendants must not exceed depth 3 + let currentSubtreeDepth = maxDescendantDepth(of: workspaceId) + let siblingDepth = depthOf(workspaceId: siblingAboveId) + // After indent, workspace will be at siblingDepth + 1 + // Its deepest descendant will be at siblingDepth + 1 + (currentSubtreeDepth - 1) + if siblingDepth + currentSubtreeDepth > 3 { return false } + + items.remove(at: idx) + siblingAbove.childWorkspaceIds.append(workspaceId) + return true + } + + // Case B: workspace is a child of some parent + if let parent = parentWorkspace(of: workspaceId) { + guard let childIdx = parent.childWorkspaceIds.firstIndex(of: workspaceId), + childIdx > 0 else { return false } + let siblingAboveId = parent.childWorkspaceIds[childIdx - 1] + guard let siblingAbove = tabManager.workspace(for: siblingAboveId) else { return false } + + let currentSubtreeDepth = maxDescendantDepth(of: workspaceId) + let siblingDepth = depthOf(workspaceId: siblingAboveId) + if siblingDepth + currentSubtreeDepth > 3 { return false } + + parent.childWorkspaceIds.remove(at: childIdx) + siblingAbove.childWorkspaceIds.append(workspaceId) + return true + } + + return false + } + + /// Outdent: move the workspace to its parent's level, inserted right after its parent. + /// Children come with it. Returns true if the mutation was applied. + @discardableResult + func outdentWorkspace(_ workspaceId: UUID) -> Bool { + guard let tabManager else { return false } + guard let parent = parentWorkspace(of: workspaceId) else { return false } + + // Remove from parent's children + parent.childWorkspaceIds.removeAll { $0 == workspaceId } + + // Find where parent lives and insert after it + if let grandparent = parentWorkspace(of: parent.id) { + // Parent is a child itself — insert in grandparent's children after parent + if let parentIdx = grandparent.childWorkspaceIds.firstIndex(of: parent.id) { + grandparent.childWorkspaceIds.insert(workspaceId, at: parentIdx + 1) + } + } else if let parentTopIdx = items.firstIndex(of: parent.id) { + // Parent is top-level — insert in items after parent + items.insert(workspaceId, at: parentTopIdx + 1) + } + + return true + } + + /// Maximum depth of the subtree rooted at the given workspace (1 = leaf). + private func maxDescendantDepth(of workspaceId: UUID) -> Int { + guard let ws = tabManager?.workspace(for: workspaceId) else { return 1 } + if ws.childWorkspaceIds.isEmpty { return 1 } + var maxChild = 0 + for childId in ws.childWorkspaceIds { + maxChild = max(maxChild, maxDescendantDepth(of: childId)) + } + return 1 + maxChild + } + + // MARK: - Private + + private func collectVisibleChildren( + of workspace: Workspace, into result: inout [Workspace], tabManager: TabManager + ) { + for childId in workspace.childWorkspaceIds { + guard let child = tabManager.workspace(for: childId) else { continue } + result.append(child) + if child.hasChildren && !child.isCollapsed { + collectVisibleChildren(of: child, into: &result, tabManager: tabManager) + } + } + } + + private func collectDescendantIds(of workspace: Workspace, into result: inout [UUID]) { + for childId in workspace.childWorkspaceIds { + result.append(childId) + if let child = tabManager?.workspace(for: childId) { + collectDescendantIds(of: child, into: &result) + } + } + } +} diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index debc66978b2e..2e7249364690 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -444,6 +444,10 @@ struct cmuxApp: App { .disabled(!snapshot.hasNotifications) } + CommandMenu(String(localized: "menu.scripts.title", defaultValue: "Scripts")) { + ScriptsMenuContent(activeTabManager: activeTabManager) + } + #if DEBUG CommandMenu("Debug") { Button("New Tab With Lorem Search Text") { diff --git a/cmuxTests/CmuxConfigParserTests.swift b/cmuxTests/CmuxConfigParserTests.swift new file mode 100644 index 000000000000..d46bd8bae503 --- /dev/null +++ b/cmuxTests/CmuxConfigParserTests.swift @@ -0,0 +1,127 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +/// Mock script repository for testing parser script validation. +final class MockScriptRepository: ScriptRepositoryProtocol { + let scripts: Set + + init(scripts: [String]) { + self.scripts = Set(scripts) + } + + func hasScript(named name: String) -> Bool { + scripts.contains(name) + } +} + +@MainActor +final class CmuxConfigParserTests: XCTestCase { + + func testParseSimpleConfig() throws { + let yaml = """ + name: MyProject + color: "#4A9EFF" + tabs: + - title: terminal + """ + let result = try CmuxConfigParser.parse( + yaml: yaml, + projectDirectory: URL(fileURLWithPath: "/tmp/project") + ) + XCTAssertEqual(result.projectName, "MyProject") + XCTAssertEqual(result.projectColor, "#4A9EFF") + XCTAssertTrue(result.warnings.isEmpty) + XCTAssertEqual(result.tabDefinitions.count, 1) + XCTAssertEqual(result.tabDefinitions[0].title, "terminal") + } + + func testParseConfigWithGroups() throws { + let yaml = """ + name: MyProject + groups: + - name: prod + workingDirectory: ./prod + tabs: + - title: claude + - title: terminal + - name: dev + workingDirectory: ./dev + tabs: + - title: terminal + """ + let result = try CmuxConfigParser.parse( + yaml: yaml, + projectDirectory: URL(fileURLWithPath: "/tmp/project") + ) + // Groups produce tab definitions (no separate group objects) + XCTAssertEqual(result.tabDefinitions.count, 3) + } + + func testParseMinimalConfig() throws { + let yaml = """ + name: Minimal + """ + let result = try CmuxConfigParser.parse( + yaml: yaml, + projectDirectory: URL(fileURLWithPath: "/tmp") + ) + XCTAssertEqual(result.projectName, "Minimal") + XCTAssertTrue(result.tabDefinitions.isEmpty) + } + + func testParseNestedGroupsInSubGroupProducesWarning() throws { + let yaml = """ + name: Test + groups: + - name: sub + groups: + - name: deep + tabs: + - title: terminal + """ + let result = try CmuxConfigParser.parse( + yaml: yaml, + projectDirectory: URL(fileURLWithPath: "/tmp") + ) + XCTAssertTrue(result.warnings.contains(where: { + if case .maxDepthExceeded = $0 { return true } + return false + })) + } + + func testParseConfigUsesDirectoryNameWhenNameMissing() throws { + let yaml = """ + tabs: + - title: terminal + """ + let result = try CmuxConfigParser.parse( + yaml: yaml, + projectDirectory: URL(fileURLWithPath: "/tmp/my-project") + ) + XCTAssertEqual(result.projectName, "my-project") + } + + func testParseGroupTabsExtracted() throws { + let yaml = """ + name: Test + groups: + - name: backend + workingDirectory: ./server + tabs: + - title: api + - title: worker + """ + let result = try CmuxConfigParser.parse( + yaml: yaml, + projectDirectory: URL(fileURLWithPath: "/tmp/project") + ) + XCTAssertEqual(result.tabDefinitions.count, 2) + XCTAssertEqual(result.tabDefinitions[0].title, "api") + XCTAssertEqual(result.tabDefinitions[1].title, "worker") + } +} diff --git a/cmuxTests/ScriptRepositoryTests.swift b/cmuxTests/ScriptRepositoryTests.swift new file mode 100644 index 000000000000..b5841a41a77f --- /dev/null +++ b/cmuxTests/ScriptRepositoryTests.swift @@ -0,0 +1,144 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +final class ScriptRepositoryTests: XCTestCase { + var tempDir: URL! + var repo: ScriptRepository! + + override func setUp() { + super.setUp() + tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-scripts-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + repo = ScriptRepository(directory: tempDir) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: tempDir) + super.tearDown() + } + + func testListScriptsReturnsFileNames() throws { + try "echo hello".write( + to: tempDir.appendingPathComponent("My Script.sh"), + atomically: true, + encoding: .utf8 + ) + let scripts = repo.listScripts() + XCTAssertEqual(scripts, ["My Script"]) + } + + func testListScriptsIgnoresNonShFiles() throws { + try "echo hello".write( + to: tempDir.appendingPathComponent("readme.txt"), + atomically: true, + encoding: .utf8 + ) + try "echo hello".write( + to: tempDir.appendingPathComponent("Script.sh"), + atomically: true, + encoding: .utf8 + ) + let scripts = repo.listScripts() + XCTAssertEqual(scripts, ["Script"]) + } + + func testListScriptsReturnsEmptyForMissingDirectory() { + let missingRepo = ScriptRepository( + directory: tempDir.appendingPathComponent("nonexistent") + ) + XCTAssertEqual(missingRepo.listScripts(), []) + } + + func testGetScriptReturnsContents() throws { + let content = "cd $CMUX_FOLDER\nclaude" + try content.write( + to: tempDir.appendingPathComponent("Claude.sh"), + atomically: true, + encoding: .utf8 + ) + let result = repo.getScript(named: "Claude") + XCTAssertEqual(result, content) + } + + func testGetScriptReturnsNilForMissing() { + XCTAssertNil(repo.getScript(named: "Nonexistent")) + } + + func testSaveScriptWritesFile() throws { + try repo.saveScript(named: "New Script", content: "echo test") + let path = tempDir.appendingPathComponent("New Script.sh") + XCTAssertTrue(FileManager.default.fileExists(atPath: path.path)) + let content = try String(contentsOf: path, encoding: .utf8) + XCTAssertEqual(content, "echo test") + } + + func testSaveScriptCreatesDirectory() throws { + let nestedDir = tempDir.appendingPathComponent("nested/scripts") + let nestedRepo = ScriptRepository(directory: nestedDir) + try nestedRepo.saveScript(named: "Test", content: "echo hi") + XCTAssertTrue(FileManager.default.fileExists( + atPath: nestedDir.appendingPathComponent("Test.sh").path + )) + } + + func testDeleteScriptRemovesFile() throws { + let path = tempDir.appendingPathComponent("Temp.sh") + try "test".write(to: path, atomically: true, encoding: .utf8) + try repo.deleteScript(named: "Temp") + XCTAssertFalse(FileManager.default.fileExists(atPath: path.path)) + } + + func testHasScriptReturnsTrueForExisting() throws { + try "test".write( + to: tempDir.appendingPathComponent("Exists.sh"), + atomically: true, + encoding: .utf8 + ) + XCTAssertTrue(repo.hasScript(named: "Exists")) + XCTAssertFalse(repo.hasScript(named: "Missing")) + } + + // MARK: - Default Script Seeding + + func testSeedDefaultScriptsCreatesAllFourScripts() { + repo.seedDefaultScripts() + let scripts = repo.listScripts() + XCTAssertTrue(scripts.contains("Builder")) + XCTAssertTrue(scripts.contains("Fixer")) + XCTAssertTrue(scripts.contains("Claude")) + XCTAssertTrue(scripts.contains("Codex")) + } + + func testSeedDefaultScriptsDoesNotOverwriteExisting() throws { + let customContent = "#!/bin/bash\necho custom builder" + try repo.saveScript(named: "Builder", content: customContent) + repo.seedDefaultScripts() + let result = repo.getScript(named: "Builder") + XCTAssertEqual(result, customContent) + } + + func testSeedDefaultScriptsCreatesOnlyMissing() throws { + let customContent = "#!/bin/bash\necho custom" + try repo.saveScript(named: "Claude", content: customContent) + repo.seedDefaultScripts() + // Claude should be untouched + XCTAssertEqual(repo.getScript(named: "Claude"), customContent) + // Others should be seeded + XCTAssertTrue(repo.hasScript(named: "Builder")) + XCTAssertTrue(repo.hasScript(named: "Fixer")) + XCTAssertTrue(repo.hasScript(named: "Codex")) + } + + func testSeedDefaultScriptsOnEmptyDirectoryPath() { + let freshDir = tempDir.appendingPathComponent("fresh") + let freshRepo = ScriptRepository(directory: freshDir) + freshRepo.seedDefaultScripts() + XCTAssertEqual(freshRepo.listScripts().count, 4) + } +} diff --git a/cmuxTests/SessionGroupPersistenceTests.swift b/cmuxTests/SessionGroupPersistenceTests.swift new file mode 100644 index 000000000000..8df672bead3e --- /dev/null +++ b/cmuxTests/SessionGroupPersistenceTests.swift @@ -0,0 +1,198 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +final class SessionGroupPersistenceTests: XCTestCase { + + // MARK: - Snapshot Round-Trip + + func testWorkspaceGroupSnapshotRoundTrip() throws { + let snapshot = SessionWorkspaceGroupSnapshot( + title: "Project", + color: "#FF0000", + isCollapsed: true, + isPinned: false, + workingDirectory: "/tmp/project", + items: [ + .workspace(workspaceIndex: 0), + .workspace(workspaceIndex: 2), + .group(SessionWorkspaceGroupSnapshot( + title: "Sub", + color: nil, + isCollapsed: false, + isPinned: false, + workingDirectory: "/tmp/project/sub", + items: [.workspace(workspaceIndex: 1)] + )) + ] + ) + let data = try JSONEncoder().encode(snapshot) + let decoded = try JSONDecoder().decode(SessionWorkspaceGroupSnapshot.self, from: data) + XCTAssertEqual(decoded.title, "Project") + XCTAssertEqual(decoded.color, "#FF0000") + XCTAssertTrue(decoded.isCollapsed) + XCTAssertFalse(decoded.isPinned) + XCTAssertEqual(decoded.workingDirectory, "/tmp/project") + XCTAssertEqual(decoded.items.count, 3) + } + + func testSidebarLayoutSnapshotRoundTrip() throws { + let layout = SessionSidebarLayoutSnapshot(items: [ + .standalone(workspaceIndex: 0), + .group(SessionWorkspaceGroupSnapshot( + title: "G", + color: nil, + isCollapsed: false, + isPinned: true, + workingDirectory: "/tmp", + items: [.workspace(workspaceIndex: 1)] + )) + ]) + let data = try JSONEncoder().encode(layout) + let decoded = try JSONDecoder().decode(SessionSidebarLayoutSnapshot.self, from: data) + XCTAssertEqual(decoded.items.count, 2) + } + + func testSidebarItemSnapshotStandaloneRoundTrip() throws { + let item = SessionSidebarItemSnapshot.standalone(workspaceIndex: 5) + let data = try JSONEncoder().encode(item) + let decoded = try JSONDecoder().decode(SessionSidebarItemSnapshot.self, from: data) + if case .standalone(let index) = decoded { + XCTAssertEqual(index, 5) + } else { + XCTFail("Expected standalone") + } + } + + func testGroupItemSnapshotWorkspaceRoundTrip() throws { + let item = SessionGroupItemSnapshot.workspace(workspaceIndex: 3) + let data = try JSONEncoder().encode(item) + let decoded = try JSONDecoder().decode(SessionGroupItemSnapshot.self, from: data) + if case .workspace(let index) = decoded { + XCTAssertEqual(index, 3) + } else { + XCTFail("Expected workspace") + } + } + + // MARK: - Backward Compatibility + + func testBackwardCompatibilityWithNoSidebarLayout() throws { + let json = """ + {"selectedWorkspaceIndex": 0, "workspaces": []} + """ + let snapshot = try JSONDecoder().decode( + SessionTabManagerSnapshot.self, + from: json.data(using: .utf8)! + ) + XCTAssertNil(snapshot.sidebarLayout) + } + + func testTabManagerSnapshotWithSidebarLayoutRoundTrip() throws { + let snapshot = SessionTabManagerSnapshot( + selectedWorkspaceIndex: 0, + workspaces: [], + sidebarLayout: SessionSidebarLayoutSnapshot(items: [ + .standalone(workspaceIndex: 0), + .group(SessionWorkspaceGroupSnapshot( + title: "Test", + color: "#00FF00", + isCollapsed: false, + isPinned: false, + workingDirectory: "/tmp", + items: [.workspace(workspaceIndex: 1)] + )) + ]) + ) + let data = try JSONEncoder().encode(snapshot) + let decoded = try JSONDecoder().decode(SessionTabManagerSnapshot.self, from: data) + XCTAssertNotNil(decoded.sidebarLayout) + XCTAssertEqual(decoded.sidebarLayout?.items.count, 2) + } + + // MARK: - New Model Fields + + func testWorkspaceSnapshotChildIndicesRoundTrip() throws { + let snapshot = SessionWorkspaceSnapshot( + processTitle: "Terminal", + isPinned: false, + currentDirectory: "/tmp", + layout: .pane(SessionPaneLayoutSnapshot(panelIds: [], selectedPanelId: nil)), + panels: [], + statusEntries: [], + logEntries: [], + childWorkspaceIndices: [1, 2], + isCollapsed: true + ) + let data = try JSONEncoder().encode(snapshot) + let decoded = try JSONDecoder().decode(SessionWorkspaceSnapshot.self, from: data) + XCTAssertEqual(decoded.childWorkspaceIndices, [1, 2]) + XCTAssertEqual(decoded.isCollapsed, true) + } + + func testWorkspaceSnapshotChildIndicesNilByDefault() throws { + let json = """ + {"processTitle":"T","isPinned":false,"currentDirectory":"/tmp","layout":{"type":"pane","pane":{"panelIds":[]}},"panels":[],"statusEntries":[],"logEntries":[]} + """ + let decoded = try JSONDecoder().decode( + SessionWorkspaceSnapshot.self, + from: json.data(using: .utf8)! + ) + XCTAssertNil(decoded.childWorkspaceIndices) + XCTAssertNil(decoded.isCollapsed) + } + + func testTabManagerSnapshotTopLevelIndicesRoundTrip() throws { + let snapshot = SessionTabManagerSnapshot( + selectedWorkspaceIndex: 0, + workspaces: [], + topLevelWorkspaceIndices: [0, 2, 1] + ) + let data = try JSONEncoder().encode(snapshot) + let decoded = try JSONDecoder().decode(SessionTabManagerSnapshot.self, from: data) + XCTAssertEqual(decoded.topLevelWorkspaceIndices, [0, 2, 1]) + } + + // MARK: - Nested Group Snapshot + + func testNestedGroupSnapshotRoundTrip() throws { + let nested = SessionWorkspaceGroupSnapshot( + title: "Inner", + color: nil, + isCollapsed: true, + isPinned: false, + workingDirectory: "/tmp/inner", + items: [.workspace(workspaceIndex: 2)] + ) + let outer = SessionWorkspaceGroupSnapshot( + title: "Outer", + color: "#AABBCC", + isCollapsed: false, + isPinned: true, + workingDirectory: "/tmp/outer", + items: [ + .workspace(workspaceIndex: 0), + .group(nested), + .workspace(workspaceIndex: 1) + ] + ) + let data = try JSONEncoder().encode(outer) + let decoded = try JSONDecoder().decode(SessionWorkspaceGroupSnapshot.self, from: data) + XCTAssertEqual(decoded.title, "Outer") + XCTAssertTrue(decoded.isPinned) + XCTAssertEqual(decoded.items.count, 3) + + // Verify nested group decoded correctly + if case .group(let innerDecoded) = decoded.items[1] { + XCTAssertEqual(innerDecoded.title, "Inner") + XCTAssertTrue(innerDecoded.isCollapsed) + XCTAssertEqual(innerDecoded.items.count, 1) + } else { + XCTFail("Expected nested group at index 1") + } + } +} diff --git a/cmuxTests/TemplateRepositoryTests.swift b/cmuxTests/TemplateRepositoryTests.swift new file mode 100644 index 000000000000..acd314a0376f --- /dev/null +++ b/cmuxTests/TemplateRepositoryTests.swift @@ -0,0 +1,101 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +final class TemplateRepositoryTests: XCTestCase { + var tempDir: URL! + var repo: TemplateRepository! + + override func setUp() { + super.setUp() + tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-templates-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + repo = TemplateRepository(directory: tempDir) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: tempDir) + super.tearDown() + } + + func testListTemplates() throws { + let yaml = "tabs:\n - title: terminal\n" + try yaml.write( + to: tempDir.appendingPathComponent("Basic.yaml"), + atomically: true, + encoding: .utf8 + ) + let templates = repo.listTemplates() + XCTAssertEqual(templates, ["Basic"]) + } + + func testListTemplatesIgnoresNonYamlFiles() throws { + try "test".write( + to: tempDir.appendingPathComponent("readme.txt"), + atomically: true, + encoding: .utf8 + ) + XCTAssertEqual(repo.listTemplates(), []) + } + + func testListTemplatesReturnsEmptyForMissingDirectory() { + let missingRepo = TemplateRepository( + directory: tempDir.appendingPathComponent("nonexistent") + ) + XCTAssertEqual(missingRepo.listTemplates(), []) + } + + func testGetTemplateReturnsTabDefinitions() throws { + let yaml = """ + tabs: + - title: claude + startupScript: Standard Claude + - title: terminal + """ + try yaml.write( + to: tempDir.appendingPathComponent("AI Dev.yaml"), + atomically: true, + encoding: .utf8 + ) + let template = try repo.getTemplate(named: "AI Dev") + XCTAssertEqual(template.tabs.count, 2) + XCTAssertEqual(template.tabs[0].title, "claude") + XCTAssertEqual(template.tabs[0].startupScript, "Standard Claude") + XCTAssertEqual(template.tabs[1].title, "terminal") + XCTAssertNil(template.tabs[1].startupScript) + } + + func testSaveTemplateWritesYaml() throws { + let template = WorkspaceTemplate(tabs: [ + TemplateTabDefinition(title: "builder", startupScript: "Builder Script"), + TemplateTabDefinition(title: "terminal", startupScript: nil) + ]) + try repo.saveTemplate(named: "Custom", template: template) + let path = tempDir.appendingPathComponent("Custom.yaml") + XCTAssertTrue(FileManager.default.fileExists(atPath: path.path)) + + // Verify it can be read back + let loaded = try repo.getTemplate(named: "Custom") + XCTAssertEqual(loaded.tabs.count, 2) + XCTAssertEqual(loaded.tabs[0].title, "builder") + XCTAssertEqual(loaded.tabs[0].startupScript, "Builder Script") + } + + func testDeleteTemplateRemovesFile() throws { + let yaml = "tabs:\n - title: terminal\n" + try yaml.write( + to: tempDir.appendingPathComponent("Temp.yaml"), + atomically: true, + encoding: .utf8 + ) + try repo.deleteTemplate(named: "Temp") + XCTAssertFalse(FileManager.default.fileExists( + atPath: tempDir.appendingPathComponent("Temp.yaml").path + )) + } +} diff --git a/cmuxTests/WorkspaceGroupManagerTests.swift b/cmuxTests/WorkspaceGroupManagerTests.swift new file mode 100644 index 000000000000..b60421b7bf6f --- /dev/null +++ b/cmuxTests/WorkspaceGroupManagerTests.swift @@ -0,0 +1,312 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@MainActor +final class WorkspaceGroupManagerTests: XCTestCase { + var tabManager: TabManager! + var manager: WorkspaceGroupManager! + + override func setUp() { + super.setUp() + tabManager = TabManager() + manager = WorkspaceGroupManager(tabManager: tabManager) + } + + // MARK: - Standalone Registration + + func testRegisterWorkspaceAppearsInItems() { + let wsId = tabManager.tabs[0].id + manager.registerWorkspaceAsStandalone(wsId) + XCTAssertTrue(manager.items.contains(wsId)) + } + + func testDuplicateRegistrationIgnored() { + let wsId = tabManager.tabs[0].id + manager.registerWorkspaceAsStandalone(wsId) + manager.registerWorkspaceAsStandalone(wsId) + XCTAssertEqual(manager.items.filter { $0 == wsId }.count, 1) + } + + // MARK: - Child Management + + func testAddChildIdAppendsToParent() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + manager.addChildId(child.id, to: parent.id) + XCTAssertTrue(parent.childWorkspaceIds.contains(child.id)) + } + + func testRemoveChildIdFromParent() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds.append(child.id) + manager.removeChildId(child.id, from: parent.id) + XCTAssertFalse(parent.childWorkspaceIds.contains(child.id)) + } + + // MARK: - Remove Workspace + + func testRemoveWorkspaceClearsFromItems() { + let wsId = tabManager.tabs[0].id + manager.registerWorkspaceAsStandalone(wsId) + manager.removeWorkspace(wsId) + XCTAssertFalse(manager.items.contains(wsId)) + } + + func testRemoveWorkspaceClearsFromParentChildren() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds.append(child.id) + manager.removeWorkspace(child.id) + XCTAssertFalse(parent.childWorkspaceIds.contains(child.id)) + } + + // MARK: - Depth Queries + + func testDepthOfTopLevelIs1() { + let wsId = tabManager.tabs[0].id + manager.registerWorkspaceAsStandalone(wsId) + XCTAssertEqual(manager.depthOf(workspaceId: wsId), 1) + } + + func testDepthOfChildIs2() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds.append(child.id) + XCTAssertEqual(manager.depthOf(workspaceId: child.id), 2) + } + + func testDepthOfGrandchildIs3() { + let grandparent = tabManager.tabs[0] + let parent = tabManager.addWorkspace() + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(grandparent.id) + grandparent.childWorkspaceIds.append(parent.id) + parent.childWorkspaceIds.append(child.id) + XCTAssertEqual(manager.depthOf(workspaceId: child.id), 3) + } + + func testDepthOfUnknownIs0() { + XCTAssertEqual(manager.depthOf(workspaceId: UUID()), 0) + } + + // MARK: - Parent Workspace + + func testParentWorkspaceFindsCorrectParent() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + parent.childWorkspaceIds.append(child.id) + let found = manager.parentWorkspace(of: child.id) + XCTAssertEqual(found?.id, parent.id) + } + + func testParentWorkspaceReturnsNilForTopLevel() { + let wsId = tabManager.tabs[0].id + manager.registerWorkspaceAsStandalone(wsId) + XCTAssertNil(manager.parentWorkspace(of: wsId)) + } + + // MARK: - Visible Workspaces + + func testVisibleWorkspacesIncludesExpandedChildren() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds.append(child.id) + parent.isCollapsed = false + + let visible = manager.visibleWorkspaces() + XCTAssertTrue(visible.contains(where: { $0.id == parent.id })) + XCTAssertTrue(visible.contains(where: { $0.id == child.id })) + } + + func testVisibleWorkspacesSkipsCollapsedChildren() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds.append(child.id) + parent.isCollapsed = true + + let visible = manager.visibleWorkspaces() + XCTAssertTrue(visible.contains(where: { $0.id == parent.id })) + XCTAssertFalse(visible.contains(where: { $0.id == child.id })) + } + + // MARK: - Toggle Collapsed + + func testToggleCollapsedFlipsState() { + let ws = tabManager.tabs[0] + ws.childWorkspaceIds = [UUID()] + manager.registerWorkspaceAsStandalone(ws.id) + XCTAssertFalse(ws.isCollapsed) + manager.toggleCollapsed(ws.id) + XCTAssertTrue(ws.isCollapsed) + manager.toggleCollapsed(ws.id) + XCTAssertFalse(ws.isCollapsed) + } + + func testToggleCollapsedIgnoresWorkspaceWithoutChildren() { + let ws = tabManager.tabs[0] + manager.registerWorkspaceAsStandalone(ws.id) + manager.toggleCollapsed(ws.id) + XCTAssertFalse(ws.isCollapsed) + } + + // MARK: - Descendant IDs + + func testAllDescendantIdsCollectsDeep() { + let grandparent = tabManager.tabs[0] + let parent = tabManager.addWorkspace() + let child = tabManager.addWorkspace() + grandparent.childWorkspaceIds = [parent.id] + parent.childWorkspaceIds = [child.id] + + let descendants = manager.allDescendantIds(of: grandparent.id) + XCTAssertEqual(Set(descendants), [parent.id, child.id]) + } + + // MARK: - Indent (Tab) + + func testIndentTopLevelBecomesSiblingChild() { + let ws1 = tabManager.tabs[0] + let ws2 = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(ws1.id) + manager.registerWorkspaceAsStandalone(ws2.id) + + let result = manager.indentWorkspace(ws2.id) + XCTAssertTrue(result) + XCTAssertFalse(manager.items.contains(ws2.id)) + XCTAssertTrue(ws1.childWorkspaceIds.contains(ws2.id)) + } + + func testIndentFirstTopLevelDoesNothing() { + let ws1 = tabManager.tabs[0] + manager.registerWorkspaceAsStandalone(ws1.id) + + let result = manager.indentWorkspace(ws1.id) + XCTAssertFalse(result) + XCTAssertTrue(manager.items.contains(ws1.id)) + } + + func testIndentChildBecomesSiblingChild() { + let parent = tabManager.tabs[0] + let child1 = tabManager.addWorkspace() + let child2 = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds = [child1.id, child2.id] + + let result = manager.indentWorkspace(child2.id) + XCTAssertTrue(result) + XCTAssertTrue(child1.childWorkspaceIds.contains(child2.id)) + XCTAssertFalse(parent.childWorkspaceIds.contains(child2.id)) + } + + func testIndentBlockedByDepthConstraint() { + // ws1 -> ws2 -> ws3 (depth 3), try to indent ws2 under ws1 again would exceed + let ws1 = tabManager.tabs[0] + let ws2 = tabManager.addWorkspace() + let ws3 = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(ws1.id) + manager.registerWorkspaceAsStandalone(ws2.id) + ws2.childWorkspaceIds = [ws3.id] + + // ws2 is at depth 1, ws3 at depth 2 in ws2's subtree + // Indenting ws2 under ws1: ws2 becomes depth 2, ws3 becomes depth 3 — allowed + let result = manager.indentWorkspace(ws2.id) + XCTAssertTrue(result) + + // Now ws1 -> ws2 -> ws3 (ws3 is at depth 3) + // Create ws4 and try to indent under ws3 — would exceed depth 3 + let ws4 = tabManager.addWorkspace() + ws3.childWorkspaceIds = [ws4.id] + // ws4 is now at depth 4 which is the state but indenting ws3 further isn't possible + // since ws3 is a child of ws2 which is a child of ws1 + } + + func testIndentPreservesChildren() { + let ws1 = tabManager.tabs[0] + let ws2 = tabManager.addWorkspace() + let ws3 = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(ws1.id) + manager.registerWorkspaceAsStandalone(ws2.id) + ws2.childWorkspaceIds = [ws3.id] + + let result = manager.indentWorkspace(ws2.id) + XCTAssertTrue(result) + // ws2's children should remain + XCTAssertTrue(ws2.childWorkspaceIds.contains(ws3.id)) + // ws2 is now child of ws1 + XCTAssertTrue(ws1.childWorkspaceIds.contains(ws2.id)) + } + + // MARK: - Outdent (Shift-Tab) + + func testOutdentChildBecomesTopLevel() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds = [child.id] + + let result = manager.outdentWorkspace(child.id) + XCTAssertTrue(result) + XCTAssertFalse(parent.childWorkspaceIds.contains(child.id)) + // child should be in items right after parent + guard let parentIdx = manager.items.firstIndex(of: parent.id), + let childIdx = manager.items.firstIndex(of: child.id) else { + XCTFail("Expected both in items") + return + } + XCTAssertEqual(childIdx, parentIdx + 1) + } + + func testOutdentTopLevelDoesNothing() { + let ws = tabManager.tabs[0] + manager.registerWorkspaceAsStandalone(ws.id) + + let result = manager.outdentWorkspace(ws.id) + XCTAssertFalse(result) + } + + func testOutdentGrandchildBecomesChild() { + let gp = tabManager.tabs[0] + let parent = tabManager.addWorkspace() + let child = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(gp.id) + gp.childWorkspaceIds = [parent.id] + parent.childWorkspaceIds = [child.id] + + let result = manager.outdentWorkspace(child.id) + XCTAssertTrue(result) + XCTAssertFalse(parent.childWorkspaceIds.contains(child.id)) + // child should be in grandparent's children right after parent + guard let parentIdx = gp.childWorkspaceIds.firstIndex(of: parent.id), + let childIdx = gp.childWorkspaceIds.firstIndex(of: child.id) else { + XCTFail("Expected both in grandparent's children") + return + } + XCTAssertEqual(childIdx, parentIdx + 1) + } + + func testOutdentPreservesChildren() { + let parent = tabManager.tabs[0] + let child = tabManager.addWorkspace() + let grandchild = tabManager.addWorkspace() + manager.registerWorkspaceAsStandalone(parent.id) + parent.childWorkspaceIds = [child.id] + child.childWorkspaceIds = [grandchild.id] + + let result = manager.outdentWorkspace(child.id) + XCTAssertTrue(result) + // child keeps its children + XCTAssertTrue(child.childWorkspaceIds.contains(grandchild.id)) + } +} diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift new file mode 100644 index 000000000000..ba6b97f6e588 --- /dev/null +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -0,0 +1,42 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@MainActor +final class WorkspaceGroupTests: XCTestCase { + + // MARK: - Workspace Child Properties + + func testWorkspaceDefaultsToNoChildren() { + let ws = Workspace(title: "Test") + XCTAssertTrue(ws.childWorkspaceIds.isEmpty) + XCTAssertFalse(ws.hasChildren) + XCTAssertFalse(ws.isCollapsed) + } + + func testWorkspaceHasChildrenWhenChildIdsNonEmpty() { + let ws = Workspace(title: "Parent") + ws.childWorkspaceIds = [UUID()] + XCTAssertTrue(ws.hasChildren) + } + + func testWorkspaceIsCollapsedToggles() { + let ws = Workspace(title: "Parent") + ws.childWorkspaceIds = [UUID()] + XCTAssertFalse(ws.isCollapsed) + ws.isCollapsed = true + XCTAssertTrue(ws.isCollapsed) + } + + // MARK: - SidebarItem (typealias for UUID) + + func testSidebarItemIsUUID() { + let id = UUID() + let item: SidebarItem = id + XCTAssertEqual(item, id) + } +} From bb81d439c1ca7983a55544e8faa21d5ddb7a2100 Mon Sep 17 00:00:00 2001 From: roberf Date: Tue, 24 Mar 2026 23:56:12 -0400 Subject: [PATCH 2/8] fix(security): add path traversal guard to script and template repositories Names from the socket API and UI are now validated through NameSanitizer before being interpolated into filesystem paths. Rejects directory traversal vectors (/, \, :, ..) to prevent escaping ~/.config/cmux/. Also fixes pre-existing TemplateRepositoryTests to use current WorkspaceTemplate API. Co-Authored-By: Claude Opus 4.6 (1M context) --- GhosttyTabs.xcodeproj/project.pbxproj | 8 ++ Sources/NameSanitizer.swift | 39 ++++++ Sources/ScriptRepository.swift | 12 +- Sources/TemplateRepository.swift | 18 ++- cmuxTests/NameSanitizerTests.swift | 164 ++++++++++++++++++++++++ cmuxTests/TemplateRepositoryTests.swift | 48 ++++--- 6 files changed, 260 insertions(+), 29 deletions(-) create mode 100644 Sources/NameSanitizer.swift create mode 100644 cmuxTests/NameSanitizerTests.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 6edf7d6907a2..759b694de128 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -134,6 +134,8 @@ WG00000CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift */; }; WG00000DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift */; }; WG00000EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift */; }; + WG00000GA1B2C3D4E5F60001 /* NameSanitizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001GA1B2C3D4E5F60001 /* NameSanitizer.swift */; }; + WG00000HA1B2C3D4E5F60001 /* NameSanitizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001HA1B2C3D4E5F60001 /* NameSanitizerTests.swift */; }; WG00000FA1B2C3D4E5F60001 /* GroupHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001FA1B2C3D4E5F60001 /* GroupHeaderView.swift */; }; WG000010A1B2C3D4E5F60001 /* StartupScriptRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000020A1B2C3D4E5F60001 /* StartupScriptRunner.swift */; }; WG000021A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000022A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift */; }; @@ -275,6 +277,8 @@ WG00001CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxConfigParserTests.swift; sourceTree = ""; }; WG00001DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptRepositoryTests.swift; sourceTree = ""; }; WG00001EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateRepositoryTests.swift; sourceTree = ""; }; + WG00001GA1B2C3D4E5F60001 /* NameSanitizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NameSanitizer.swift; sourceTree = ""; }; + WG00001HA1B2C3D4E5F60001 /* NameSanitizerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NameSanitizerTests.swift; sourceTree = ""; }; WG00001FA1B2C3D4E5F60001 /* GroupHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupHeaderView.swift; sourceTree = ""; }; WG000020A1B2C3D4E5F60001 /* StartupScriptRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StartupScriptRunner.swift; sourceTree = ""; }; WG000022A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerGroupCommands.swift; sourceTree = ""; }; @@ -515,6 +519,7 @@ WG00001AA1B2C3D4E5F60001 /* ScriptRepository.swift */, WG00001BA1B2C3D4E5F60001 /* TemplateRepository.swift */, WG00001BA1B2C3D4E5F60002 /* TemplateYamlParser.swift */, + WG00001GA1B2C3D4E5F60001 /* NameSanitizer.swift */, WG00001FA1B2C3D4E5F60001 /* GroupHeaderView.swift */, WG000020A1B2C3D4E5F60001 /* StartupScriptRunner.swift */, WG000022A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift */, @@ -624,6 +629,7 @@ WG00001CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift */, WG00001DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift */, WG00001EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift */, + WG00001HA1B2C3D4E5F60001 /* NameSanitizerTests.swift */, ); path = cmuxTests; sourceTree = ""; @@ -836,6 +842,7 @@ WG00000AA1B2C3D4E5F60001 /* ScriptRepository.swift in Sources */, WG00000BA1B2C3D4E5F60001 /* TemplateRepository.swift in Sources */, WG00000BA1B2C3D4E5F60002 /* TemplateYamlParser.swift in Sources */, + WG00000GA1B2C3D4E5F60001 /* NameSanitizer.swift in Sources */, WG00000FA1B2C3D4E5F60001 /* GroupHeaderView.swift in Sources */, WG000010A1B2C3D4E5F60001 /* StartupScriptRunner.swift in Sources */, WG000021A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift in Sources */, @@ -913,6 +920,7 @@ WG00000CA1B2C3D4E5F60001 /* CmuxConfigParserTests.swift in Sources */, WG00000DA1B2C3D4E5F60001 /* ScriptRepositoryTests.swift in Sources */, WG00000EA1B2C3D4E5F60001 /* TemplateRepositoryTests.swift in Sources */, + WG00000HA1B2C3D4E5F60001 /* NameSanitizerTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Sources/NameSanitizer.swift b/Sources/NameSanitizer.swift new file mode 100644 index 000000000000..fafdb0eb9727 --- /dev/null +++ b/Sources/NameSanitizer.swift @@ -0,0 +1,39 @@ +import Foundation + +enum NameSanitizer { + enum Error: LocalizedError { + case empty + case containsPathSeparator + case containsParentTraversal + + var errorDescription: String? { + switch self { + case .empty: + return String(localized: "nameSanitizer.error.empty", defaultValue: "Name cannot be empty") + case .containsPathSeparator: + return String( + localized: "nameSanitizer.error.pathSeparator", + defaultValue: "Name cannot contain path separators" + ) + case .containsParentTraversal: + return String( + localized: "nameSanitizer.error.parentTraversal", + defaultValue: "Name cannot contain '..'" + ) + } + } + } + + /// Validates a name is safe for use as a filename component. + /// Rejects directory traversal vectors: empty, contains / or \, contains .., contains : + /// Does NOT enforce general filename aesthetics (Unicode, control chars, length). + static func sanitize(_ name: String) throws -> String { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { throw Error.empty } + guard !trimmed.contains("/"), !trimmed.contains("\\"), !trimmed.contains(":") else { + throw Error.containsPathSeparator + } + guard !trimmed.contains("..") else { throw Error.containsParentTraversal } + return trimmed + } +} diff --git a/Sources/ScriptRepository.swift b/Sources/ScriptRepository.swift index ce530dcbbbaa..7ae6d8dc6a6c 100644 --- a/Sources/ScriptRepository.swift +++ b/Sources/ScriptRepository.swift @@ -32,26 +32,30 @@ final class ScriptRepository: ScriptRepositoryProtocol { /// Returns the contents of a script, or nil if not found. func getScript(named name: String) -> String? { - let path = directory.appendingPathComponent("\(name).sh") + guard let safeName = try? NameSanitizer.sanitize(name) else { return nil } + let path = directory.appendingPathComponent("\(safeName).sh") return try? String(contentsOf: path, encoding: .utf8) } /// Saves or updates a script file. Creates the directory if needed. func saveScript(named name: String, content: String) throws { + let safeName = try NameSanitizer.sanitize(name) try ensureDirectoryExists() - let path = directory.appendingPathComponent("\(name).sh") + let path = directory.appendingPathComponent("\(safeName).sh") try content.write(to: path, atomically: true, encoding: .utf8) } /// Deletes a script file. func deleteScript(named name: String) throws { - let path = directory.appendingPathComponent("\(name).sh") + let safeName = try NameSanitizer.sanitize(name) + let path = directory.appendingPathComponent("\(safeName).sh") try FileManager.default.removeItem(at: path) } /// Returns true if a script with the given name exists. func hasScript(named name: String) -> Bool { - let path = directory.appendingPathComponent("\(name).sh") + guard let safeName = try? NameSanitizer.sanitize(name) else { return false } + let path = directory.appendingPathComponent("\(safeName).sh") return FileManager.default.fileExists(atPath: path.path) } diff --git a/Sources/TemplateRepository.swift b/Sources/TemplateRepository.swift index 3a8544452942..dbc7d94ed1fc 100644 --- a/Sources/TemplateRepository.swift +++ b/Sources/TemplateRepository.swift @@ -51,41 +51,47 @@ final class TemplateRepository { /// Parses and returns a template by name. func getTemplate(named name: String) throws -> WorkspaceTemplate { - let path = directory.appendingPathComponent("\(name).yaml") + let safeName = try NameSanitizer.sanitize(name) + let path = directory.appendingPathComponent("\(safeName).yaml") let content = try String(contentsOf: path, encoding: .utf8) return try TemplateYamlParser.parse(content) } /// Returns the raw YAML string for a template, or nil if not found. func rawYaml(named name: String) -> String? { - let path = directory.appendingPathComponent("\(name).yaml") + guard let safeName = try? NameSanitizer.sanitize(name) else { return nil } + let path = directory.appendingPathComponent("\(safeName).yaml") return try? String(contentsOf: path, encoding: .utf8) } /// Saves a template definition to a file. Creates the directory if needed. func saveTemplate(named name: String, template: WorkspaceTemplate) throws { + let safeName = try NameSanitizer.sanitize(name) try ensureDirectoryExists() let yaml = TemplateYamlParser.serialize(template) - let path = directory.appendingPathComponent("\(name).yaml") + let path = directory.appendingPathComponent("\(safeName).yaml") try yaml.write(to: path, atomically: true, encoding: .utf8) } /// Saves raw YAML content as a template file. Creates the directory if needed. func saveTemplate(named name: String, rawYaml: String) throws { + let safeName = try NameSanitizer.sanitize(name) try ensureDirectoryExists() - let path = directory.appendingPathComponent("\(name).yaml") + let path = directory.appendingPathComponent("\(safeName).yaml") try rawYaml.write(to: path, atomically: true, encoding: .utf8) } /// Deletes a template file. func deleteTemplate(named name: String) throws { - let path = directory.appendingPathComponent("\(name).yaml") + let safeName = try NameSanitizer.sanitize(name) + let path = directory.appendingPathComponent("\(safeName).yaml") try FileManager.default.removeItem(at: path) } /// Returns true if a template with the given name exists. func hasTemplate(named name: String) -> Bool { - let path = directory.appendingPathComponent("\(name).yaml") + guard let safeName = try? NameSanitizer.sanitize(name) else { return false } + let path = directory.appendingPathComponent("\(safeName).yaml") return FileManager.default.fileExists(atPath: path.path) } diff --git a/cmuxTests/NameSanitizerTests.swift b/cmuxTests/NameSanitizerTests.swift new file mode 100644 index 000000000000..b7a0252a2df1 --- /dev/null +++ b/cmuxTests/NameSanitizerTests.swift @@ -0,0 +1,164 @@ +import XCTest + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +final class NameSanitizerTests: XCTestCase { + + // MARK: - Valid Names + + func testValidNamePassesThrough() throws { + XCTAssertEqual(try NameSanitizer.sanitize("Builder"), "Builder") + } + + func testValidNameWithHyphen() throws { + XCTAssertEqual(try NameSanitizer.sanitize("my-script"), "my-script") + } + + func testValidNameWithSpace() throws { + XCTAssertEqual(try NameSanitizer.sanitize("AI Dev"), "AI Dev") + } + + func testValidNameWithUnderscore() throws { + XCTAssertEqual(try NameSanitizer.sanitize("script_v2"), "script_v2") + } + + func testValidNameWithDot() throws { + XCTAssertEqual(try NameSanitizer.sanitize("file.backup"), "file.backup") + } + + func testTrimsWhitespace() throws { + XCTAssertEqual(try NameSanitizer.sanitize(" Builder "), "Builder") + } + + // MARK: - Rejections + + func testRejectsEmptyString() { + XCTAssertThrowsError(try NameSanitizer.sanitize("")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsWhitespaceOnly() { + XCTAssertThrowsError(try NameSanitizer.sanitize(" ")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsForwardSlash() { + XCTAssertThrowsError(try NameSanitizer.sanitize("foo/bar")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsBackslash() { + XCTAssertThrowsError(try NameSanitizer.sanitize("foo\\bar")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsColon() { + XCTAssertThrowsError(try NameSanitizer.sanitize("foo:bar")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsDoubleDot() { + XCTAssertThrowsError(try NameSanitizer.sanitize("..")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsParentTraversal() { + XCTAssertThrowsError(try NameSanitizer.sanitize("../../etc/passwd")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + func testRejectsEmbeddedDoubleDot() { + XCTAssertThrowsError(try NameSanitizer.sanitize("foo..bar")) { error in + XCTAssertTrue(error is NameSanitizer.Error) + } + } + + // MARK: - ScriptRepository Integration + + func testScriptRepositorySaveRejectsTraversal() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = ScriptRepository(directory: tempDir) + XCTAssertThrowsError(try repo.saveScript(named: "../escape", content: "echo pwned")) + } + + func testScriptRepositoryDeleteRejectsTraversal() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = ScriptRepository(directory: tempDir) + XCTAssertThrowsError(try repo.deleteScript(named: "../../etc")) + } + + func testScriptRepositoryGetReturnsNilForTraversal() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = ScriptRepository(directory: tempDir) + XCTAssertNil(repo.getScript(named: "../escape")) + } + + // MARK: - TemplateRepository Integration + + func testTemplateRepositorySaveRejectsTraversal() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = TemplateRepository(directory: tempDir) + XCTAssertThrowsError(try repo.saveTemplate(named: "../escape", rawYaml: "root:\n title: X")) + } + + func testTemplateRepositoryDeleteRejectsSlash() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = TemplateRepository(directory: tempDir) + XCTAssertThrowsError(try repo.deleteTemplate(named: "foo/bar")) + } + + func testTemplateRepositoryHasReturnsFalseForTraversal() { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try! FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = TemplateRepository(directory: tempDir) + XCTAssertFalse(repo.hasTemplate(named: "../escape")) + } + + // MARK: - Round-trip Sanity Check + + func testScriptRepositoryValidRoundTrip() throws { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-sanitizer-test-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let repo = ScriptRepository(directory: tempDir) + let content = "#!/bin/bash\necho hello" + try repo.saveScript(named: "my-script", content: content) + XCTAssertEqual(repo.getScript(named: "my-script"), content) + } +} diff --git a/cmuxTests/TemplateRepositoryTests.swift b/cmuxTests/TemplateRepositoryTests.swift index acd314a0376f..929c0359f6bf 100644 --- a/cmuxTests/TemplateRepositoryTests.swift +++ b/cmuxTests/TemplateRepositoryTests.swift @@ -24,7 +24,7 @@ final class TemplateRepositoryTests: XCTestCase { } func testListTemplates() throws { - let yaml = "tabs:\n - title: terminal\n" + let yaml = "root:\n title: Terminal\n" try yaml.write( to: tempDir.appendingPathComponent("Basic.yaml"), atomically: true, @@ -50,12 +50,15 @@ final class TemplateRepositoryTests: XCTestCase { XCTAssertEqual(missingRepo.listTemplates(), []) } - func testGetTemplateReturnsTabDefinitions() throws { + func testGetTemplateReturnsRootNode() throws { let yaml = """ - tabs: - - title: claude - startupScript: Standard Claude - - title: terminal + root: + title: Terminal + children: + - title: claude + color: "#00CC00" + command: claude + - title: terminal """ try yaml.write( to: tempDir.appendingPathComponent("AI Dev.yaml"), @@ -63,31 +66,38 @@ final class TemplateRepositoryTests: XCTestCase { encoding: .utf8 ) let template = try repo.getTemplate(named: "AI Dev") - XCTAssertEqual(template.tabs.count, 2) - XCTAssertEqual(template.tabs[0].title, "claude") - XCTAssertEqual(template.tabs[0].startupScript, "Standard Claude") - XCTAssertEqual(template.tabs[1].title, "terminal") - XCTAssertNil(template.tabs[1].startupScript) + XCTAssertEqual(template.root.title, "Terminal") + XCTAssertEqual(template.root.children.count, 2) + XCTAssertEqual(template.root.children[0].title, "claude") + XCTAssertEqual(template.root.children[0].color, "#00CC00") + XCTAssertEqual(template.root.children[0].command, "claude") + XCTAssertEqual(template.root.children[1].title, "terminal") + XCTAssertNil(template.root.children[1].command) } func testSaveTemplateWritesYaml() throws { - let template = WorkspaceTemplate(tabs: [ - TemplateTabDefinition(title: "builder", startupScript: "Builder Script"), - TemplateTabDefinition(title: "terminal", startupScript: nil) - ]) + let template = WorkspaceTemplate(root: TemplateNode( + title: "Terminal", + color: nil, + command: nil, + children: [ + TemplateNode(title: "builder", color: nil, command: "claude", children: []), + TemplateNode(title: "terminal", color: nil, command: nil, children: []) + ] + )) try repo.saveTemplate(named: "Custom", template: template) let path = tempDir.appendingPathComponent("Custom.yaml") XCTAssertTrue(FileManager.default.fileExists(atPath: path.path)) // Verify it can be read back let loaded = try repo.getTemplate(named: "Custom") - XCTAssertEqual(loaded.tabs.count, 2) - XCTAssertEqual(loaded.tabs[0].title, "builder") - XCTAssertEqual(loaded.tabs[0].startupScript, "Builder Script") + XCTAssertEqual(loaded.root.children.count, 2) + XCTAssertEqual(loaded.root.children[0].title, "builder") + XCTAssertEqual(loaded.root.children[0].command, "claude") } func testDeleteTemplateRemovesFile() throws { - let yaml = "tabs:\n - title: terminal\n" + let yaml = "root:\n title: Terminal\n" try yaml.write( to: tempDir.appendingPathComponent("Temp.yaml"), atomically: true, From 76093f09049fa3ad58116814231805555c214c15 Mon Sep 17 00:00:00 2001 From: roberf Date: Tue, 24 Mar 2026 23:56:21 -0400 Subject: [PATCH 3/8] fix(security): reject socket connections when pid unavailable in cmuxOnly mode Previously fell back to same-UID check when LOCAL_PEERPID returned nil, which is weaker than the descendant-process guarantee cmuxOnly promises. Now rejects outright when ancestry cannot be verified. Co-Authored-By: Claude Opus 4.6 (1M context) --- Sources/TerminalController.swift | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 33ebac41355d..cc538fa217a9 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -1586,19 +1586,13 @@ class TerminalController { return } } - // If pid is nil, LOCAL_PEERPID failed (peer disconnected before we - // could read it — common with ncat --send-only). We still verify the - // peer runs as the same user via LOCAL_PEERCRED. This is the same - // security boundary as the socket file permissions (0600), so it does - // not widen the attack surface. We also require that the peer actually - // sent data (checked in the read loop below) — a connect-only probe - // with no data is harmless. + // If pid is nil, LOCAL_PEERPID failed. In cmuxOnly mode the security + // guarantee is process ancestry (descendant of cmux), not merely same-UID. + // Without a pid we cannot verify ancestry, so reject the connection. if pid == nil { - guard peerHasSameUID(socket) else { - let msg = "ERROR: Unable to verify client process\n" - msg.withCString { ptr in _ = write(socket, ptr, strlen(ptr)) } - return - } + let msg = "ERROR: Access denied — unable to verify client ancestry (cmuxOnly mode requires LOCAL_PEERPID)\n" + msg.withCString { ptr in _ = write(socket, ptr, strlen(ptr)) } + return } } From 5527c3674cb7bfb26a00cff1104f9c8faddbf72e Mon Sep 17 00:00:00 2001 From: roberf Date: Tue, 24 Mar 2026 23:56:29 -0400 Subject: [PATCH 4/8] fix: surface file operation errors in script and template manager UIs Replace try? with do/catch in save, add, duplicate, and delete operations so users see error messages instead of silent failures. Adds errorMessage property and red error banner to ScriptManagerWindow matching the existing TemplateManagerWindow pattern. Co-Authored-By: Claude Opus 4.6 (1M context) --- Sources/ScriptManagerViewModel.swift | 51 ++++++++++++++++++-------- Sources/ScriptManagerWindow.swift | 14 +++++++ Sources/TemplateManagerViewModel.swift | 40 +++++++++++++------- 3 files changed, 77 insertions(+), 28 deletions(-) diff --git a/Sources/ScriptManagerViewModel.swift b/Sources/ScriptManagerViewModel.swift index bb1410d49612..99f573d9578c 100644 --- a/Sources/ScriptManagerViewModel.swift +++ b/Sources/ScriptManagerViewModel.swift @@ -7,6 +7,7 @@ final class ScriptManagerViewModel: ObservableObject { @Published var scriptNames: [String] = [] @Published var selectedName: String? @Published var editorText: String = "" + @Published var errorMessage: String? @Published private(set) var isDirty: Bool = false private var loadedText: String = "" @@ -33,9 +34,14 @@ final class ScriptManagerViewModel: ObservableObject { func save() { guard let name = selectedName else { return } - try? repo.saveScript(named: name, content: editorText) - loadedText = editorText - isDirty = false + errorMessage = nil + do { + try repo.saveScript(named: name, content: editorText) + loadedText = editorText + isDirty = false + } catch { + errorMessage = error.localizedDescription + } } func revert() { @@ -44,6 +50,7 @@ final class ScriptManagerViewModel: ObservableObject { } func addScript() { + errorMessage = nil var baseName = String( localized: "scriptManager.newScriptName", defaultValue: "New Script" @@ -57,12 +64,17 @@ final class ScriptManagerViewModel: ObservableObject { ) } let defaultContent = "#!/bin/bash\n# New script\n" - try? repo.saveScript(named: baseName, content: defaultContent) - reload() - selectScript(named: baseName) + do { + try repo.saveScript(named: baseName, content: defaultContent) + reload() + selectScript(named: baseName) + } catch { + errorMessage = error.localizedDescription + } } func duplicateSelected() { + errorMessage = nil guard let name = selectedName, let content = repo.getScript(named: name) else { return } var copyName = "\(name) Copy" @@ -71,19 +83,28 @@ final class ScriptManagerViewModel: ObservableObject { counter += 1 copyName = "\(name) Copy \(counter)" } - try? repo.saveScript(named: copyName, content: content) - reload() - selectScript(named: copyName) + do { + try repo.saveScript(named: copyName, content: content) + reload() + selectScript(named: copyName) + } catch { + errorMessage = error.localizedDescription + } } func deleteSelected() { + errorMessage = nil guard let name = selectedName else { return } - try? repo.deleteScript(named: name) - selectedName = nil - editorText = "" - loadedText = "" - isDirty = false - reload() + do { + try repo.deleteScript(named: name) + selectedName = nil + editorText = "" + loadedText = "" + isDirty = false + reload() + } catch { + errorMessage = error.localizedDescription + } } func textDidChange(_ newText: String) { diff --git a/Sources/ScriptManagerWindow.swift b/Sources/ScriptManagerWindow.swift index b24b8818d4da..b8ed0d70fa4c 100644 --- a/Sources/ScriptManagerWindow.swift +++ b/Sources/ScriptManagerWindow.swift @@ -148,6 +148,20 @@ struct ScriptManagerView: View { onChange: viewModel.textDidChange ) + if let error = viewModel.errorMessage { + HStack { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundColor(.red) + Text(error) + .foregroundColor(.red) + .font(.caption) + .lineLimit(2) + Spacer() + } + .padding(.horizontal, 8) + .padding(.vertical, 4) + } + HStack { Spacer() Button(String(localized: "common.revert", defaultValue: "Revert")) { diff --git a/Sources/TemplateManagerViewModel.swift b/Sources/TemplateManagerViewModel.swift index 833c8ebb64ef..855c0b04f49f 100644 --- a/Sources/TemplateManagerViewModel.swift +++ b/Sources/TemplateManagerViewModel.swift @@ -58,6 +58,7 @@ final class TemplateManagerViewModel: ObservableObject { } func addTemplate() { + errorMessage = nil var baseName = String( localized: "templateManager.newTemplateName", defaultValue: "New Template" @@ -77,12 +78,17 @@ final class TemplateManagerViewModel: ObservableObject { - title: Shell command: "" """ - try? repo.saveTemplate(named: baseName, rawYaml: defaultContent) - reload() - selectTemplate(named: baseName) + do { + try repo.saveTemplate(named: baseName, rawYaml: defaultContent) + reload() + selectTemplate(named: baseName) + } catch { + errorMessage = error.localizedDescription + } } func duplicateSelected() { + errorMessage = nil guard let name = selectedName, let yaml = repo.rawYaml(named: name) else { return } var copyName = "\(name) Copy" @@ -91,20 +97,28 @@ final class TemplateManagerViewModel: ObservableObject { counter += 1 copyName = "\(name) Copy \(counter)" } - try? repo.saveTemplate(named: copyName, rawYaml: yaml) - reload() - selectTemplate(named: copyName) + do { + try repo.saveTemplate(named: copyName, rawYaml: yaml) + reload() + selectTemplate(named: copyName) + } catch { + errorMessage = error.localizedDescription + } } func deleteSelected() { - guard let name = selectedName else { return } - try? repo.deleteTemplate(named: name) - selectedName = nil - editorText = "" - loadedText = "" - isDirty = false errorMessage = nil - reload() + guard let name = selectedName else { return } + do { + try repo.deleteTemplate(named: name) + selectedName = nil + editorText = "" + loadedText = "" + isDirty = false + reload() + } catch { + errorMessage = error.localizedDescription + } } func textDidChange(_ newText: String) { From 4448ba5d8156abdf936a211fe131e813431cdd7c Mon Sep 17 00:00:00 2001 From: roberf Date: Wed, 25 Mar 2026 01:13:12 -0400 Subject: [PATCH 5/8] fix: reduce Scripts menu flicker and improve UI polish - Add read-only preferredTabManager to AppDelegate (ported from upstream 6bd98948) to avoid mutation-triggered re-evaluation in menu lookups - Decouple ScriptsMenuContent from activeTabManager parameter; resolve live state only in action closures - Add Equatable conformance + .equatable() to minimize body re-evaluation - Restore .disabled(!isAtPrompt) on Run Script items for proper greyed-out state - Change duplicate icon from doc.on.doc to plus.square.on.square in both Script Manager and Template Manager windows Note: cosmetic highlight flicker in the Run Script submenu persists during active terminal output due to a SwiftUI CommandMenu framework limitation (Scene-level invalidation rebuilds the NSMenu bridge regardless of content stability). Clears up once terminal output settles. Co-Authored-By: Claude Opus 4.6 (1M context) --- Sources/AppDelegate.swift | 20 +++++++++++++ Sources/ScriptManagerWindow.swift | 2 +- Sources/ScriptsMenu.swift | 44 +++++++++++++++++++---------- Sources/TemplateManagerWindow.swift | 2 +- Sources/cmuxApp.swift | 9 ++++-- 5 files changed, 58 insertions(+), 19 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 80d2e59141a6..2d206afd0078 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -5194,6 +5194,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return nil } + /// Resolve the best current `TabManager` for menu/UI reads without mutating + /// the app-wide active window pointers. Use this in SwiftUI computed properties + /// and CommandMenu closures to avoid triggering @Published re-evaluation loops. + func preferredTabManager(preferredWindow: NSWindow? = nil) -> TabManager? { + if let preferredWindow, + let context = contextForMainWindow(preferredWindow) { + return context.tabManager + } + if let context = contextForMainWindow(NSApp.keyWindow) { + return context.tabManager + } + if let context = contextForMainWindow(NSApp.mainWindow) { + return context.tabManager + } + if let activeManager = tabManager { + return activeManager + } + return mainWindowContexts.values.first?.tabManager + } + /// Re-sync app-level active window pointers from the currently focused main terminal window. /// This keeps menu/shortcut actions window-scoped even if the cached `tabManager` drifts. @discardableResult diff --git a/Sources/ScriptManagerWindow.swift b/Sources/ScriptManagerWindow.swift index b8ed0d70fa4c..de00bf454717 100644 --- a/Sources/ScriptManagerWindow.swift +++ b/Sources/ScriptManagerWindow.swift @@ -121,7 +121,7 @@ struct ScriptManagerView: View { .buttonStyle(.borderless) Button(action: viewModel.duplicateSelected) { - Image(systemName: "doc.on.doc") + Image(systemName: "plus.square.on.square") } .buttonStyle(.borderless) .disabled(viewModel.selectedName == nil) diff --git a/Sources/ScriptsMenu.swift b/Sources/ScriptsMenu.swift index d070bc6d3d6d..f2819cb63254 100644 --- a/Sources/ScriptsMenu.swift +++ b/Sources/ScriptsMenu.swift @@ -1,9 +1,16 @@ import SwiftUI /// Scripts menu added to the app's main menu bar via CommandMenu. -/// Provides access to run scripts, open templates, and manage both. -struct ScriptsMenuContent: View { - let activeTabManager: TabManager +/// Uses Equatable to minimize body re-evaluation. Resolves live state +/// (active tab manager, prompt state) only inside action closures, +/// not during menu rendering. +struct ScriptsMenuContent: View, Equatable { + let scriptNames: [String] + let templateNames: [String] + + static func == (lhs: ScriptsMenuContent, rhs: ScriptsMenuContent) -> Bool { + lhs.scriptNames == rhs.scriptNames && lhs.templateNames == rhs.templateNames + } var body: some View { runScriptSubmenu @@ -21,16 +28,15 @@ struct ScriptsMenuContent: View { @ViewBuilder private var runScriptSubmenu: some View { - let scripts = ScriptRepository.shared.listScripts() - let isAtPrompt = activeTabManager.selectedTab?.isFocusedPanelAtPrompt ?? false + let isAtPrompt = Self.resolveActiveTabManager()?.selectedTab?.isFocusedPanelAtPrompt ?? false Menu(String(localized: "menu.scripts.runScript", defaultValue: "Run Script")) { - ForEach(scripts, id: \.self) { scriptName in + ForEach(scriptNames, id: \.self) { scriptName in Button(scriptName) { runScript(named: scriptName) } .disabled(!isAtPrompt) } - if scripts.isEmpty { + if scriptNames.isEmpty { Text(String(localized: "menu.scripts.noScripts", defaultValue: "No Scripts")) } } @@ -38,7 +44,8 @@ struct ScriptsMenuContent: View { private func runScript(named scriptName: String) { guard let scriptContent = ScriptRepository.shared.getScript(named: scriptName), - let terminalPanel = activeTabManager.selectedTab?.focusedTerminalPanel else { return } + let tabManager = Self.resolveActiveTabManager(), + let terminalPanel = tabManager.selectedTab?.focusedTerminalPanel else { return } let lines = StartupScriptRunner.prepareScriptLines(scriptContent) guard !lines.isEmpty else { return } let text = lines.joined(separator: "\n") + "\n" @@ -49,21 +56,21 @@ struct ScriptsMenuContent: View { @ViewBuilder private var openTemplateSubmenu: some View { - let templates = TemplateRepository.shared.listTemplates() Menu(String(localized: "menu.scripts.openTemplate", defaultValue: "Open Template")) { - ForEach(templates, id: \.self) { templateName in + ForEach(templateNames, id: \.self) { templateName in Button(templateName) { openTemplate(named: templateName) } } - if templates.isEmpty { + if templateNames.isEmpty { Text(String(localized: "menu.scripts.noTemplates", defaultValue: "No Templates")) } } } private func openTemplate(named templateName: String) { - guard let template = try? TemplateRepository.shared.getTemplate(named: templateName) else { return } + guard let template = try? TemplateRepository.shared.getTemplate(named: templateName), + let tabManager = Self.resolveActiveTabManager() else { return } let panel = NSOpenPanel() panel.canChooseFiles = false @@ -75,12 +82,19 @@ struct ScriptsMenuContent: View { ) panel.prompt = String(localized: "menu.scripts.openTemplate.panelPrompt", defaultValue: "Open") - // Default to the focused tab's current directory if available - if let currentDir = activeTabManager.selectedTab?.currentDirectory { + if let currentDir = tabManager.selectedTab?.currentDirectory { panel.directoryURL = URL(fileURLWithPath: currentDir) } guard panel.runModal() == .OK, let url = panel.url else { return } - activeTabManager.openTemplate(template, directory: url.path) + tabManager.openTemplate(template, directory: url.path) + } + + // MARK: - Private + + private static func resolveActiveTabManager() -> TabManager? { + AppDelegate.shared?.preferredTabManager( + preferredWindow: NSApp.keyWindow ?? NSApp.mainWindow + ) } } diff --git a/Sources/TemplateManagerWindow.swift b/Sources/TemplateManagerWindow.swift index 4ef921bddb61..edd90bca02f9 100644 --- a/Sources/TemplateManagerWindow.swift +++ b/Sources/TemplateManagerWindow.swift @@ -124,7 +124,7 @@ struct TemplateManagerView: View { .buttonStyle(.borderless) Button(action: viewModel.duplicateSelected) { - Image(systemName: "doc.on.doc") + Image(systemName: "plus.square.on.square") } .buttonStyle(.borderless) .disabled(viewModel.selectedName == nil) diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 2e7249364690..3141c6401831 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -213,6 +213,7 @@ struct cmuxApp: App { // UI tests depend on AppDelegate wiring happening even if SwiftUI view appearance // callbacks (e.g. `.onAppear`) are delayed or skipped. appDelegate.configure(tabManager: tabManager, notificationStore: notificationStore, sidebarState: sidebarState) + } private static func terminateForMissingLaunchTag() -> Never { @@ -445,7 +446,11 @@ struct cmuxApp: App { } CommandMenu(String(localized: "menu.scripts.title", defaultValue: "Scripts")) { - ScriptsMenuContent(activeTabManager: activeTabManager) + ScriptsMenuContent( + scriptNames: ScriptRepository.shared.listScripts(), + templateNames: TemplateRepository.shared.listTemplates() + ) + .equatable() } #if DEBUG @@ -976,7 +981,7 @@ struct cmuxApp: App { } private var activeTabManager: TabManager { - AppDelegate.shared?.synchronizeActiveMainWindowContext( + appDelegate.preferredTabManager( preferredWindow: NSApp.keyWindow ?? NSApp.mainWindow ) ?? tabManager } From d84739d85a7d7d78cfb05054dbe3b14aa3ebded9 Mon Sep 17 00:00:00 2001 From: roberf Date: Wed, 25 Mar 2026 11:43:30 -0400 Subject: [PATCH 6/8] feat: add hierarchy-aware drag-and-drop reordering and visual group spacing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add moveWorkspaceByIndicator to TabManager for cross-level drag-and-drop: top-level reorder, child reorder, promote (child→tier 1), demote (tier 1→child), with depth constraint checks and cycle prevention - Update SidebarTabDropDelegate to use visible workspace list instead of flat tabs array, and call moveWorkspaceByIndicator with indicator info - Add SidebarGroupSpacerDropDelegate for two-zone drop target in the 10px spacer between tier 1 groups (upper half = last child, lower half = tier 1) - Add showsBottomDropIndicator and bottom overlay on TabItemView for correct indicator positioning at group boundaries - Fix showsCenteredTopDropIndicator to suppress top line at group boundaries - Override indicator in updateDropIndicator when planner returns no-op at group boundaries (bottom-of-self at boundary is meaningful) - Add 10px spacing above each tier 1 workspace for visual group separation - Fix shouldShowTopDropIndicator in SidebarEmptyArea to use visible workspaces Co-Authored-By: Claude Opus 4.6 (1M context) --- Sources/ContentView.swift | 251 ++++++++++++++++++++++------ Sources/TabManager.swift | 80 +++++++++ Sources/WorkspaceGroupManager.swift | 2 +- 3 files changed, 278 insertions(+), 55 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 75382fb696d2..d93f130af849 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -8209,8 +8209,15 @@ struct VerticalTabsSidebar: View { LazyVStack(spacing: tabRowSpacing) { let visibleWorkspaces = tabManager.groupManager.visibleWorkspaces() let visibleCount = visibleWorkspaces.count - ForEach(tabManager.items, id: \.self) { wsId in + ForEach(Array(tabManager.items.enumerated()), id: \.element) { itemIndex, wsId in if let tab = tabManager.workspace(for: wsId) { + // 10px spacer between tier 1 groups, with drop delegate + groupSpacerView( + itemIndex: itemIndex, + currentTier1Id: wsId, + visibleWorkspaces: visibleWorkspaces + ) + let visibleIndex = visibleWorkspaces.firstIndex(where: { $0.id == wsId }) ?? 0 sidebarTabItemView( tab: tab, @@ -8397,6 +8404,43 @@ struct VerticalTabsSidebar: View { .equatable() } + /// 10px spacer between tier 1 groups with two-zone drop target. + @ViewBuilder + private func groupSpacerView( + itemIndex: Int, + currentTier1Id: UUID, + visibleWorkspaces: [Workspace] + ) -> some View { + let prevLastChildId: UUID? = { + guard itemIndex > 0 else { return nil } + let prevWsId = tabManager.items[itemIndex - 1] + guard let prevTab = tabManager.workspace(for: prevWsId) else { return prevWsId } + return lastVisibleDescendantId(of: prevTab) + }() + Color.clear + .frame(height: 10) + .contentShape(Rectangle()) + .onDrop(of: SidebarTabDragPayload.dropContentTypes, delegate: SidebarGroupSpacerDropDelegate( + previousGroupLastChildId: prevLastChildId, + nextTopLevelTabId: currentTier1Id, + tabManager: tabManager, + draggedTabId: $draggedTabId, + selectedTabIds: $selectedTabIds, + lastSidebarSelectionIndex: $lastSidebarSelectionIndex, + dragAutoScrollController: dragAutoScrollController, + dropIndicator: $dropIndicator + )) + } + + private func lastVisibleDescendantId(of workspace: Workspace) -> UUID { + guard workspace.hasChildren && !workspace.isCollapsed else { return workspace.id } + guard let lastChildId = workspace.childWorkspaceIds.last, + let lastChild = tabManager.workspace(for: lastChildId) else { + return workspace.id + } + return lastVisibleDescendantId(of: lastChild) + } + /// Renders child workspaces (max 3 levels deep, no recursion needed). @ViewBuilder private func sidebarChildWorkspaces( @@ -10631,7 +10675,8 @@ private struct SidebarEmptyArea: View { if indicator.tabId == nil { return true } - guard indicator.edge == .bottom, let lastTabId = tabManager.tabs.last?.id else { return false } + let visible = tabManager.groupManager.visibleWorkspaces() + guard indicator.edge == .bottom, let lastTabId = visible.last?.id else { return false } return indicator.tabId == lastTabId } } @@ -11345,6 +11390,15 @@ private struct TabItemView: View, Equatable { .offset(y: index == 0 ? 0 : -(rowSpacing / 2)) } } + .overlay(alignment: .bottom) { + if showsBottomDropIndicator { + Rectangle() + .fill(cmuxAccentColor()) + .frame(height: 2) + .padding(.horizontal, 8) + .offset(y: rowSpacing / 2) + } + } .onDrag { #if DEBUG dlog("sidebar.onDrag tab=\(tab.id.uuidString.prefix(5))") @@ -11708,13 +11762,32 @@ private struct TabItemView: View, Equatable { return true } + let visible = tabManager.groupManager.visibleWorkspaces() guard indicator.edge == .bottom, - let currentIndex = tabManager.tabs.firstIndex(where: { $0.id == tab.id }), + let currentIndex = visible.firstIndex(where: { $0.id == tab.id }), currentIndex > 0 else { return false } - return tabManager.tabs[currentIndex - 1].id == indicator.tabId + let prevId = visible[currentIndex - 1].id + guard prevId == indicator.tabId else { return false } + // Don't show top indicator here if the previous item is across a group boundary + let myParent = tabManager.groupManager.parentWorkspace(of: tab.id) + let prevParent = tabManager.groupManager.parentWorkspace(of: prevId) + return myParent?.id == prevParent?.id + } + + private var showsBottomDropIndicator: Bool { + guard draggedTabId != nil, let indicator = dropIndicator else { return false } + guard indicator.tabId == tab.id, indicator.edge == .bottom else { return false } + let visible = tabManager.groupManager.visibleWorkspaces() + guard let myIndex = visible.firstIndex(where: { $0.id == tab.id }) else { return false } + let nextIndex = myIndex + 1 + if nextIndex >= visible.count { return true } + let nextId = visible[nextIndex].id + let myParent = tabManager.groupManager.parentWorkspace(of: tab.id) + let nextParent = tabManager.groupManager.parentWorkspace(of: nextId) + return myParent?.id != nextParent?.id } /// Whether this workspace can be nested under the sibling above it. @@ -13063,67 +13136,75 @@ private struct SidebarTabDropDelegate: DropDelegate { dropIndicator = nil dragAutoScrollController.stop() } - #if DEBUG - dlog("sidebar.drop target=\(targetTabId?.uuidString.prefix(5) ?? "end")") - #endif - guard let draggedTabId else { -#if DEBUG - dlog("sidebar.drop.abort reason=missingDraggedTab") -#endif - return false - } - guard let fromIndex = tabManager.tabs.firstIndex(where: { $0.id == draggedTabId }) else { -#if DEBUG - dlog("sidebar.drop.abort reason=draggedTabMissing tab=\(draggedTabId.uuidString.prefix(5))") -#endif - return false - } - let tabIds = tabManager.tabs.map(\.id) - guard let targetIndex = SidebarDropPlanner.targetIndex( - draggedTabId: draggedTabId, - targetTabId: targetTabId, - indicator: dropIndicator, - tabIds: tabIds, - pinnedTabIds: Set(tabManager.tabs.filter(\.isPinned).map(\.id)) - ) else { -#if DEBUG - dlog( - "sidebar.drop.abort reason=noTargetIndex tab=\(draggedTabId.uuidString.prefix(5)) " + - "target=\(targetTabId?.uuidString.prefix(5) ?? "end") indicator=\(debugIndicator(dropIndicator))" - ) -#endif - return false - } + guard let draggedTabId else { return false } - guard fromIndex != targetIndex else { -#if DEBUG - dlog("sidebar.drop.noop from=\(fromIndex) to=\(targetIndex)") -#endif - syncSidebarSelection() - return true + // Use indicator directly — it knows the target tab and edge + let indicatorTabId: UUID? + let indicatorEdge: SidebarDropEdge + if let indicator = dropIndicator { + indicatorTabId = indicator.tabId + indicatorEdge = indicator.edge + } else if let targetTabId { + indicatorTabId = targetTabId + indicatorEdge = .top + } else { + indicatorTabId = nil + indicatorEdge = .bottom } #if DEBUG - dlog("sidebar.drop.commit tab=\(draggedTabId.uuidString.prefix(5)) from=\(fromIndex) to=\(targetIndex)") + let indicatorDesc = indicatorTabId.map { String($0.uuidString.prefix(5)) } ?? "end" + dlog("sidebar.drop.commit tab=\(draggedTabId.uuidString.prefix(5)) indicatorTab=\(indicatorDesc) edge=\(indicatorEdge == .top ? "top" : "bottom")") #endif - _ = tabManager.reorderWorkspace(tabId: draggedTabId, toIndex: targetIndex) - if let selectedId = tabManager.selectedTabId { - selectedTabIds = [selectedId] - syncSidebarSelection(preferredSelectedTabId: selectedId) - } else { - selectedTabIds = [] - syncSidebarSelection() + let moved = tabManager.moveWorkspaceByIndicator( + tabId: draggedTabId, + targetTabId: indicatorTabId, + edge: indicatorEdge + ) + if moved { + if let selectedId = tabManager.selectedTabId { + selectedTabIds = [selectedId] + syncSidebarSelection(preferredSelectedTabId: selectedId) + } else { + selectedTabIds = [] + syncSidebarSelection() + } } - return true + return moved } private func updateDropIndicator(for info: DropInfo) { - let tabIds = tabManager.tabs.map(\.id) - let pinnedTabIds = Set(tabManager.tabs.filter(\.isPinned).map(\.id)) + let visible = tabManager.groupManager.visibleWorkspaces() + let visibleIds = visible.map(\.id) + let pinnedTabIds = Set(visible.filter(\.isPinned).map(\.id)) + + // Special case: pointer is on the bottom half of a tab at a group boundary. + // The planner treats "insert after self" as a no-op and returns nil, but at + // group boundaries this position is meaningful (last-child vs promote-to-tier-1). + if let targetTabId, + let targetHeight = targetRowHeight, targetHeight > 0, + info.location.y >= targetHeight / 2 { + let myParent = tabManager.groupManager.parentWorkspace(of: targetTabId) + if let myIdx = visibleIds.firstIndex(of: targetTabId) { + let nextIdx = myIdx + 1 + let isGroupBoundary: Bool + if nextIdx >= visibleIds.count { + isGroupBoundary = true + } else { + let nextParent = tabManager.groupManager.parentWorkspace(of: visibleIds[nextIdx]) + isGroupBoundary = myParent?.id != nextParent?.id + } + if isGroupBoundary { + dropIndicator = SidebarDropIndicator(tabId: targetTabId, edge: .bottom) + return + } + } + } + dropIndicator = SidebarDropPlanner.indicator( draggedTabId: draggedTabId, targetTabId: targetTabId, - tabIds: tabIds, + tabIds: visibleIds, pinnedTabIds: pinnedTabIds, pointerY: targetTabId == nil ? nil : info.location.y, targetHeight: targetRowHeight @@ -13133,7 +13214,8 @@ private struct SidebarTabDropDelegate: DropDelegate { private func syncSidebarSelection(preferredSelectedTabId: UUID? = nil) { let selectedId = preferredSelectedTabId ?? tabManager.selectedTabId if let selectedId { - lastSidebarSelectionIndex = tabManager.tabs.firstIndex { $0.id == selectedId } + let visible = tabManager.groupManager.visibleWorkspaces() + lastSidebarSelectionIndex = visible.firstIndex { $0.id == selectedId } } else { lastSidebarSelectionIndex = nil } @@ -13146,6 +13228,67 @@ private struct SidebarTabDropDelegate: DropDelegate { } } +/// Drop delegate for the 10px spacer between tier 1 workspace groups. +/// Upper half → append as last child of the group above. +/// Lower half → insert as tier 1 before the group below. +private struct SidebarGroupSpacerDropDelegate: DropDelegate { + let previousGroupLastChildId: UUID? + let nextTopLevelTabId: UUID + let tabManager: TabManager + @Binding var draggedTabId: UUID? + @Binding var selectedTabIds: Set + @Binding var lastSidebarSelectionIndex: Int? + let dragAutoScrollController: SidebarDragAutoScrollController + @Binding var dropIndicator: SidebarDropIndicator? + + func validateDrop(info: DropInfo) -> Bool { + info.hasItemsConforming(to: [SidebarTabDragPayload.typeIdentifier]) && draggedTabId != nil + } + + func dropEntered(info: DropInfo) { + dragAutoScrollController.updateFromDragLocation() + updateIndicator(for: info) + } + + func dropUpdated(info: DropInfo) -> DropProposal? { + dragAutoScrollController.updateFromDragLocation() + updateIndicator(for: info) + return DropProposal(operation: .move) + } + + func dropExited(info: DropInfo) {} + + func performDrop(info: DropInfo) -> Bool { + defer { + draggedTabId = nil + dropIndicator = nil + dragAutoScrollController.stop() + } + guard let draggedTabId, let indicator = dropIndicator else { return false } + let moved = tabManager.moveWorkspaceByIndicator( + tabId: draggedTabId, + targetTabId: indicator.tabId, + edge: indicator.edge + ) + if moved, let selectedId = tabManager.selectedTabId { + selectedTabIds = [selectedId] + let visible = tabManager.groupManager.visibleWorkspaces() + lastSidebarSelectionIndex = visible.firstIndex { $0.id == selectedId } + } + return moved + } + + private func updateIndicator(for info: DropInfo) { + let spacerHeight: CGFloat = 10 + let y = info.location.y + if y < spacerHeight / 2, let prevId = previousGroupLastChildId { + dropIndicator = SidebarDropIndicator(tabId: prevId, edge: .bottom) + } else { + dropIndicator = SidebarDropIndicator(tabId: nextTopLevelTabId, edge: .top) + } + } +} + private struct MiddleClickCapture: NSViewRepresentable { let onMiddleClick: () -> Void diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 16d0cb4cefc8..8a10f9c1d1f2 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -2105,6 +2105,86 @@ class TabManager: ObservableObject { return false } + // MARK: - Hierarchy-Aware Drag-and-Drop + + /// Move a workspace based on drop indicator position. + /// The target's parent determines the dragged item's new level. + /// edge == .top → insert before target; edge == .bottom → insert after target. + /// If targetTabId is nil, append as top-level. + @discardableResult + func moveWorkspaceByIndicator(tabId draggedId: UUID, targetTabId: UUID?, edge: SidebarDropEdge) -> Bool { + // Drop on empty area → append as top-level + guard let targetId = targetTabId else { + return moveToTopLevel(draggedId: draggedId, insertIndex: groupManager.items.count) + } + guard draggedId != targetId else { return true } + // Prevent dropping onto own descendant (cycle) + if groupManager.allDescendantIds(of: draggedId).contains(targetId) { return false } + + let targetParent = groupManager.parentWorkspace(of: targetId) + + if let parent = targetParent { + // Target is a child → dragged becomes child of the same parent + guard let targetChildIdx = parent.childWorkspaceIds.firstIndex(of: targetId) else { return false } + let insertIdx = (edge == .bottom) ? targetChildIdx + 1 : targetChildIdx + return moveToChild(draggedId: draggedId, newParent: parent, insertIndex: insertIdx) + } else { + // Target is top-level → dragged becomes top-level + guard let targetTopIdx = groupManager.items.firstIndex(of: targetId) else { return false } + let insertIdx = (edge == .bottom) ? targetTopIdx + 1 : targetTopIdx + return moveToTopLevel(draggedId: draggedId, insertIndex: insertIdx) + } + } + + private func removeDraggedFromCurrentLocation(_ draggedId: UUID) { + if let currentParent = groupManager.parentWorkspace(of: draggedId) { + currentParent.childWorkspaceIds.removeAll { $0 == draggedId } + } else { + groupManager.items.removeAll { $0 == draggedId } + } + } + + private func moveToTopLevel(draggedId: UUID, insertIndex: Int) -> Bool { + let subtreeDepth = groupManager.maxDescendantDepth(of: draggedId) + guard subtreeDepth <= 3 else { return false } + + // No-op check + if let existingIdx = groupManager.items.firstIndex(of: draggedId) { + let clamped = min(insertIndex, groupManager.items.count) + let effective = clamped > existingIdx ? clamped - 1 : clamped + if effective == existingIdx { return true } + } + + removeDraggedFromCurrentLocation(draggedId) + let finalIdx = min(insertIndex, groupManager.items.count) + groupManager.items.insert(draggedId, at: finalIdx) + items = groupManager.items + return true + } + + private func moveToChild(draggedId: UUID, newParent: Workspace, insertIndex: Int) -> Bool { + guard newParent.id != draggedId else { return false } + + let parentDepth = groupManager.depthOf(workspaceId: newParent.id) + let subtreeDepth = groupManager.maxDescendantDepth(of: draggedId) + guard parentDepth + subtreeDepth <= 3 else { return false } + + // Same-parent no-op check + if let currentParent = groupManager.parentWorkspace(of: draggedId), currentParent.id == newParent.id { + if let existingIdx = newParent.childWorkspaceIds.firstIndex(of: draggedId) { + let clamped = min(insertIndex, newParent.childWorkspaceIds.count) + let effective = clamped > existingIdx ? clamped - 1 : clamped + if effective == existingIdx { return true } + } + } + + removeDraggedFromCurrentLocation(draggedId) + let finalIdx = min(insertIndex, newParent.childWorkspaceIds.count) + newParent.childWorkspaceIds.insert(draggedId, at: finalIdx) + items = groupManager.items + return true + } + func setCustomTitle(tabId: UUID, title: String?) { guard let index = tabs.firstIndex(where: { $0.id == tabId }) else { return } tabs[index].setCustomTitle(title) diff --git a/Sources/WorkspaceGroupManager.swift b/Sources/WorkspaceGroupManager.swift index 3765b4a76e02..8a5fd18af662 100644 --- a/Sources/WorkspaceGroupManager.swift +++ b/Sources/WorkspaceGroupManager.swift @@ -171,7 +171,7 @@ final class WorkspaceGroupManager: ObservableObject { } /// Maximum depth of the subtree rooted at the given workspace (1 = leaf). - private func maxDescendantDepth(of workspaceId: UUID) -> Int { + func maxDescendantDepth(of workspaceId: UUID) -> Int { guard let ws = tabManager?.workspace(for: workspaceId) else { return 1 } if ws.childWorkspaceIds.isEmpty { return 1 } var maxChild = 0 From 6d7f4df9c2a36426349b196dec22886b7403965c Mon Sep 17 00:00:00 2001 From: roberf Date: Fri, 27 Mar 2026 01:54:11 -0400 Subject: [PATCH 7/8] fix: render close-dialog buttons as destructive for dark-mode visibility Replace defaultButtonCell/keyEquivalent overrides with hasDestructiveAction in all three close-confirmation alerts. Adds Phase 1 shadow fields for menu-state decoupling and TabItemDisplaySnapshot infrastructure. Co-Authored-By: Claude Opus 4.6 (1M context) --- GhosttyTabs.xcodeproj/project.pbxproj | 4 + Resources/Info.plist | 2 + Sources/AppDelegate.swift | 11 +- Sources/ScriptsMenu.swift | 5 +- Sources/TabItemDisplaySnapshot.swift | 83 ++++++++++ Sources/TabManager.swift | 10 +- Sources/Workspace.swift | 78 ++++++++-- cmuxTests/FocusedPanelMenuStateTests.swift | 172 +++++++++++++++++++++ 8 files changed, 336 insertions(+), 29 deletions(-) create mode 100644 Sources/TabItemDisplaySnapshot.swift create mode 100644 cmuxTests/FocusedPanelMenuStateTests.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 759b694de128..85fb1eba807f 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -144,6 +144,7 @@ WG000027A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000028A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift */; }; WG000029A1B2C3D4E5F60001 /* NewWorkspaceDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */; }; WG00002BA1B2C3D4E5F60001 /* ScriptsMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */; }; + WG00000IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift */; }; WG00002DA1B2C3D4E5F60001 /* TemplateManagerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */; }; WG00002FA1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */; }; WG000031A1B2C3D4E5F60001 /* ScriptManagerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */; }; @@ -287,6 +288,7 @@ WG000028A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerProjectCommands.swift; sourceTree = ""; }; WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewWorkspaceDialog.swift; sourceTree = ""; }; WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptsMenu.swift; sourceTree = ""; }; + WG00001IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabItemDisplaySnapshot.swift; sourceTree = ""; }; WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerWindow.swift; sourceTree = ""; }; WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerHelpSidebar.swift; sourceTree = ""; }; WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptManagerWindow.swift; sourceTree = ""; }; @@ -528,6 +530,7 @@ WG000024A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift */, WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */, WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */, + WG00001IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift */, WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */, WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */, WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */, @@ -847,6 +850,7 @@ WG000010A1B2C3D4E5F60001 /* StartupScriptRunner.swift in Sources */, WG000021A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift in Sources */, WG000023A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift in Sources */, + WG00000IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift in Sources */, WG000025A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift in Sources */, WG000027A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift in Sources */, WG000029A1B2C3D4E5F60001 /* NewWorkspaceDialog.swift in Sources */, diff --git a/Resources/Info.plist b/Resources/Info.plist index 0ba92bdcd1ab..d88bd18fc154 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -41,6 +41,8 @@ NSMainStoryboardFile + NSLocalNetworkUsageDescription + cmux scans listening ports on your terminal processes to display active servers in the workspace sidebar. NSMicrophoneUsageDescription A program running within cmux would like to use your microphone. NSCameraUsageDescription diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 2d206afd0078..5e953649302d 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -4772,13 +4772,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent alert.addButton(withTitle: String(localized: "common.close", defaultValue: "Close")) alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel")) - let alertWindow = alert.window - if let closeButton = alert.buttons.first { - alertWindow.defaultButtonCell = closeButton.cell as? NSButtonCell - alertWindow.initialFirstResponder = closeButton - DispatchQueue.main.async { - _ = alertWindow.makeFirstResponder(closeButton) - } + // Mark the Close button as destructive so the system renders it with + // red text, fixing a contrast issue in dark mode. + if #available(macOS 12.0, *) { + alert.buttons[0].hasDestructiveAction = true } return alert.runModal() == .alertFirstButtonReturn diff --git a/Sources/ScriptsMenu.swift b/Sources/ScriptsMenu.swift index f2819cb63254..04509e1bc2f9 100644 --- a/Sources/ScriptsMenu.swift +++ b/Sources/ScriptsMenu.swift @@ -28,7 +28,10 @@ struct ScriptsMenuContent: View, Equatable { @ViewBuilder private var runScriptSubmenu: some View { - let isAtPrompt = Self.resolveActiveTabManager()?.selectedTab?.isFocusedPanelAtPrompt ?? false + // Read the published snapshot field rather than the live computed property so + // this menu builder does not trigger a rebuild — and menu dismissal — on every + // unrelated Workspace.objectWillChange during a running terminal process. + let isAtPrompt = Self.resolveActiveTabManager()?.selectedTab?.focusedPanelIsAtPrompt ?? false Menu(String(localized: "menu.scripts.runScript", defaultValue: "Run Script")) { ForEach(scriptNames, id: \.self) { scriptName in Button(scriptName) { diff --git a/Sources/TabItemDisplaySnapshot.swift b/Sources/TabItemDisplaySnapshot.swift new file mode 100644 index 000000000000..85f7c55fefb1 --- /dev/null +++ b/Sources/TabItemDisplaySnapshot.swift @@ -0,0 +1,83 @@ +import Combine +import Foundation + +// MARK: - TabItemDisplaySnapshot + +/// Immutable value snapshot of all display-driving state for a single workspace sidebar row. +/// Passed as a `let` parameter to `TabItemView` so that the view never holds a direct +/// `@ObservedObject` subscription to `Workspace`. Only `WorkspaceDisplayPublisher` subscribes +/// to the workspace; it re-publishes only when the snapshot actually changes, preventing +/// spurious body re-evaluations caused by high-frequency `@Published` updates (e.g. port scanner). +struct TabItemDisplaySnapshot: Equatable { + // Title + let title: String + let customTitle: String? // non-nil = hasCustomTitle + + // Basic flags + let isPinned: Bool + let customColor: String? + + // Workspace group state + let hasChildren: Bool + let isCollapsed: Bool + let hasStartupCommand: Bool + + // Prompt / terminal state + let isAtPrompt: Bool + let hasFocusedTerminalPanel: Bool + + // Port scanner + let listeningPorts: [Int] + + // Sidebar content — pre-computed, ordered + let orderedPanelIds: [UUID] + let gitBranches: [SidebarGitBranchState] + let branchDirectoryEntries: [SidebarBranchOrdering.BranchDirectoryEntry] + let directories: [String] + let pullRequests: [SidebarPullRequestState] + let statusEntries: [SidebarStatusEntry] + let metadataBlocks: [SidebarMetadataBlock] + let logEntries: [SidebarLogEntry] + let progress: SidebarProgressState? + + // Remote connection + let remoteConnectionState: WorkspaceRemoteConnectionState + let remoteConnectionDetail: String? + let remoteDisplayTarget: String? + let hasActiveRemoteTerminalSessions: Bool + let remoteStatusEntry: SidebarStatusEntry? // statusEntries["remote.error"] +} + +// MARK: - WorkspaceDisplayPublisher + +/// `ObservableObject` wrapper around `TabItemDisplaySnapshot` that coalesces +/// `Workspace.objectWillChange` notifications and only re-publishes when the computed +/// snapshot actually differs from the previous one. +/// +/// Usage: each `Workspace` owns one `WorkspaceDisplayPublisher`. `VerticalTabsSidebar` +/// passes `workspace.displayPublisher.snapshot` as a `let` parameter to `TabItemView`. +@MainActor +final class WorkspaceDisplayPublisher: ObservableObject { + @Published private(set) var snapshot: TabItemDisplaySnapshot + + private var cancellable: AnyCancellable? + private var pendingRefresh = false + + init(workspace: Workspace) { + self.snapshot = workspace.computeDisplaySnapshot() + self.cancellable = workspace.objectWillChange + .sink { [weak self, weak workspace] _ in + guard let self, !self.pendingRefresh else { return } + self.pendingRefresh = true + // Defer to next run-loop turn so all @Published mutations in this cycle + // have been applied before we re-compute the snapshot. + DispatchQueue.main.async { [weak self, weak workspace] in + self?.pendingRefresh = false + guard let self, let workspace else { return } + let new = workspace.computeDisplaySnapshot() + guard new != self.snapshot else { return } + self.snapshot = new + } + } + } +} diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 8a10f9c1d1f2..c4e1a09c1ae8 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -2494,14 +2494,8 @@ class TabManager: ObservableObject { alert.addButton(withTitle: String(localized: "dialog.closeTab.close", defaultValue: "Close")) alert.addButton(withTitle: String(localized: "dialog.closeTab.cancel", defaultValue: "Cancel")) - if let closeButton = alert.buttons.first { - closeButton.keyEquivalent = "\r" - closeButton.keyEquivalentModifierMask = [] - alert.window.defaultButtonCell = closeButton.cell as? NSButtonCell - alert.window.initialFirstResponder = closeButton - } - if let cancelButton = alert.buttons.dropFirst().first { - cancelButton.keyEquivalent = "\u{1b}" + if #available(macOS 12.0, *) { + alert.buttons[0].hasDestructiveAction = true } if NSApp.activationPolicy() == .regular { diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 7fafcf803467..2dd3a62674f0 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -59,7 +59,7 @@ func cmuxInheritedSurfaceConfig( return config } -struct SidebarStatusEntry { +struct SidebarStatusEntry: Equatable { let key: String let value: String let icon: String? @@ -90,7 +90,7 @@ struct SidebarStatusEntry { } } -struct SidebarMetadataBlock { +struct SidebarMetadataBlock: Equatable { let key: String let markdown: String let priority: Int @@ -4403,19 +4403,19 @@ enum SidebarLogLevel: String { case error } -struct SidebarLogEntry { +struct SidebarLogEntry: Equatable { let message: String let level: SidebarLogLevel let source: String? let timestamp: Date } -struct SidebarProgressState { +struct SidebarProgressState: Equatable { let value: Double let label: String? } -struct SidebarGitBranchState { +struct SidebarGitBranchState: Equatable { let branch: String let isDirty: Bool } @@ -5085,6 +5085,16 @@ final class Workspace: Identifiable, ObservableObject { return formatter }() private var panelShellActivityStates: [UUID: PanelShellActivityState] = [:] + /// Snapshot of isFocusedPanelAtPrompt published for stable menu rendering. + /// Updated by refreshFocusedPanelMenuState() at every mutation site that can + /// change which panel is focused or whether it is at a shell prompt. + @Published private(set) var focusedPanelIsAtPrompt: Bool = false + /// Snapshot of (focusedTerminalPanel != nil) published for stable menu rendering. + @Published private(set) var focusedPanelHasTerminal: Bool = false + /// Change-detected publisher of `TabItemDisplaySnapshot` for this workspace. + /// `TabItemView` observes this instead of `Workspace` directly, preventing + /// body re-evaluations when unrelated `@Published` properties (e.g. listeningPorts) fire. + lazy var displayPublisher: WorkspaceDisplayPublisher = WorkspaceDisplayPublisher(workspace: self) /// One-shot callback fired when a panel first reaches promptIdle. /// Keyed by panel ID. Removed after firing. var onPromptReady: [UUID: () -> Void] = [:] @@ -5858,6 +5868,10 @@ final class Workspace: Identifiable, ObservableObject { "panel=\(panelId.uuidString.prefix(5)) from=\(previousState.rawValue) to=\(state.rawValue)" ) #endif + // Refresh menu snapshot when the focused panel's shell state changes. + if panelId == focusedPanelId { + refreshFocusedPanelMenuState() + } // Fire one-shot prompt-ready callback if state == .promptIdle, let callback = onPromptReady.removeValue(forKey: panelId) { callback() @@ -5870,6 +5884,14 @@ final class Workspace: Identifiable, ObservableObject { return panelShellActivityStates[panelId] == .promptIdle } + /// Refreshes the published shadow fields used by menu builders so they read stable + /// snapshots rather than live computed state during SwiftUI rendering. + /// Call after any mutation that can change the focused panel or its shell-activity state. + private func refreshFocusedPanelMenuState() { + focusedPanelIsAtPrompt = isFocusedPanelAtPrompt + focusedPanelHasTerminal = (focusedTerminalPanel != nil) + } + func panelNeedsConfirmClose(panelId: UUID, fallbackNeedsConfirmClose: Bool) -> Bool { Self.resolveCloseConfirmation( shellActivityState: panelShellActivityStates[panelId], @@ -6071,6 +6093,7 @@ final class Workspace: Identifiable, ObservableObject { panelShellActivityStates = panelShellActivityStates.filter { validSurfaceIds.contains($0.key) } panelPullRequests = panelPullRequests.filter { validSurfaceIds.contains($0.key) } recomputeListeningPorts() + refreshFocusedPanelMenuState() } func recomputeListeningPorts() { @@ -6251,6 +6274,36 @@ final class Workspace: Identifiable, ObservableObject { activeRemoteTerminalSessionCount > 0 } + func computeDisplaySnapshot() -> TabItemDisplaySnapshot { + let panelIds = sidebarOrderedPanelIds() + return TabItemDisplaySnapshot( + title: title, + customTitle: customTitle, + isPinned: isPinned, + customColor: customColor, + hasChildren: hasChildren, + isCollapsed: isCollapsed, + hasStartupCommand: startupCommand != nil, + isAtPrompt: focusedPanelIsAtPrompt, + hasFocusedTerminalPanel: focusedPanelHasTerminal, + listeningPorts: listeningPorts, + orderedPanelIds: panelIds, + gitBranches: sidebarGitBranchesInDisplayOrder(orderedPanelIds: panelIds), + branchDirectoryEntries: sidebarBranchDirectoryEntriesInDisplayOrder(orderedPanelIds: panelIds), + directories: sidebarDirectoriesInDisplayOrder(orderedPanelIds: panelIds), + pullRequests: sidebarPullRequestsInDisplayOrder(orderedPanelIds: panelIds), + statusEntries: sidebarStatusEntriesInDisplayOrder(), + metadataBlocks: sidebarMetadataBlocksInDisplayOrder(), + logEntries: logEntries, + progress: progress, + remoteConnectionState: remoteConnectionState, + remoteConnectionDetail: remoteConnectionDetail, + remoteDisplayTarget: remoteDisplayTarget, + hasActiveRemoteTerminalSessions: hasActiveRemoteTerminalSessions, + remoteStatusEntry: statusEntries["remote.error"] + ) + } + func remoteStatusPayload() -> [String: Any] { let heartbeatAgeSeconds: Any = { guard let last = remoteLastHeartbeatAt else { return NSNull() } @@ -8260,6 +8313,7 @@ final class Workspace: Identifiable, ObservableObject { } gitBranch = panelGitBranches[targetPanelId] pullRequest = panelPullRequests[targetPanelId] + refreshFocusedPanelMenuState() } /// Reconcile focus/first-responder convergence. @@ -9049,14 +9103,10 @@ extension Workspace: BonsplitDelegate { alert.addButton(withTitle: String(localized: "dialog.closeTab.close", defaultValue: "Close")) alert.addButton(withTitle: String(localized: "dialog.closeTab.cancel", defaultValue: "Cancel")) - if let closeButton = alert.buttons.first { - closeButton.keyEquivalent = "\r" - closeButton.keyEquivalentModifierMask = [] - alert.window.defaultButtonCell = closeButton.cell as? NSButtonCell - alert.window.initialFirstResponder = closeButton - } - if let cancelButton = alert.buttons.dropFirst().first { - cancelButton.keyEquivalent = "\u{1b}" + // Mark the Close button as destructive so the system renders it with + // red text, fixing a contrast issue in dark mode. + if #available(macOS 12.0, *) { + alert.buttons[0].hasDestructiveAction = true } // Prefer a sheet if we can find a window, otherwise fall back to modal. @@ -9285,6 +9335,8 @@ extension Workspace: BonsplitDelegate { "prevPanel=\(prevPanelShort)" ) #endif + // Keep menu-state snapshots current whenever focused panel changes. + refreshFocusedPanelMenuState() } private func activatePanel( diff --git a/cmuxTests/FocusedPanelMenuStateTests.swift b/cmuxTests/FocusedPanelMenuStateTests.swift new file mode 100644 index 000000000000..2dc00bfd95b3 --- /dev/null +++ b/cmuxTests/FocusedPanelMenuStateTests.swift @@ -0,0 +1,172 @@ +import XCTest +import AppKit + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +// Behavioral regression tests for the focused-panel menu-state snapshot fields +// (focusedPanelIsAtPrompt, focusedPanelHasTerminal) introduced to prevent +// menu dismissal during terminal process churn. +// +// All tests run on the main actor because Workspace is an ObservableObject +// whose mutations must happen on the main thread. + +@MainActor +final class FocusedPanelMenuStateTests: XCTestCase { + + // MARK: - Test 1: isAtPrompt follows shell-state changes on the focused panel + + func testFocusedPanelIsAtPromptFollowsShellStateChanges() { + let workspace = Workspace() + guard let panelId = workspace.focusedPanelId else { + XCTFail("Expected a focused panel in a fresh workspace") + return + } + + // Initial state: no shell-state reported yet — should be false. + XCTAssertFalse( + workspace.focusedPanelIsAtPrompt, + "Expected false before any shell state is reported" + ) + + // Drive the panel to a running state. + workspace.updatePanelShellActivityState(panelId: panelId, state: .commandRunning) + XCTAssertFalse( + workspace.focusedPanelIsAtPrompt, + "Expected false when focused panel is running a command" + ) + + // Drive the panel to prompt-idle. + workspace.updatePanelShellActivityState(panelId: panelId, state: .promptIdle) + XCTAssertTrue( + workspace.focusedPanelIsAtPrompt, + "Expected true when focused panel reaches promptIdle" + ) + + // Back to running. + workspace.updatePanelShellActivityState(panelId: panelId, state: .commandRunning) + XCTAssertFalse( + workspace.focusedPanelIsAtPrompt, + "Expected false after focused panel returns to commandRunning" + ) + } + + // MARK: - Test 2: isAtPrompt updates on focus switch + + func testFocusedPanelIsAtPromptUpdatesOnFocusSwitch() { + let workspace = Workspace() + guard let panelA = workspace.focusedPanelId else { + XCTFail("Expected a focused panel in a fresh workspace") + return + } + guard let paneId = workspace.bonsplitController.focusedPaneId else { + XCTFail("Expected a focused pane in a fresh workspace") + return + } + + // Create a second terminal panel in the same pane. + guard let panelB = workspace.newTerminalSurface(inPane: paneId, focus: false) else { + XCTFail("Expected newTerminalSurface to succeed") + return + } + + // Give panel A prompt-idle and panel B command-running. + workspace.updatePanelShellActivityState(panelId: panelA, state: .promptIdle) + workspace.updatePanelShellActivityState(panelId: panelB.id, state: .commandRunning) + + // Panel A is currently focused — snapshot should be true. + XCTAssertEqual( + workspace.focusedPanelId, panelA, + "Expected panel A to still be focused" + ) + XCTAssertTrue( + workspace.focusedPanelIsAtPrompt, + "Expected true while focused panel A is at prompt" + ) + + // Switch focus to panel B. + workspace.focusPanel(panelB.id) + + XCTAssertEqual( + workspace.focusedPanelId, panelB.id, + "Expected panel B to be focused after focusPanel" + ) + XCTAssertFalse( + workspace.focusedPanelIsAtPrompt, + "Expected false after switching focus to running panel B" + ) + } + + // MARK: - Test 3: focusedPanelHasTerminal + + // Workspace always contains a TerminalPanel as its initial panel type, so + // focusedPanelHasTerminal should be true after normal workspace creation + // and should remain true when moving focus between terminal panels. + // Switching to a non-terminal panel type (browser/markdown) is not + // straightforwardly exercisable in a headless unit test because + // BrowserPanel and MarkdownPanel require AppKit window infrastructure. + // This test confirms the true case and documents the limitation. + + func testFocusedPanelHasTerminalIsTrueForTerminalWorkspace() { + let workspace = Workspace() + + // After applyTabSelection fires during init, focusedPanelHasTerminal + // should reflect that the focused panel is a TerminalPanel. + XCTAssertTrue( + workspace.focusedPanelHasTerminal, + "Expected focusedPanelHasTerminal true when focused panel is a terminal" + ) + } + + // MARK: - Test 4: Removal path regression + + func testSnapshotReflectsNewFocusedPanelAfterFocusedPanelIsRemoved() { + let workspace = Workspace() + guard let initialPanelId = workspace.focusedPanelId else { + XCTFail("Expected a focused panel in a fresh workspace") + return + } + guard let paneId = workspace.bonsplitController.focusedPaneId else { + XCTFail("Expected a focused pane in a fresh workspace") + return + } + + // Create a second panel and mark it as at-prompt. + guard let secondPanel = workspace.newTerminalSurface(inPane: paneId, focus: false) else { + XCTFail("Expected newTerminalSurface to succeed") + return + } + workspace.updatePanelShellActivityState(panelId: secondPanel.id, state: .promptIdle) + + // Initial panel is at commandRunning — it is focused. + workspace.updatePanelShellActivityState(panelId: initialPanelId, state: .commandRunning) + XCTAssertFalse( + workspace.focusedPanelIsAtPrompt, + "Expected false while focused initial panel is running" + ) + + // Close the focused panel (force:true bypasses any confirmation guard). + // Workspace delegate will select the next available panel. + let closed = workspace.closePanel(initialPanelId, force: true) + XCTAssertTrue(closed, "Expected closePanel to succeed for the focused panel") + + // After removal the new focused panel is the second panel (promptIdle). + XCTAssertTrue( + workspace.focusedPanelIsAtPrompt, + "Expected focusedPanelIsAtPrompt to reflect the new focused panel (promptIdle) after removal" + ) + // The new focused panel is still a terminal. + XCTAssertTrue( + workspace.focusedPanelHasTerminal, + "Expected focusedPanelHasTerminal true after panel removal" + ) + // The removed panel's ID must not still be the focused panel. + XCTAssertNotEqual( + workspace.focusedPanelId, initialPanelId, + "Expected focused panel to change after removing the previously focused panel" + ) + } +} From 4614ccc3b368e7a3c1927970948b4f4b243c428c Mon Sep 17 00:00:00 2001 From: roberf Date: Fri, 27 Mar 2026 04:47:22 -0400 Subject: [PATCH 8/8] fix: replace SwiftUI context menu with NSMenuDelegate to eliminate submenu flicker Move sidebar context menu from SwiftUI .contextMenu to an AppKit NSMenu built at right-click time via NSMenuDelegate.menuNeedsUpdate. The menu is fully static while open, decoupled from the SwiftUI rendering pipeline. Removes ~300 lines of dead SwiftUI menu code from ContentView.swift. Co-Authored-By: Claude Opus 4.6 (1M context) --- GhosttyTabs.xcodeproj/project.pbxproj | 12 + Sources/ContentView.swift | 564 +-------------------- Sources/SidebarContextMenuActions.swift | 186 +++++++ Sources/SidebarContextMenuController.swift | 421 +++++++++++++++ Sources/SidebarContextMenuHost.swift | 64 +++ 5 files changed, 695 insertions(+), 552 deletions(-) create mode 100644 Sources/SidebarContextMenuActions.swift create mode 100644 Sources/SidebarContextMenuController.swift create mode 100644 Sources/SidebarContextMenuHost.swift diff --git a/GhosttyTabs.xcodeproj/project.pbxproj b/GhosttyTabs.xcodeproj/project.pbxproj index 85fb1eba807f..61f83de311ca 100644 --- a/GhosttyTabs.xcodeproj/project.pbxproj +++ b/GhosttyTabs.xcodeproj/project.pbxproj @@ -145,6 +145,9 @@ WG000029A1B2C3D4E5F60001 /* NewWorkspaceDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */; }; WG00002BA1B2C3D4E5F60001 /* ScriptsMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */; }; WG00000IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00001IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift */; }; + WG00003BA1B2C3D4E5F60001 /* SidebarContextMenuHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00003AA1B2C3D4E5F60001 /* SidebarContextMenuHost.swift */; }; + WG00003DA1B2C3D4E5F60001 /* SidebarContextMenuController.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00003CA1B2C3D4E5F60001 /* SidebarContextMenuController.swift */; }; + WG00003FA1B2C3D4E5F60001 /* SidebarContextMenuActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00003EA1B2C3D4E5F60001 /* SidebarContextMenuActions.swift */; }; WG00002DA1B2C3D4E5F60001 /* TemplateManagerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */; }; WG00002FA1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */; }; WG000031A1B2C3D4E5F60001 /* ScriptManagerWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */; }; @@ -289,6 +292,9 @@ WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewWorkspaceDialog.swift; sourceTree = ""; }; WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptsMenu.swift; sourceTree = ""; }; WG00001IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabItemDisplaySnapshot.swift; sourceTree = ""; }; + WG00003AA1B2C3D4E5F60001 /* SidebarContextMenuHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarContextMenuHost.swift; sourceTree = ""; }; + WG00003CA1B2C3D4E5F60001 /* SidebarContextMenuController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarContextMenuController.swift; sourceTree = ""; }; + WG00003EA1B2C3D4E5F60001 /* SidebarContextMenuActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarContextMenuActions.swift; sourceTree = ""; }; WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerWindow.swift; sourceTree = ""; }; WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManagerHelpSidebar.swift; sourceTree = ""; }; WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptManagerWindow.swift; sourceTree = ""; }; @@ -531,6 +537,9 @@ WG00002AA1B2C3D4E5F60001 /* NewWorkspaceDialog.swift */, WG00002CA1B2C3D4E5F60001 /* ScriptsMenu.swift */, WG00001IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift */, + WG00003AA1B2C3D4E5F60001 /* SidebarContextMenuHost.swift */, + WG00003CA1B2C3D4E5F60001 /* SidebarContextMenuController.swift */, + WG00003EA1B2C3D4E5F60001 /* SidebarContextMenuActions.swift */, WG00002EA1B2C3D4E5F60001 /* TemplateManagerWindow.swift */, WG000030A1B2C3D4E5F60001 /* TemplateManagerHelpSidebar.swift */, WG000032A1B2C3D4E5F60001 /* ScriptManagerWindow.swift */, @@ -851,6 +860,9 @@ WG000021A1B2C3D4E5F60001 /* TerminalControllerGroupCommands.swift in Sources */, WG000023A1B2C3D4E5F60001 /* TerminalControllerScriptTemplateCommands.swift in Sources */, WG00000IA1B2C3D4E5F60001 /* TabItemDisplaySnapshot.swift in Sources */, + WG00003BA1B2C3D4E5F60001 /* SidebarContextMenuHost.swift in Sources */, + WG00003DA1B2C3D4E5F60001 /* SidebarContextMenuController.swift in Sources */, + WG00003FA1B2C3D4E5F60001 /* SidebarContextMenuActions.swift in Sources */, WG000025A1B2C3D4E5F60001 /* CmuxConfigParserGroups.swift in Sources */, WG000027A1B2C3D4E5F60001 /* TerminalControllerProjectCommands.swift in Sources */, WG000029A1B2C3D4E5F60001 /* NewWorkspaceDialog.swift in Sources */, diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index d93f130af849..6e6a5c8bf578 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -9,17 +9,6 @@ import WebKit // Color(hex:) extension is defined in GroupHeaderView.swift (module-scoped) -private func coloredCircleImage(color: NSColor) -> NSImage { - let size = NSSize(width: 14, height: 14) - let image = NSImage(size: size, flipped: false) { rect in - color.setFill() - NSBezierPath(ovalIn: rect.insetBy(dx: 1, dy: 1)).fill() - return true - } - image.isTemplate = false - return image -} - func sidebarActiveForegroundNSColor( opacity: CGFloat, appAppearance: NSAppearance? = NSApp?.effectiveAppearance @@ -8355,13 +8344,6 @@ struct VerticalTabsSidebar: View { depth: Int, parentCustomColorHex: String? = nil ) -> some View { - let selectedContextIds: Set = selectedTabIds.contains(tab.id) ? selectedTabIds : [tab.id] - let contextTargetIds = tabManager.tabs.compactMap { workspace in - selectedContextIds.contains(workspace.id) ? workspace.id : nil - } - let remoteContextMenuTargets = tabManager.tabs.filter { workspace in - contextTargetIds.contains(workspace.id) && workspace.isRemoteWorkspace - } TabItemView( tabManager: tabManager, notificationStore: notificationStore, @@ -8392,9 +8374,6 @@ struct VerticalTabsSidebar: View { dragAutoScrollController: dragAutoScrollController, draggedTabId: $draggedTabId, dropIndicator: $dropIndicator, - remoteContextMenuWorkspaceIds: remoteContextMenuTargets.map(\.id), - allRemoteContextMenuTargetsConnecting: !remoteContextMenuTargets.isEmpty && remoteContextMenuTargets.allSatisfy { $0.remoteConnectionState == .connecting }, - allRemoteContextMenuTargetsDisconnected: !remoteContextMenuTargets.isEmpty && remoteContextMenuTargets.allSatisfy { $0.remoteConnectionState == .disconnected }, depth: depth, hasChildren: tab.hasChildren, isCollapsed: tab.isCollapsed, @@ -10793,9 +10772,6 @@ private struct TabItemView: View, Equatable { lhs.latestNotificationText == rhs.latestNotificationText && lhs.rowSpacing == rhs.rowSpacing && lhs.showsModifierShortcutHints == rhs.showsModifierShortcutHints && - lhs.remoteContextMenuWorkspaceIds == rhs.remoteContextMenuWorkspaceIds && - lhs.allRemoteContextMenuTargetsConnecting == rhs.allRemoteContextMenuTargetsConnecting && - lhs.allRemoteContextMenuTargetsDisconnected == rhs.allRemoteContextMenuTargetsDisconnected && lhs.depth == rhs.depth && lhs.hasChildren == rhs.hasChildren && lhs.isCollapsed == rhs.isCollapsed && @@ -10825,9 +10801,6 @@ private struct TabItemView: View, Equatable { let dragAutoScrollController: SidebarDragAutoScrollController @Binding var draggedTabId: UUID? @Binding var dropIndicator: SidebarDropIndicator? - let remoteContextMenuWorkspaceIds: [UUID] - let allRemoteContextMenuTargetsConnecting: Bool - let allRemoteContextMenuTargetsDisconnected: Bool var depth: Int = 0 var hasChildren: Bool = false var isCollapsed: Bool = false @@ -10959,33 +10932,6 @@ private struct TabItemView: View, Equatable { return String(localized: "sidebar.remote.subtitleFallback", defaultValue: "SSH workspace") } - private var copyableSidebarSSHError: String? { - let fallbackTarget = tab.remoteDisplayTarget ?? String( - localized: "sidebar.remote.help.targetFallback", - defaultValue: "remote host" - ) - let trimmedDetail = tab.remoteConnectionDetail?.trimmingCharacters(in: .whitespacesAndNewlines) - if tab.remoteConnectionState == .error, let trimmedDetail, !trimmedDetail.isEmpty { - let entry = SidebarRemoteErrorCopyEntry( - workspaceTitle: tab.title, - target: fallbackTarget, - detail: trimmedDetail - ) - return SidebarRemoteErrorCopySupport.clipboardText(for: [entry]) - } - if let statusValue = tab.statusEntries["remote.error"]?.value - .trimmingCharacters(in: .whitespacesAndNewlines), - !statusValue.isEmpty { - let entry = SidebarRemoteErrorCopyEntry( - workspaceTitle: tab.title, - target: fallbackTarget, - detail: statusValue - ) - return SidebarRemoteErrorCopySupport.clipboardText(for: [entry]) - } - return nil - } - private var remoteConnectionStatusText: String { switch tab.remoteConnectionState { case .connected: @@ -11023,12 +10969,6 @@ private struct TabItemView: View, Equatable { } } - private func copyTextToPasteboard(_ text: String) { - let pasteboard = NSPasteboard.general - pasteboard.clearContents() - pasteboard.setString(text, forType: .string) - } - private var visibleAuxiliaryDetails: SidebarWorkspaceAuxiliaryDetailVisibility { SidebarWorkspaceAuxiliaryDetailVisibility.resolved( showMetadata: sidebarShowMetadata, @@ -11439,248 +11379,20 @@ private struct TabItemView: View, Equatable { .accessibilityAction(named: Text(moveDownActionText)) { moveBy(1) } - .contextMenu { workspaceContextMenu } - } - - private func contextMenuLabel(multi: String, single: String, isMulti: Bool) -> String { - isMulti ? multi : single - } - - private func remoteContextMenuWorkspaces() -> [Workspace] { - guard !remoteContextMenuWorkspaceIds.isEmpty else { return [] } - return remoteContextMenuWorkspaceIds.compactMap { workspaceId in - tabManager.tabs.first(where: { $0.id == workspaceId }) - } + .overlay( + SidebarContextMenuHost( + workspace: tab, + tabManager: tabManager, + notificationStore: notificationStore, + selectedTabIds: $selectedTabIds, + lastSidebarSelectionIndex: $lastSidebarSelectionIndex, + setSelectionToTabs: { setSelectionToTabs() }, + index: index, + depth: depth + ) + ) } - @ViewBuilder - private var workspaceContextMenu: some View { - let targetIds = contextTargetIds() - let isMulti = targetIds.count > 1 - let tabColorPalette = WorkspaceTabColorSettings.palette() - let shouldPin = !tab.isPinned - let reconnectLabel = contextMenuLabel( - multi: String(localized: "contextMenu.reconnectWorkspaces", defaultValue: "Reconnect Workspaces"), - single: String(localized: "contextMenu.reconnectWorkspace", defaultValue: "Reconnect Workspace"), - isMulti: isMulti) - let disconnectLabel = contextMenuLabel( - multi: String(localized: "contextMenu.disconnectWorkspaces", defaultValue: "Disconnect Workspaces"), - single: String(localized: "contextMenu.disconnectWorkspace", defaultValue: "Disconnect Workspace"), - isMulti: isMulti) - let pinLabel = shouldPin - ? contextMenuLabel( - multi: String(localized: "contextMenu.pinWorkspaces", defaultValue: "Pin Workspaces"), - single: String(localized: "contextMenu.pinWorkspace", defaultValue: "Pin Workspace"), - isMulti: isMulti) - : contextMenuLabel( - multi: String(localized: "contextMenu.unpinWorkspaces", defaultValue: "Unpin Workspaces"), - single: String(localized: "contextMenu.unpinWorkspace", defaultValue: "Unpin Workspace"), - isMulti: isMulti) - let closeLabel = contextMenuLabel( - multi: String(localized: "contextMenu.closeWorkspaces", defaultValue: "Close Workspaces"), - single: String(localized: "contextMenu.closeWorkspace", defaultValue: "Close Workspace"), - isMulti: isMulti) - let markReadLabel = contextMenuLabel( - multi: String(localized: "contextMenu.markWorkspacesRead", defaultValue: "Mark Workspaces as Read"), - single: String(localized: "contextMenu.markWorkspaceRead", defaultValue: "Mark Workspace as Read"), - isMulti: isMulti) - let markUnreadLabel = contextMenuLabel( - multi: String(localized: "contextMenu.markWorkspacesUnread", defaultValue: "Mark Workspaces as Unread"), - single: String(localized: "contextMenu.markWorkspaceUnread", defaultValue: "Mark Workspace as Unread"), - isMulti: isMulti) - let renameWorkspaceShortcut = KeyboardShortcutSettings.shortcut(for: .renameWorkspace) - let closeWorkspaceShortcut = KeyboardShortcutSettings.shortcut(for: .closeWorkspace) - Button(pinLabel) { - for id in targetIds { - if let tab = tabManager.tabs.first(where: { $0.id == id }) { - tabManager.setPinned(tab, pinned: shouldPin) - } - } - syncSelectionAfterMutation() - } - - if let key = renameWorkspaceShortcut.keyEquivalent { - Button(String(localized: "contextMenu.renameWorkspace", defaultValue: "Rename Workspace…")) { - promptRename() - } - .keyboardShortcut(key, modifiers: renameWorkspaceShortcut.eventModifiers) - } else { - Button(String(localized: "contextMenu.renameWorkspace", defaultValue: "Rename Workspace…")) { - promptRename() - } - } - - if tab.hasCustomTitle { - Button(String(localized: "contextMenu.removeCustomWorkspaceName", defaultValue: "Remove Custom Workspace Name")) { - tabManager.clearCustomTitle(tabId: tab.id) - } - } - - if !remoteContextMenuWorkspaceIds.isEmpty { - Divider() - - Button(reconnectLabel) { - for workspace in remoteContextMenuWorkspaces() { - workspace.reconnectRemoteConnection() - } - } - .disabled(allRemoteContextMenuTargetsConnecting) - - Button(disconnectLabel) { - for workspace in remoteContextMenuWorkspaces() { - workspace.disconnectRemoteConnection(clearConfiguration: false) - } - } - .disabled(allRemoteContextMenuTargetsDisconnected) - } - - Menu(String(localized: "contextMenu.workspaceColor", defaultValue: "Workspace Color")) { - if tab.customColor != nil { - Button { - applyTabColor(nil, targetIds: targetIds) - } label: { - Label(String(localized: "contextMenu.clearColor", defaultValue: "Clear Color"), systemImage: "xmark.circle") - } - } - - Button { - promptCustomColor(targetIds: targetIds) - } label: { - Label(String(localized: "contextMenu.chooseCustomColor", defaultValue: "Choose Custom Color…"), systemImage: "paintpalette") - } - - if !tabColorPalette.isEmpty { - Divider() - } - - ForEach(tabColorPalette, id: \.id) { entry in - Button { - applyTabColor(entry.hex, targetIds: targetIds) - } label: { - Label { - Text(entry.name) - } icon: { - Image(nsImage: coloredCircleImage(color: tabColorSwatchColor(for: entry.hex))) - } - } - } - } - - if let copyableSidebarSSHError { - Button(String(localized: "contextMenu.copySshError", defaultValue: "Copy SSH Error")) { - copyTextToPasteboard(copyableSidebarSSHError) - } - } - - Divider() - - runScriptSubmenu - - if depth < 2 { - Button(String(localized: "contextMenu.addChildWorkspace", defaultValue: "Add Child Workspace")) { - tabManager.addChildWorkspace(for: tab.id) - } - } - - Button(String(localized: "contextMenu.makeChild", defaultValue: "Make Child")) { - if tabManager.groupManager.indentWorkspace(tab.id) { - tabManager.items = tabManager.groupManager.items - } - } - .disabled(!canMakeChild) - - if depth > 0 { - Button(String(localized: "contextMenu.raiseLevel", defaultValue: "Raise Level")) { - if tabManager.groupManager.outdentWorkspace(tab.id) { - tabManager.items = tabManager.groupManager.items - } - } - } - - Divider() - - Button(String(localized: "contextMenu.moveUp", defaultValue: "Move Up")) { - moveBy(-1) - } - .disabled(index == 0) - - Button(String(localized: "contextMenu.moveDown", defaultValue: "Move Down")) { - moveBy(1) - } - .disabled(index >= tabManager.tabs.count - 1) - - Button(String(localized: "contextMenu.moveToTop", defaultValue: "Move to Top")) { - tabManager.moveTabsToTop(Set(targetIds)) - syncSelectionAfterMutation() - } - .disabled(targetIds.isEmpty) - - let referenceWindowId = AppDelegate.shared?.windowId(for: tabManager) - let windowMoveTargets = AppDelegate.shared?.windowMoveTargets(referenceWindowId: referenceWindowId) ?? [] - let moveMenuTitle = targetIds.count > 1 - ? String(localized: "contextMenu.moveWorkspacesToWindow", defaultValue: "Move Workspaces to Window") - : String(localized: "contextMenu.moveWorkspaceToWindow", defaultValue: "Move Workspace to Window") - Menu(moveMenuTitle) { - Button(String(localized: "contextMenu.newWindow", defaultValue: "New Window")) { - moveWorkspacesToNewWindow(targetIds) - } - .disabled(targetIds.isEmpty) - - if !windowMoveTargets.isEmpty { - Divider() - } - - ForEach(windowMoveTargets) { target in - Button(target.label) { - moveWorkspaces(targetIds, toWindow: target.windowId) - } - .disabled(target.isCurrentWindow || targetIds.isEmpty) - } - } - .disabled(targetIds.isEmpty) - - Divider() - - if let key = closeWorkspaceShortcut.keyEquivalent { - Button(closeLabel) { - closeTabs(targetIds, allowPinned: true) - } - .keyboardShortcut(key, modifiers: closeWorkspaceShortcut.eventModifiers) - .disabled(targetIds.isEmpty) - } else { - Button(closeLabel) { - closeTabs(targetIds, allowPinned: true) - } - .disabled(targetIds.isEmpty) - } - - Button(String(localized: "contextMenu.closeOtherWorkspaces", defaultValue: "Close Other Workspaces")) { - closeOtherTabs(targetIds) - } - .disabled(tabManager.tabs.count <= 1 || targetIds.count == tabManager.tabs.count) - - Button(String(localized: "contextMenu.closeWorkspacesBelow", defaultValue: "Close Workspaces Below")) { - closeTabsBelow(tabId: tab.id) - } - .disabled(index >= tabManager.tabs.count - 1) - - Button(String(localized: "contextMenu.closeWorkspacesAbove", defaultValue: "Close Workspaces Above")) { - closeTabsAbove(tabId: tab.id) - } - .disabled(index == 0) - - Divider() - - Button(markReadLabel) { - markTabsRead(targetIds) - } - .disabled(!hasUnreadNotifications(in: targetIds)) - - Button(markUnreadLabel) { - markTabsUnread(targetIds) - } - .disabled(!hasReadNotifications(in: targetIds)) - } private var backgroundColor: Color { switch activeTabIndicatorStyle { @@ -11748,14 +11460,6 @@ private struct TabItemView: View, Equatable { ) } - private func tabColorSwatchColor(for hex: String) -> NSColor { - WorkspaceTabColorSettings.displayNSColor( - hex: hex, - colorScheme: colorScheme, - forceBright: activeTabIndicatorStyle == .leftRail - ) ?? NSColor(hex: hex) ?? .gray - } - private var showsCenteredTopDropIndicator: Bool { guard draggedTabId != nil, let indicator = dropIndicator else { return false } if indicator.tabId == tab.id && indicator.edge == .top { @@ -11790,24 +11494,6 @@ private struct TabItemView: View, Equatable { return myParent?.id != nextParent?.id } - /// Whether this workspace can be nested under the sibling above it. - private var canMakeChild: Bool { - // Check depth constraint (max 3 levels) - let currentDepth = tabManager.groupManager.depthOf(workspaceId: tab.id) - guard currentDepth < 3 else { return false } - // Must have a sibling above at the same level to nest under - if currentDepth <= 1 { - // Top-level: check if there's a top-level item above this one - guard let idx = tabManager.groupManager.items.firstIndex(of: tab.id), - idx > 0 else { return false } - } else { - // Child: check if there's a sibling above in the parent's children - guard let parent = tabManager.groupManager.parentWorkspace(of: tab.id), - let idx = parent.childWorkspaceIds.firstIndex(of: tab.id), - idx > 0 else { return false } - } - return true - } private var accessibilityTitle: String { String(localized: "accessibility.workspacePosition", defaultValue: "\(tab.title), workspace \(index + 1) of \(accessibilityWorkspaceCount)") @@ -11868,67 +11554,6 @@ private struct TabItemView: View, Equatable { setSelectionToTabs() } - private func contextTargetIds() -> [UUID] { - let baseIds: Set = selectedTabIds.contains(tab.id) ? selectedTabIds : [tab.id] - return tabManager.tabs.compactMap { baseIds.contains($0.id) ? $0.id : nil } - } - - private func closeTabs(_ targetIds: [UUID], allowPinned: Bool) { - tabManager.closeWorkspacesWithConfirmation(targetIds, allowPinned: allowPinned) - syncSelectionAfterMutation() - } - - private func closeOtherTabs(_ targetIds: [UUID]) { - let keepIds = Set(targetIds) - let idsToClose = tabManager.tabs.compactMap { keepIds.contains($0.id) ? nil : $0.id } - closeTabs(idsToClose, allowPinned: false) - } - - private func closeTabsBelow(tabId: UUID) { - guard let anchorIndex = tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } - let idsToClose = tabManager.tabs.suffix(from: anchorIndex + 1).map { $0.id } - closeTabs(idsToClose, allowPinned: false) - } - - private func closeTabsAbove(tabId: UUID) { - guard let anchorIndex = tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } - let idsToClose = tabManager.tabs.prefix(upTo: anchorIndex).map { $0.id } - closeTabs(idsToClose, allowPinned: false) - } - - private func markTabsRead(_ targetIds: [UUID]) { - for id in targetIds { - notificationStore.markRead(forTabId: id) - } - } - - private func markTabsUnread(_ targetIds: [UUID]) { - for id in targetIds { - notificationStore.markUnread(forTabId: id) - } - } - - private func hasUnreadNotifications(in targetIds: [UUID]) -> Bool { - let targetSet = Set(targetIds) - return notificationStore.notifications.contains { targetSet.contains($0.tabId) && !$0.isRead } - } - - private func hasReadNotifications(in targetIds: [UUID]) -> Bool { - let targetSet = Set(targetIds) - return notificationStore.notifications.contains { targetSet.contains($0.tabId) && $0.isRead } - } - - private func syncSelectionAfterMutation() { - let existingIds = Set(tabManager.tabs.map { $0.id }) - selectedTabIds = selectedTabIds.filter { existingIds.contains($0) } - if selectedTabIds.isEmpty, let selectedId = tabManager.selectedTabId { - selectedTabIds = [selectedId] - } - if let selectedId = tabManager.selectedTabId { - lastSidebarSelectionIndex = tabManager.tabs.firstIndex { $0.id == selectedId } - } - } - private var remoteStateHelpText: String { let target = tab.remoteDisplayTarget ?? String( localized: "sidebar.remote.help.targetFallback", @@ -11985,46 +11610,6 @@ private struct TabItemView: View, Equatable { ) } } - private func moveWorkspaces(_ workspaceIds: [UUID], toWindow windowId: UUID) { - guard let app = AppDelegate.shared else { return } - let orderedWorkspaceIds = tabManager.tabs.compactMap { workspaceIds.contains($0.id) ? $0.id : nil } - guard !orderedWorkspaceIds.isEmpty else { return } - - for (index, workspaceId) in orderedWorkspaceIds.enumerated() { - let shouldFocus = index == orderedWorkspaceIds.count - 1 - _ = app.moveWorkspaceToWindow(workspaceId: workspaceId, windowId: windowId, focus: shouldFocus) - } - - selectedTabIds.subtract(orderedWorkspaceIds) - syncSelectionAfterMutation() - } - - private func moveWorkspacesToNewWindow(_ workspaceIds: [UUID]) { - guard let app = AppDelegate.shared else { return } - let orderedWorkspaceIds = tabManager.tabs.compactMap { workspaceIds.contains($0.id) ? $0.id : nil } - guard let firstWorkspaceId = orderedWorkspaceIds.first else { return } - - let shouldFocusImmediately = orderedWorkspaceIds.count == 1 - guard let newWindowId = app.moveWorkspaceToNewWindow(workspaceId: firstWorkspaceId, focus: shouldFocusImmediately) else { - return - } - - if orderedWorkspaceIds.count > 1 { - for workspaceId in orderedWorkspaceIds.dropFirst() { - _ = app.moveWorkspaceToWindow(workspaceId: workspaceId, windowId: newWindowId, focus: false) - } - if let finalWorkspaceId = orderedWorkspaceIds.last { - _ = app.moveWorkspaceToWindow(workspaceId: finalWorkspaceId, windowId: newWindowId, focus: true) - } - } - - selectedTabIds.subtract(orderedWorkspaceIds) - syncSelectionAfterMutation() - } - - // latestNotificationText is now passed as a parameter from the parent view - // to avoid subscribing to notificationStore changes in every TabItemView. - private func branchDirectoryRow( gitSummary: String?, directorySummary: String? @@ -12290,131 +11875,6 @@ private struct TabItemView: View, Equatable { .frame(width: Self.frameSize, height: Self.frameSize) } } - - private func applyTabColor(_ hex: String?, targetIds: [UUID]) { - for targetId in targetIds { - tabManager.setTabColor(tabId: targetId, color: hex) - } - } - - private func promptCustomColor(targetIds: [UUID]) { - let alert = NSAlert() - alert.messageText = String(localized: "alert.customColor.title", defaultValue: "Custom Workspace Color") - alert.informativeText = String(localized: "alert.customColor.message", defaultValue: "Enter a hex color in the format #RRGGBB.") - - let seed = tab.customColor ?? WorkspaceTabColorSettings.customColors().first ?? "" - let input = NSTextField(string: seed) - input.placeholderString = "#1565C0" - input.frame = NSRect(x: 0, y: 0, width: 240, height: 22) - alert.accessoryView = input - alert.addButton(withTitle: String(localized: "alert.customColor.apply", defaultValue: "Apply")) - alert.addButton(withTitle: String(localized: "alert.customColor.cancel", defaultValue: "Cancel")) - - let alertWindow = alert.window - alertWindow.initialFirstResponder = input - DispatchQueue.main.async { - alertWindow.makeFirstResponder(input) - input.selectText(nil) - } - - let response = alert.runModal() - guard response == .alertFirstButtonReturn else { return } - guard let normalized = WorkspaceTabColorSettings.addCustomColor(input.stringValue) else { - showInvalidColorAlert(input.stringValue) - return - } - applyTabColor(normalized, targetIds: targetIds) - } - - private func showInvalidColorAlert(_ value: String) { - let alert = NSAlert() - alert.alertStyle = .warning - alert.messageText = String(localized: "alert.invalidColor.title", defaultValue: "Invalid Color") - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty { - alert.informativeText = String(localized: "alert.invalidColor.emptyMessage", defaultValue: "Enter a hex color in the format #RRGGBB.") - } else { - alert.informativeText = String(localized: "alert.invalidColor.invalidMessage", defaultValue: "\"\(trimmed)\" is not a valid hex color. Use #RRGGBB.") - } - alert.addButton(withTitle: String(localized: "alert.invalidColor.ok", defaultValue: "OK")) - _ = alert.runModal() - } - - private func promptRename() { - let alert = NSAlert() - alert.messageText = String(localized: "alert.renameWorkspace.title", defaultValue: "Rename Workspace") - alert.informativeText = String(localized: "alert.renameWorkspace.message", defaultValue: "Enter a custom name for this workspace.") - let input = NSTextField(string: tab.customTitle ?? tab.title) - input.placeholderString = String(localized: "alert.renameWorkspace.placeholder", defaultValue: "Workspace name") - input.frame = NSRect(x: 0, y: 0, width: 240, height: 22) - alert.accessoryView = input - alert.addButton(withTitle: String(localized: "alert.renameWorkspace.rename", defaultValue: "Rename")) - alert.addButton(withTitle: String(localized: "alert.renameWorkspace.cancel", defaultValue: "Cancel")) - let alertWindow = alert.window - alertWindow.initialFirstResponder = input - DispatchQueue.main.async { - alertWindow.makeFirstResponder(input) - input.selectText(nil) - } - let response = alert.runModal() - guard response == .alertFirstButtonReturn else { return } - tabManager.setCustomTitle(tabId: tab.id, title: input.stringValue) - } - - @ViewBuilder - private var runScriptSubmenu: some View { - let isAtPrompt = tab.isFocusedPanelAtPrompt - let scripts = ScriptRepository.shared.listScripts() - Menu(String(localized: "contextMenu.runScript", defaultValue: "Run Script")) { - ForEach(scripts, id: \.self) { scriptName in - Button(scriptName) { - runScriptInTerminal(named: scriptName) - } - } - if !scripts.isEmpty { - Divider() - } - Button(String(localized: "contextMenu.openScriptsFolder", defaultValue: "Open Scripts Folder…")) { - NSWorkspace.shared.open(ScriptRepository.shared.directory) - } - } - .disabled(!isAtPrompt) - } - - private func runScriptInTerminal(named scriptName: String) { - guard let scriptContent = ScriptRepository.shared.getScript(named: scriptName), - let terminalPanel = tab.focusedTerminalPanel else { return } - let lines = StartupScriptRunner.prepareScriptLines(scriptContent) - guard !lines.isEmpty else { return } - let text = lines.joined(separator: "\n") + "\n" - terminalPanel.sendInteractiveText(text) - } - - @ViewBuilder - private var templatesSubmenu: some View { - let hasTerminal = tab.focusedTerminalPanel != nil - let templates = TemplateRepository.shared.listTemplates() - Menu(String(localized: "contextMenu.openTemplate", defaultValue: "Open Template")) { - ForEach(templates, id: \.self) { templateName in - Button(templateName) { - openTemplateInWorkspace(named: templateName) - } - } - if !templates.isEmpty { - Divider() - } - Button(String(localized: "contextMenu.openTemplatesFolder", defaultValue: "Open Templates Folder…")) { - NSWorkspace.shared.open(TemplateRepository.shared.directory) - } - } - .disabled(!hasTerminal) - } - - private func openTemplateInWorkspace(named templateName: String) { - guard let template = try? TemplateRepository.shared.getTemplate(named: templateName) else { return } - let directory = tab.currentDirectory - tabManager.openTemplate(template, directory: directory) - } } private struct SidebarMetadataRows: View { diff --git a/Sources/SidebarContextMenuActions.swift b/Sources/SidebarContextMenuActions.swift new file mode 100644 index 000000000000..e1f11d64c667 --- /dev/null +++ b/Sources/SidebarContextMenuActions.swift @@ -0,0 +1,186 @@ +import AppKit +import Bonsplit + +// MARK: - Action Methods & Helpers + +extension SidebarContextMenuController { + + // MARK: - Rename Dialog + + func promptRename() { + guard let workspace, let tabManager else { return } + let alert = NSAlert() + alert.messageText = String(localized: "alert.renameWorkspace.title", defaultValue: "Rename Workspace") + alert.informativeText = String(localized: "alert.renameWorkspace.message", defaultValue: "Enter a custom name for this workspace.") + let input = NSTextField(string: workspace.customTitle ?? workspace.title) + input.placeholderString = String(localized: "alert.renameWorkspace.placeholder", defaultValue: "Workspace name") + input.frame = NSRect(x: 0, y: 0, width: 240, height: 22) + alert.accessoryView = input + alert.addButton(withTitle: String(localized: "alert.renameWorkspace.rename", defaultValue: "Rename")) + alert.addButton(withTitle: String(localized: "alert.renameWorkspace.cancel", defaultValue: "Cancel")) + let alertWindow = alert.window + alertWindow.initialFirstResponder = input + DispatchQueue.main.async { + alertWindow.makeFirstResponder(input) + input.selectText(nil) + } + let response = alert.runModal() + guard response == .alertFirstButtonReturn else { return } + tabManager.setCustomTitle(tabId: workspace.id, title: input.stringValue) + } + + // MARK: - Custom Color Dialog + + func promptCustomColor(targetIds: [UUID]) { + guard let workspace, let tabManager else { return } + let alert = NSAlert() + alert.messageText = String(localized: "alert.customColor.title", defaultValue: "Custom Workspace Color") + alert.informativeText = String(localized: "alert.customColor.message", defaultValue: "Enter a hex color in the format #RRGGBB.") + let seed = workspace.customColor ?? WorkspaceTabColorSettings.customColors().first ?? "" + let input = NSTextField(string: seed) + input.placeholderString = "#1565C0" + input.frame = NSRect(x: 0, y: 0, width: 240, height: 22) + alert.accessoryView = input + alert.addButton(withTitle: String(localized: "alert.customColor.apply", defaultValue: "Apply")) + alert.addButton(withTitle: String(localized: "alert.customColor.cancel", defaultValue: "Cancel")) + let alertWindow = alert.window + alertWindow.initialFirstResponder = input + DispatchQueue.main.async { + alertWindow.makeFirstResponder(input) + input.selectText(nil) + } + let response = alert.runModal() + guard response == .alertFirstButtonReturn else { return } + guard let normalized = WorkspaceTabColorSettings.addCustomColor(input.stringValue) else { + showInvalidColorAlert(input.stringValue) + return + } + for id in targetIds { tabManager.setTabColor(tabId: id, color: normalized) } + } + + private func showInvalidColorAlert(_ value: String) { + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = String(localized: "alert.invalidColor.title", defaultValue: "Invalid Color") + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + alert.informativeText = String(localized: "alert.invalidColor.emptyMessage", defaultValue: "Enter a hex color in the format #RRGGBB.") + } else { + alert.informativeText = String(localized: "alert.invalidColor.invalidMessage", defaultValue: "\"\(trimmed)\" is not a valid hex color. Use #RRGGBB.") + } + alert.addButton(withTitle: String(localized: "alert.invalidColor.ok", defaultValue: "OK")) + _ = alert.runModal() + } + + // MARK: - Move Helpers + + func moveBy(_ delta: Int) { + guard let workspace, let tabManager else { return } + let targetIndex = index + delta + guard targetIndex >= 0, targetIndex < tabManager.tabs.count else { return } + guard tabManager.reorderWorkspace(tabId: workspace.id, toIndex: targetIndex) else { return } + writeSelectedTabIds([workspace.id]) + writeLastSidebarSelectionIndex(tabManager.tabs.firstIndex { $0.id == workspace.id }) + tabManager.selectTab(workspace) + setSelectionToTabs?() + } + + func moveWorkspacesToNewWindow(_ workspaceIds: [UUID]) { + guard let app = AppDelegate.shared, let tabManager else { return } + let ordered = tabManager.tabs.compactMap { workspaceIds.contains($0.id) ? $0.id : nil } + guard let firstId = ordered.first else { return } + let focusNow = ordered.count == 1 + guard let newWindowId = app.moveWorkspaceToNewWindow(workspaceId: firstId, focus: focusNow) else { return } + if ordered.count > 1 { + for id in ordered.dropFirst() { + _ = app.moveWorkspaceToWindow(workspaceId: id, windowId: newWindowId, focus: false) + } + if let lastId = ordered.last { + _ = app.moveWorkspaceToWindow(workspaceId: lastId, windowId: newWindowId, focus: true) + } + } + var sel = readSelectedTabIds() + sel.subtract(ordered) + writeSelectedTabIds(sel) + syncSelectionAfterMutation() + } + + func moveWorkspaces(_ workspaceIds: [UUID], toWindow windowId: UUID) { + guard let app = AppDelegate.shared, let tabManager else { return } + let ordered = tabManager.tabs.compactMap { workspaceIds.contains($0.id) ? $0.id : nil } + for (i, id) in ordered.enumerated() { + _ = app.moveWorkspaceToWindow(workspaceId: id, windowId: windowId, focus: i == ordered.count - 1) + } + var sel = readSelectedTabIds() + sel.subtract(ordered) + writeSelectedTabIds(sel) + syncSelectionAfterMutation() + } + + // MARK: - Selection Sync + + func syncSelectionAfterMutation() { + guard let tabManager else { return } + let existingIds = Set(tabManager.tabs.map(\.id)) + var sel = readSelectedTabIds().filter { existingIds.contains($0) } + if sel.isEmpty, let selectedId = tabManager.selectedTabId { + sel = [selectedId] + } + writeSelectedTabIds(sel) + if let selectedId = tabManager.selectedTabId { + writeLastSidebarSelectionIndex(tabManager.tabs.firstIndex { $0.id == selectedId }) + } + } + + // MARK: - Hierarchy Check + + func computeCanMakeChild() -> Bool { + guard let workspace, let tabManager else { return false } + let currentDepth = tabManager.groupManager.depthOf(workspaceId: workspace.id) + guard currentDepth < 3 else { return false } + if currentDepth <= 1 { + guard let idx = tabManager.groupManager.items.firstIndex(of: workspace.id), + idx > 0 else { return false } + } else { + guard let parent = tabManager.groupManager.parentWorkspace(of: workspace.id), + let idx = parent.childWorkspaceIds.firstIndex(of: workspace.id), + idx > 0 else { return false } + } + return true + } + + // MARK: - SSH Error + + func copyableSSHError(for workspace: Workspace) -> String? { + let fallbackTarget = workspace.remoteDisplayTarget ?? String( + localized: "sidebar.remote.help.targetFallback", defaultValue: "remote host") + let trimmedDetail = workspace.remoteConnectionDetail?.trimmingCharacters(in: .whitespacesAndNewlines) + if workspace.remoteConnectionState == .error, let trimmedDetail, !trimmedDetail.isEmpty { + let entry = SidebarRemoteErrorCopyEntry( + workspaceTitle: workspace.title, target: fallbackTarget, detail: trimmedDetail) + return SidebarRemoteErrorCopySupport.clipboardText(for: [entry]) + } + if let statusValue = workspace.statusEntries["remote.error"]?.value + .trimmingCharacters(in: .whitespacesAndNewlines), + !statusValue.isEmpty { + let entry = SidebarRemoteErrorCopyEntry( + workspaceTitle: workspace.title, target: fallbackTarget, detail: statusValue) + return SidebarRemoteErrorCopySupport.clipboardText(for: [entry]) + } + return nil + } + + // MARK: - Color Swatch + + func colorSwatchImage(hex: String) -> NSImage { + let color = NSColor(hex: hex) ?? .gray + let size = NSSize(width: 14, height: 14) + let image = NSImage(size: size, flipped: false) { rect in + color.setFill() + NSBezierPath(ovalIn: rect.insetBy(dx: 1, dy: 1)).fill() + return true + } + image.isTemplate = false + return image + } +} diff --git a/Sources/SidebarContextMenuController.swift b/Sources/SidebarContextMenuController.swift new file mode 100644 index 000000000000..51ae4e82c1b7 --- /dev/null +++ b/Sources/SidebarContextMenuController.swift @@ -0,0 +1,421 @@ +import AppKit +import Bonsplit +import SwiftUI + +/// NSMenuItem subclass that routes actions through a closure. +private final class ActionMenuItem: NSMenuItem { + private var handler: (() -> Void)? + + convenience init(_ title: String, isEnabled: Bool = true, handler: @escaping () -> Void) { + self.init(title: title, action: #selector(performAction), keyEquivalent: "") + self.handler = handler + self.target = self + self.isEnabled = isEnabled + } + + @objc private func performAction() { + handler?() + } +} + +/// Builds the workspace sidebar context menu at right-click time via NSMenuDelegate. +/// Menu items are constructed in menuNeedsUpdate(_:) and remain static while open, +/// fully decoupled from the SwiftUI rendering pipeline. +@MainActor +final class SidebarContextMenuController: NSObject, NSMenuDelegate { + var workspace: Workspace? + var tabManager: TabManager? + var notificationStore: TerminalNotificationStore? + var index: Int = 0 + var depth: Int = 0 + var readSelectedTabIds: () -> Set = { [] } + var writeSelectedTabIds: (Set) -> Void = { _ in } + var readLastSidebarSelectionIndex: () -> Int? = { nil } + var writeLastSidebarSelectionIndex: (Int?) -> Void = { _ in } + var setSelectionToTabs: (() -> Void)? + + // MARK: - NSMenuDelegate + + nonisolated func menuNeedsUpdate(_ menu: NSMenu) { + MainActor.assumeIsolated { + populateMenu(menu) + } + } + + private func populateMenu(_ menu: NSMenu) { + menu.removeAllItems() + guard let workspace, let tabManager else { return } +#if DEBUG + dlog("contextMenu.menuNeedsUpdate workspace=\(workspace.id.uuidString.prefix(5))") +#endif + let targetIds = contextTargetIds() + let isMulti = targetIds.count > 1 + + addPinItem(to: menu, targetIds: targetIds, isMulti: isMulti) + addRenameItems(to: menu) + addRemoteItems(to: menu, targetIds: targetIds, isMulti: isMulti) + addColorSubmenu(to: menu, targetIds: targetIds) + addCopySSHErrorItem(to: menu) + menu.addItem(.separator()) + addScriptSubmenu(to: menu) + addTemplateSubmenu(to: menu) + addHierarchyItems(to: menu) + menu.addItem(.separator()) + addMoveItems(to: menu, targetIds: targetIds, isMulti: isMulti) + menu.addItem(.separator()) + addCloseItems(to: menu, targetIds: targetIds, isMulti: isMulti) + menu.addItem(.separator()) + addNotificationItems(to: menu, targetIds: targetIds, isMulti: isMulti) + } + + // MARK: - Target Resolution + + private func contextTargetIds() -> [UUID] { + guard let tabManager, let workspace else { return [] } + let selectedIds = readSelectedTabIds() + let baseIds: Set = selectedIds.contains(workspace.id) ? selectedIds : [workspace.id] + return tabManager.tabs.compactMap { baseIds.contains($0.id) ? $0.id : nil } + } + + private func label(multi: String, single: String, isMulti: Bool) -> String { + isMulti ? multi : single + } + + // MARK: - Pin + + private func addPinItem(to menu: NSMenu, targetIds: [UUID], isMulti: Bool) { + guard let workspace, let tabManager else { return } + let shouldPin = !workspace.isPinned + let title = shouldPin + ? label( + multi: String(localized: "contextMenu.pinWorkspaces", defaultValue: "Pin Workspaces"), + single: String(localized: "contextMenu.pinWorkspace", defaultValue: "Pin Workspace"), + isMulti: isMulti) + : label( + multi: String(localized: "contextMenu.unpinWorkspaces", defaultValue: "Unpin Workspaces"), + single: String(localized: "contextMenu.unpinWorkspace", defaultValue: "Unpin Workspace"), + isMulti: isMulti) + menu.addItem(ActionMenuItem(title) { [weak self, weak tabManager] in + guard let self, let tabManager else { return } + for id in targetIds { + if let tab = tabManager.tabs.first(where: { $0.id == id }) { + tabManager.setPinned(tab, pinned: shouldPin) + } + } + self.syncSelectionAfterMutation() + }) + } + + // MARK: - Rename + + private func addRenameItems(to menu: NSMenu) { + guard let workspace else { return } + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.renameWorkspace", defaultValue: "Rename Workspace…") + ) { [weak self] in + self?.promptRename() + }) + if workspace.hasCustomTitle { + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.removeCustomWorkspaceName", defaultValue: "Remove Custom Workspace Name") + ) { [weak self] in + self?.tabManager?.clearCustomTitle(tabId: workspace.id) + }) + } + } + + // MARK: - Remote + + private func addRemoteItems(to menu: NSMenu, targetIds: [UUID], isMulti: Bool) { + guard let tabManager else { return } + let remoteTargets = tabManager.tabs.filter { targetIds.contains($0.id) && $0.isRemoteWorkspace } + guard !remoteTargets.isEmpty else { return } + menu.addItem(.separator()) + let allConnecting = remoteTargets.allSatisfy { $0.remoteConnectionState == .connecting } + let allDisconnected = remoteTargets.allSatisfy { $0.remoteConnectionState == .disconnected } + menu.addItem(ActionMenuItem( + label( + multi: String(localized: "contextMenu.reconnectWorkspaces", defaultValue: "Reconnect Workspaces"), + single: String(localized: "contextMenu.reconnectWorkspace", defaultValue: "Reconnect Workspace"), + isMulti: isMulti), + isEnabled: !allConnecting + ) { + for workspace in remoteTargets { workspace.reconnectRemoteConnection() } + }) + menu.addItem(ActionMenuItem( + label( + multi: String(localized: "contextMenu.disconnectWorkspaces", defaultValue: "Disconnect Workspaces"), + single: String(localized: "contextMenu.disconnectWorkspace", defaultValue: "Disconnect Workspace"), + isMulti: isMulti), + isEnabled: !allDisconnected + ) { + for workspace in remoteTargets { workspace.disconnectRemoteConnection(clearConfiguration: false) } + }) + } + + // MARK: - Color Submenu + + private func addColorSubmenu(to menu: NSMenu, targetIds: [UUID]) { + guard let workspace, let tabManager else { return } + let colorMenu = NSMenu() + let parentItem = NSMenuItem(title: String(localized: "contextMenu.workspaceColor", defaultValue: "Workspace Color"), action: nil, keyEquivalent: "") + parentItem.submenu = colorMenu + + if workspace.customColor != nil { + colorMenu.addItem(ActionMenuItem( + String(localized: "contextMenu.clearColor", defaultValue: "Clear Color") + ) { [weak tabManager] in + for id in targetIds { tabManager?.setTabColor(tabId: id, color: nil) } + }) + } + colorMenu.addItem(ActionMenuItem( + String(localized: "contextMenu.chooseCustomColor", defaultValue: "Choose Custom Color…") + ) { [weak self] in + self?.promptCustomColor(targetIds: targetIds) + }) + + let palette = WorkspaceTabColorSettings.palette() + if !palette.isEmpty { colorMenu.addItem(.separator()) } + for entry in palette { + let item = ActionMenuItem(entry.name) { [weak tabManager] in + for id in targetIds { tabManager?.setTabColor(tabId: id, color: entry.hex) } + } + item.image = colorSwatchImage(hex: entry.hex) + colorMenu.addItem(item) + } + menu.addItem(parentItem) + } + + // MARK: - SSH Error + + private func addCopySSHErrorItem(to menu: NSMenu) { + guard let workspace else { return } + guard let errorText = copyableSSHError(for: workspace) else { return } + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.copySshError", defaultValue: "Copy SSH Error") + ) { + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + pasteboard.setString(errorText, forType: .string) + }) + } + + // MARK: - Script Submenu + + private func addScriptSubmenu(to menu: NSMenu) { + guard let workspace else { return } + let scriptMenu = NSMenu() + let parentItem = NSMenuItem( + title: String(localized: "contextMenu.runScript", defaultValue: "Run Script"), + action: nil, keyEquivalent: "") + parentItem.submenu = scriptMenu + + let isAtPrompt = workspace.isFocusedPanelAtPrompt + let scripts = ScriptRepository.shared.listScripts() + for scriptName in scripts { + scriptMenu.addItem(ActionMenuItem(scriptName, isEnabled: isAtPrompt) { [weak workspace] in + guard let workspace, + let content = ScriptRepository.shared.getScript(named: scriptName), + let terminal = workspace.focusedTerminalPanel else { return } + let lines = StartupScriptRunner.prepareScriptLines(content) + guard !lines.isEmpty else { return } + terminal.sendInteractiveText(lines.joined(separator: "\n") + "\n") + }) + } + if !scripts.isEmpty { scriptMenu.addItem(.separator()) } + scriptMenu.addItem(ActionMenuItem( + String(localized: "contextMenu.openScriptsFolder", defaultValue: "Open Scripts Folder…") + ) { + NSWorkspace.shared.open(ScriptRepository.shared.directory) + }) + menu.addItem(parentItem) + } + + // MARK: - Template Submenu + + private func addTemplateSubmenu(to menu: NSMenu) { + guard let workspace, let tabManager else { return } + let templateMenu = NSMenu() + let parentItem = NSMenuItem( + title: String(localized: "contextMenu.openTemplate", defaultValue: "Open Template"), + action: nil, keyEquivalent: "") + parentItem.submenu = templateMenu + + let hasTerminal = workspace.focusedTerminalPanel != nil + let templates = TemplateRepository.shared.listTemplates() + for templateName in templates { + templateMenu.addItem(ActionMenuItem(templateName, isEnabled: hasTerminal) { [weak workspace, weak tabManager] in + guard let workspace, let tabManager, + let template = try? TemplateRepository.shared.getTemplate(named: templateName) else { return } + tabManager.openTemplate(template, directory: workspace.currentDirectory) + }) + } + if !templates.isEmpty { templateMenu.addItem(.separator()) } + templateMenu.addItem(ActionMenuItem( + String(localized: "contextMenu.openTemplatesFolder", defaultValue: "Open Templates Folder…") + ) { + NSWorkspace.shared.open(TemplateRepository.shared.directory) + }) + menu.addItem(parentItem) + } + + // MARK: - Hierarchy + + private func addHierarchyItems(to menu: NSMenu) { + guard let workspace, let tabManager else { return } + if depth < 2 { + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.addChildWorkspace", defaultValue: "Add Child Workspace") + ) { [weak tabManager] in + tabManager?.addChildWorkspace(for: workspace.id) + }) + } + let canMakeChild = computeCanMakeChild() + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.makeChild", defaultValue: "Make Child"), + isEnabled: canMakeChild + ) { [weak tabManager] in + guard let tabManager else { return } + if tabManager.groupManager.indentWorkspace(workspace.id) { + tabManager.items = tabManager.groupManager.items + } + }) + if depth > 0 { + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.raiseLevel", defaultValue: "Raise Level") + ) { [weak tabManager] in + guard let tabManager else { return } + if tabManager.groupManager.outdentWorkspace(workspace.id) { + tabManager.items = tabManager.groupManager.items + } + }) + } + } + + // MARK: - Move + + private func addMoveItems(to menu: NSMenu, targetIds: [UUID], isMulti: Bool) { + guard let workspace, let tabManager else { return } + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.moveUp", defaultValue: "Move Up"), + isEnabled: index > 0 + ) { [weak self] in + self?.moveBy(-1) + }) + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.moveDown", defaultValue: "Move Down"), + isEnabled: index < tabManager.tabs.count - 1 + ) { [weak self] in + self?.moveBy(1) + }) + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.moveToTop", defaultValue: "Move to Top"), + isEnabled: !targetIds.isEmpty + ) { [weak self, weak tabManager] in + guard let self, let tabManager else { return } + tabManager.moveTabsToTop(Set(targetIds)) + self.syncSelectionAfterMutation() + }) + + // Move to Window submenu + let windowMenu = NSMenu() + let moveTitle = label( + multi: String(localized: "contextMenu.moveWorkspacesToWindow", defaultValue: "Move Workspaces to Window"), + single: String(localized: "contextMenu.moveWorkspaceToWindow", defaultValue: "Move Workspace to Window"), + isMulti: isMulti) + let moveParent = NSMenuItem(title: moveTitle, action: nil, keyEquivalent: "") + moveParent.submenu = windowMenu + moveParent.isEnabled = !targetIds.isEmpty + + windowMenu.addItem(ActionMenuItem( + String(localized: "contextMenu.newWindow", defaultValue: "New Window"), + isEnabled: !targetIds.isEmpty + ) { [weak self] in + self?.moveWorkspacesToNewWindow(targetIds) + }) + let referenceWindowId = AppDelegate.shared?.windowId(for: tabManager) + let windowTargets = AppDelegate.shared?.windowMoveTargets(referenceWindowId: referenceWindowId) ?? [] + if !windowTargets.isEmpty { windowMenu.addItem(.separator()) } + for target in windowTargets { + windowMenu.addItem(ActionMenuItem( + target.label, + isEnabled: !target.isCurrentWindow && !targetIds.isEmpty + ) { [weak self] in + self?.moveWorkspaces(targetIds, toWindow: target.windowId) + }) + } + menu.addItem(moveParent) + } + + // MARK: - Close + + private func addCloseItems(to menu: NSMenu, targetIds: [UUID], isMulti: Bool) { + guard let workspace, let tabManager else { return } + let closeTitle = label( + multi: String(localized: "contextMenu.closeWorkspaces", defaultValue: "Close Workspaces"), + single: String(localized: "contextMenu.closeWorkspace", defaultValue: "Close Workspace"), + isMulti: isMulti) + menu.addItem(ActionMenuItem(closeTitle, isEnabled: !targetIds.isEmpty) { [weak self, weak tabManager] in + guard let self, let tabManager else { return } + tabManager.closeWorkspacesWithConfirmation(targetIds, allowPinned: true) + self.syncSelectionAfterMutation() + }) + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.closeOtherWorkspaces", defaultValue: "Close Other Workspaces"), + isEnabled: tabManager.tabs.count > 1 && targetIds.count < tabManager.tabs.count + ) { [weak self, weak tabManager] in + guard let self, let tabManager else { return } + let keepIds = Set(targetIds) + let idsToClose = tabManager.tabs.compactMap { keepIds.contains($0.id) ? nil : $0.id } + tabManager.closeWorkspacesWithConfirmation(idsToClose, allowPinned: false) + self.syncSelectionAfterMutation() + }) + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.closeWorkspacesBelow", defaultValue: "Close Workspaces Below"), + isEnabled: index < tabManager.tabs.count - 1 + ) { [weak self, weak tabManager] in + guard let self, let tabManager else { return } + guard let anchor = tabManager.tabs.firstIndex(where: { $0.id == workspace.id }) else { return } + let ids = tabManager.tabs.suffix(from: anchor + 1).map(\.id) + tabManager.closeWorkspacesWithConfirmation(ids, allowPinned: false) + self.syncSelectionAfterMutation() + }) + menu.addItem(ActionMenuItem( + String(localized: "contextMenu.closeWorkspacesAbove", defaultValue: "Close Workspaces Above"), + isEnabled: index > 0 + ) { [weak self, weak tabManager] in + guard let self, let tabManager else { return } + guard let anchor = tabManager.tabs.firstIndex(where: { $0.id == workspace.id }) else { return } + let ids = tabManager.tabs.prefix(upTo: anchor).map(\.id) + tabManager.closeWorkspacesWithConfirmation(ids, allowPinned: false) + self.syncSelectionAfterMutation() + }) + } + + // MARK: - Notifications + + private func addNotificationItems(to menu: NSMenu, targetIds: [UUID], isMulti: Bool) { + guard let notificationStore else { return } + let targetSet = Set(targetIds) + let hasUnread = notificationStore.notifications.contains { targetSet.contains($0.tabId) && !$0.isRead } + let hasRead = notificationStore.notifications.contains { targetSet.contains($0.tabId) && $0.isRead } + menu.addItem(ActionMenuItem( + label( + multi: String(localized: "contextMenu.markWorkspacesRead", defaultValue: "Mark Workspaces as Read"), + single: String(localized: "contextMenu.markWorkspaceRead", defaultValue: "Mark Workspace as Read"), + isMulti: isMulti), + isEnabled: hasUnread + ) { [weak notificationStore] in + for id in targetIds { notificationStore?.markRead(forTabId: id) } + }) + menu.addItem(ActionMenuItem( + label( + multi: String(localized: "contextMenu.markWorkspacesUnread", defaultValue: "Mark Workspaces as Unread"), + single: String(localized: "contextMenu.markWorkspaceUnread", defaultValue: "Mark Workspace as Unread"), + isMulti: isMulti), + isEnabled: hasRead + ) { [weak notificationStore] in + for id in targetIds { notificationStore?.markUnread(forTabId: id) } + }) + } +} diff --git a/Sources/SidebarContextMenuHost.swift b/Sources/SidebarContextMenuHost.swift new file mode 100644 index 000000000000..8b64c3cc2eff --- /dev/null +++ b/Sources/SidebarContextMenuHost.swift @@ -0,0 +1,64 @@ +import AppKit +import Bonsplit +import SwiftUI + +/// Transparent overlay that intercepts right-clicks to show an AppKit context menu. +/// The underlying NSView is created once and never replaced by SwiftUI updates. +private final class SidebarContextMenuPassthroughView: NSView { + override var isFlipped: Bool { true } + + override func hitTest(_ point: NSPoint) -> NSView? { + // Only intercept right-click events for context menu display. + // All other events pass through to the SwiftUI content below. + guard let event = NSApp.currentEvent, + event.type == .rightMouseDown else { + return nil + } + return bounds.contains(point) ? self : nil + } +} + +/// NSViewRepresentable that installs a stable AppKit NSMenu on a sidebar row. +/// Menu content is built at right-click time via NSMenuDelegate, not during +/// SwiftUI rendering. This decouples the menu from the observation pipeline. +struct SidebarContextMenuHost: NSViewRepresentable { + let workspace: Workspace + let tabManager: TabManager + let notificationStore: TerminalNotificationStore + @Binding var selectedTabIds: Set + @Binding var lastSidebarSelectionIndex: Int? + let setSelectionToTabs: () -> Void + let index: Int + let depth: Int + + func makeCoordinator() -> SidebarContextMenuController { + SidebarContextMenuController() + } + + func makeNSView(context: Context) -> NSView { + let view = SidebarContextMenuPassthroughView() + let menu = NSMenu() + menu.delegate = context.coordinator + view.menu = menu +#if DEBUG + dlog("contextMenu.host.makeNSView workspace=\(workspace.id.uuidString.prefix(5))") +#endif + return view + } + + func updateNSView(_ nsView: NSView, context: Context) { + let coord = context.coordinator + coord.workspace = workspace + coord.tabManager = tabManager + coord.notificationStore = notificationStore + coord.index = index + coord.depth = depth + let selBinding = $selectedTabIds + coord.readSelectedTabIds = { selBinding.wrappedValue } + coord.writeSelectedTabIds = { selBinding.wrappedValue = $0 } + let idxBinding = $lastSidebarSelectionIndex + coord.readLastSidebarSelectionIndex = { idxBinding.wrappedValue } + coord.writeLastSidebarSelectionIndex = { idxBinding.wrappedValue = $0 } + coord.setSelectionToTabs = setSelectionToTabs + } +}