Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions Sources/GhosttyTerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -4550,6 +4551,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,
Expand All @@ -4566,6 +4568,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)
Expand All @@ -4581,9 +4584,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) {
Expand Down Expand Up @@ -5040,8 +5045,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
Expand All @@ -5062,7 +5070,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
Expand Down Expand Up @@ -5672,6 +5683,10 @@ final class TerminalSurface: Identifiable, ObservableObject {
_ = ghostty_surface_key(surface, keyEvent)
}

// 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() {
if !Thread.isMainThread {
DispatchQueue.main.async { [weak self] in
Expand All @@ -5690,14 +5705,6 @@ final class TerminalSurface: Identifiable, ObservableObject {
self.backgroundSurfaceStartQueued = false
guard self.allowsRuntimeSurfaceCreation() else { return }
guard self.surface == nil, let view = self.attachedView else { return }
guard view.window != nil else {
#if DEBUG
cmuxDebugLog(
"surface.background_start.defer surface=\(self.id.uuidString.prefix(8)) reason=noWindow"
)
#endif
return
}
#if DEBUG
let startedAt = ProcessInfo.processInfo.systemUptime
#endif
Expand Down
2 changes: 1 addition & 1 deletion Sources/Panels/TerminalPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,14 @@ final class TerminalPanel: Panel, ObservableObject {
context: context,
configTemplate: configTemplate,
workingDirectory: workingDirectory,
portOrdinal: portOrdinal,
initialCommand: initialCommand,
tmuxStartCommand: tmuxStartCommand,
initialInput: initialInput,
initialEnvironmentOverrides: initialEnvironmentOverrides,
additionalEnvironment: additionalEnvironment,
focusPlacement: focusPlacement
)
surface.portOrdinal = portOrdinal
self.init(workspaceId: workspaceId, surface: surface)
}

Expand Down
1 change: 1 addition & 0 deletions Sources/Workspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,7 @@ extension Workspace {
}
}
pendingTerminalInputObserversByPanelId[panelId, default: []].append(registration)
panel.surface.requestBackgroundSurfaceStartIfNeeded()

guard let timeout else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self, registration] in
Expand Down
38 changes: 30 additions & 8 deletions tests_v2/test_cli_new_workspace_command_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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

Expand All @@ -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}")
Expand Down
160 changes: 160 additions & 0 deletions tests_v2/test_cli_new_workspace_layout_command_queue.py
Original file line number Diff line number Diff line change
@@ -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())
Loading