diff --git a/Sources/GhosttyTerminalView.swift b/Sources/GhosttyTerminalView.swift index 2e6fcd46e7d9..6f8961a7e64e 100644 --- a/Sources/GhosttyTerminalView.swift +++ b/Sources/GhosttyTerminalView.swift @@ -4438,8 +4438,9 @@ final class TerminalSurface: Identifiable, ObservableObject { var isViewInWindow: Bool { hostedView.window != nil } let id: UUID private(set) var tabId: UUID - /// Port ordinal for CMUX_PORT range assignment - var portOrdinal: Int = 0 + /// Port ordinal for CMUX_PORT range assignment. Captured at construction so + /// every runtime startup path uses the same immutable workspace port range. + private let portOrdinal: Int /// Snapshotted once per app session so all workspaces use consistent values private static let sessionPortBase: Int = { let val = UserDefaults.standard.integer(forKey: AutomationSettings.portBaseKey) @@ -4474,6 +4475,7 @@ final class TerminalSurface: Identifiable, ObservableObject { private var pendingSocketInputBytes: Int = 0 private let maxPendingSocketInputBytes = 1_048_576 private var backgroundSurfaceStartQueued = false + private var queuedBackgroundSurfaceStartAllowsOffWindow = false private var surfaceCallbackContext: Unmanaged? /// The desired focus state for the Ghostty C surface. May be set before the /// C surface exists (e.g. during layout restoration); `createSurface` @@ -4550,6 +4552,7 @@ final class TerminalSurface: Identifiable, ObservableObject { context: ghostty_surface_context_e, configTemplate: CmuxSurfaceConfigTemplate?, workingDirectory: String? = nil, + portOrdinal: Int = 0, initialCommand: String? = nil, tmuxStartCommand: String? = nil, initialInput: String? = nil, @@ -4566,6 +4569,7 @@ final class TerminalSurface: Identifiable, ObservableObject { self.surfaceContext = context self.configTemplate = configTemplate self.workingDirectory = workingDirectory?.trimmingCharacters(in: .whitespacesAndNewlines) + self.portOrdinal = portOrdinal let trimmedCommand = initialCommand?.trimmingCharacters(in: .whitespacesAndNewlines) self.initialCommand = (trimmedCommand?.isEmpty == false) ? trimmedCommand : nil let trimmedTmuxStartCommand = tmuxStartCommand?.trimmingCharacters(in: .whitespacesAndNewlines) @@ -4581,9 +4585,11 @@ final class TerminalSurface: Identifiable, ObservableObject { let view = GhosttyNSView(frame: NSRect(x: 0, y: 0, width: 800, height: 600)) self.surfaceView = view self.hostedView = GhosttySurfaceScrollView(surfaceView: view) - // Surface is created when attached to a view - hostedView.attachSurface(self) TerminalSurfaceRegistry.shared.register(self) + // Attach records the concrete GhosttyNSView immediately. Visual mounts + // still wait for a backing window, while explicit runtime requests from + // the socket/control plane may start from this attached view off-window. + hostedView.attachSurface(self) } func updateWorkspaceId(_ newTabId: UUID) { @@ -5040,8 +5046,11 @@ final class TerminalSurface: Identifiable, ObservableObject { attachedView = view - // If surface doesn't exist yet, create it once the view is in a real window so - // content scale and pixel geometry are derived from the actual backing context. + // The ordinary visual lifecycle remains lazy until this view has a real + // window so model-only panels, unit tests, and restored-but-unpresented + // workspaces do not spawn PTYs just by constructing TerminalPanel objects. + // Control-plane callers use requestBackgroundSurfaceStartIfNeeded() below, + // which can start the runtime off-window once an attachedView exists. if surface == nil { guard allowsRuntimeSurfaceCreation() else { #if DEBUG @@ -5062,7 +5071,10 @@ final class TerminalSurface: Identifiable, ObservableObject { return } #if DEBUG - cmuxDebugLog("surface.attach.create surface=\(id.uuidString.prefix(5))") + cmuxDebugLog( + "surface.attach.create surface=\(id.uuidString.prefix(5)) " + + "inWindow=\(view.window != nil ? 1 : 0)" + ) #endif createSurface(for: view) #if DEBUG @@ -5672,25 +5684,33 @@ final class TerminalSurface: Identifiable, ObservableObject { _ = ghostty_surface_key(surface, keyEvent) } - func requestBackgroundSurfaceStartIfNeeded() { + // Socket/API operations are an explicit runtime demand: they must be able to + // start a terminal in a background workspace without selecting that workspace. + // Ghostty can create from the attached NSView while it is off-window; geometry + // and display id are reconciled later when the view is presented. + func requestBackgroundSurfaceStartIfNeeded(allowOffWindow: Bool = false) { if !Thread.isMainThread { DispatchQueue.main.async { [weak self] in - self?.requestBackgroundSurfaceStartIfNeeded() + self?.requestBackgroundSurfaceStartIfNeeded(allowOffWindow: allowOffWindow) } return } guard allowsRuntimeSurfaceCreation() else { return } guard surface == nil, attachedView != nil else { return } + queuedBackgroundSurfaceStartAllowsOffWindow = + queuedBackgroundSurfaceStartAllowsOffWindow || allowOffWindow guard !backgroundSurfaceStartQueued else { return } backgroundSurfaceStartQueued = true DispatchQueue.main.async { [weak self] in guard let self else { return } + let allowOffWindow = self.queuedBackgroundSurfaceStartAllowsOffWindow + self.queuedBackgroundSurfaceStartAllowsOffWindow = false self.backgroundSurfaceStartQueued = false guard self.allowsRuntimeSurfaceCreation() else { return } guard self.surface == nil, let view = self.attachedView else { return } - guard view.window != nil else { + guard allowOffWindow || view.window != nil else { #if DEBUG cmuxDebugLog( "surface.background_start.defer surface=\(self.id.uuidString.prefix(8)) reason=noWindow" diff --git a/Sources/Panels/TerminalPanel.swift b/Sources/Panels/TerminalPanel.swift index 7ca080d0f53d..937c0d949065 100644 --- a/Sources/Panels/TerminalPanel.swift +++ b/Sources/Panels/TerminalPanel.swift @@ -105,6 +105,7 @@ final class TerminalPanel: Panel, ObservableObject { context: context, configTemplate: configTemplate, workingDirectory: workingDirectory, + portOrdinal: portOrdinal, initialCommand: initialCommand, tmuxStartCommand: tmuxStartCommand, initialInput: initialInput, @@ -112,7 +113,6 @@ final class TerminalPanel: Panel, ObservableObject { additionalEnvironment: additionalEnvironment, focusPlacement: focusPlacement ) - surface.portOrdinal = portOrdinal self.init(workspaceId: workspaceId, surface: surface) } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 76013d29eb0b..fcec2be3fb2f 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1212,6 +1212,7 @@ extension Workspace { } } pendingTerminalInputObserversByPanelId[panelId, default: []].append(registration) + panel.surface.requestBackgroundSurfaceStartIfNeeded(allowOffWindow: true) guard let timeout else { return } DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self, registration] in @@ -8462,7 +8463,11 @@ final class Workspace: Identifiable, ObservableObject { return panels[panelId] as? TerminalPanel } } - func requestBackgroundPrimeTerminalSurfaceStartIfNeeded() { backgroundPrimeTerminalPanels.forEach { $0.surface.requestBackgroundSurfaceStartIfNeeded() } } + func requestBackgroundPrimeTerminalSurfaceStartIfNeeded() { + backgroundPrimeTerminalPanels.forEach { + $0.surface.requestBackgroundSurfaceStartIfNeeded(allowOffWindow: true) + } + } func hasLoadedBackgroundPrimeTerminalSurface() -> Bool { backgroundPrimeTerminalPanels.allSatisfy { $0.surface.surface != nil } } @discardableResult func preloadTerminalPanelForDebugStress( diff --git a/tests_v2/test_cli_new_workspace_command_queue.py b/tests_v2/test_cli_new_workspace_command_queue.py index 9b19443d3d7e..91dec9f52adf 100644 --- a/tests_v2/test_cli_new_workspace_command_queue.py +++ b/tests_v2/test_cli_new_workspace_command_queue.py @@ -23,6 +23,17 @@ def _must(cond: bool, msg: str) -> None: raise cmuxError(msg) +def _float_env(name: str, default: float) -> float: + raw = os.environ.get(name) + if not raw: + return default + try: + value = float(raw) + except ValueError: + return default + return value if value > 0 else default + + def _find_cli_binary() -> str: env_cli = os.environ.get("CMUXTERM_CLI") if env_cli and os.path.isfile(env_cli) and os.access(env_cli, os.X_OK): @@ -47,14 +58,21 @@ def _run_cli(cli: str, args: list[str]) -> tuple[subprocess.CompletedProcess[str env.pop("CMUX_SURFACE_ID", None) env.pop("CMUX_TAB_ID", None) + command = [cli, "--socket", SOCKET_PATH, *args] + timeout = _float_env("CMUX_TEST_CLI_RUN_TIMEOUT", 30.0) started = time.monotonic() - proc = subprocess.run( - [cli, "--socket", SOCKET_PATH] + args, - capture_output=True, - text=True, - check=False, - env=env, - ) + try: + proc = subprocess.run( + command, + capture_output=True, + text=True, + check=False, + env=env, + timeout=timeout, + ) + except subprocess.TimeoutExpired as exc: + details = f"stdout={exc.output!r} stderr={exc.stderr!r}" + raise cmuxError(f"CLI timed out after {timeout:.1f}s: {command!r}; {details}") from exc elapsed = time.monotonic() - started return proc, elapsed @@ -78,7 +96,11 @@ def main() -> int: proc, elapsed = _run_cli(cli, ["new-workspace", "--command", cmd_text]) combined = f"{proc.stdout}\n{proc.stderr}".strip() _must(proc.returncode == 0, f"CLI failed ({proc.returncode}): {combined}") - _must(elapsed < 1.5, f"new-workspace --command should return quickly, took {elapsed:.2f}s") + quick_return_timeout = _float_env("NEW_WORKSPACE_COMMAND_TIMEOUT", 5.0) + _must( + elapsed < quick_return_timeout, + f"new-workspace --command should return quickly, took {elapsed:.2f}s", + ) output = (proc.stdout or "").strip() _must(output.startswith("OK "), f"Expected OK response, got: {output!r}") diff --git a/tests_v2/test_cli_new_workspace_layout_command_queue.py b/tests_v2/test_cli_new_workspace_layout_command_queue.py new file mode 100644 index 000000000000..34c0e0e3b8d8 --- /dev/null +++ b/tests_v2/test_cli_new_workspace_layout_command_queue.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Regression: `new-workspace --layout` terminal commands should execute without focus.""" + +from __future__ import annotations + +import glob +import json +import os +import shlex +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +from cmux import cmux, cmuxError + + +SOCKET_PATH = os.environ.get("CMUX_SOCKET_PATH", "/tmp/cmux-debug.sock") + + +def _must(cond: bool, msg: str) -> None: + if not cond: + raise cmuxError(msg) + + +def _float_env(name: str, default: float) -> float: + raw = os.environ.get(name) + if not raw: + return default + try: + value = float(raw) + except ValueError: + return default + return value if value > 0 else default + + +def _find_cli_binary() -> str: + env_cli = os.environ.get("CMUXTERM_CLI") + if env_cli and os.path.isfile(env_cli) and os.access(env_cli, os.X_OK): + return env_cli + + fixed = os.path.expanduser("~/Library/Developer/Xcode/DerivedData/cmux-tests-v2/Build/Products/Debug/cmux") + if os.path.isfile(fixed) and os.access(fixed, os.X_OK): + return fixed + + candidates = glob.glob(os.path.expanduser("~/Library/Developer/Xcode/DerivedData/**/Build/Products/Debug/cmux"), recursive=True) + candidates += glob.glob("/tmp/cmux-*/Build/Products/Debug/cmux") + candidates = [p for p in candidates if os.path.isfile(p) and os.access(p, os.X_OK)] + if not candidates: + raise cmuxError("Could not locate cmux CLI binary; set CMUXTERM_CLI") + candidates.sort(key=lambda p: os.path.getmtime(p), reverse=True) + return candidates[0] + + +def _run_cli(cli: str, args: list[str]) -> tuple[subprocess.CompletedProcess[str], float]: + env = dict(os.environ) + env.pop("CMUX_WORKSPACE_ID", None) + env.pop("CMUX_SURFACE_ID", None) + env.pop("CMUX_TAB_ID", None) + + command = [cli, "--socket", SOCKET_PATH, *args] + timeout = _float_env("CMUX_TEST_CLI_RUN_TIMEOUT", 30.0) + started = time.monotonic() + try: + proc = subprocess.run( + command, + capture_output=True, + text=True, + check=False, + env=env, + timeout=timeout, + ) + except subprocess.TimeoutExpired as exc: + details = f"stdout={exc.output!r} stderr={exc.stderr!r}" + raise cmuxError(f"CLI timed out after {timeout:.1f}s: {command!r}; {details}") from exc + elapsed = time.monotonic() - started + return proc, elapsed + + +def main() -> int: + cli = _find_cli_binary() + marker = Path(tempfile.gettempdir()) / f"cmux_new_workspace_layout_command_{os.getpid()}.txt" + created_ws_id: str | None = None + + try: + marker.unlink(missing_ok=True) + except OSError: + pass + + with cmux(SOCKET_PATH) as c: + try: + baseline_ws_id = c.current_workspace() + token = f"layout-{os.getpid()}-{int(time.time() * 1000)}" + command = ( + "python3 -c " + + shlex.quote( + f"from pathlib import Path; Path({marker.as_posix()!r}).write_text({token!r}, encoding='utf-8')" + ) + ) + layout = { + "pane": { + "surfaces": [ + { + "type": "terminal", + "command": command, + } + ] + } + } + + proc, elapsed = _run_cli(cli, ["new-workspace", "--layout", json.dumps(layout)]) + combined = f"{proc.stdout}\n{proc.stderr}".strip() + _must(proc.returncode == 0, f"CLI failed ({proc.returncode}): {combined}") + quick_return_timeout = _float_env("NEW_WORKSPACE_LAYOUT_TIMEOUT", 5.0) + _must( + elapsed < quick_return_timeout, + f"new-workspace --layout should return quickly, took {elapsed:.2f}s", + ) + + output = (proc.stdout or "").strip() + _must(output.startswith("OK "), f"Expected OK response, got: {output!r}") + created_ws_id = output[3:].strip() + _must(bool(created_ws_id), f"Missing workspace id in output: {output!r}") + _must(c.current_workspace() == baseline_ws_id, "new-workspace --layout should preserve selected workspace") + + observed = "" + deadline = time.time() + 12.0 + while time.time() < deadline: + if marker.exists(): + try: + observed = marker.read_text(encoding="utf-8").strip() + except OSError: + observed = "" + if observed: + break + time.sleep(0.05) + + _must(marker.exists(), f"Layout command marker file was not created: {marker}") + _must(observed == token, f"Layout command did not execute as expected: expected={token!r} observed={observed!r}") + _must(c.current_workspace() == baseline_ws_id, "Layout command execution should not switch selected workspace") + finally: + if created_ws_id: + try: + c.close_workspace(created_ws_id) + except Exception: + pass + + try: + marker.unlink(missing_ok=True) + except OSError: + pass + + print("PASS: new-workspace --layout commands execute without opening the created workspace") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())