Skip to content
52 changes: 50 additions & 2 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17288,6 +17288,25 @@ struct CMUXCLI {
throw CLIError(message: "Pane has no surface to target")
}

private func tmuxStoredStartCommand(
workspaceId: String,
surfaceId: String,
client: SocketClient
) throws -> String? {
let payload = try client.sendV2(method: "surface.list", params: ["workspace_id": workspaceId])
let surfaces = payload["surfaces"] as? [[String: Any]] ?? []
guard let surface = surfaces.first(where: { ($0["id"] as? String) == surfaceId }) else {
return nil
}
return [
surface["tmux_start_command"],
surface["pane_start_command"],
surface["initial_command"]
]
.compactMap { ($0 as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) }
.first { !$0.isEmpty }
}

private func tmuxResolveSurfaceTarget(
_ raw: String?,
client: SocketClient
Expand Down Expand Up @@ -20187,6 +20206,32 @@ struct CMUXCLI {
"orientation": "vertical"
])

case "respawn-pane", "respawnp":
let parsed = try parseTmuxArguments(
rawArgs,
valueFlags: ["-c", "-t"],
boolFlags: ["-k"]
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let target = try tmuxResolveSurfaceTarget(parsed.value("-t"), client: client)
let commandText = tmuxStartCommand(commandTokens: parsed.positional)
?? (try? tmuxStoredStartCommand(
workspaceId: target.workspaceId,
surfaceId: target.surfaceId,
client: client
))
?? "exec ${SHELL:-/bin/sh} -l"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
var params: [String: Any] = [
"workspace_id": target.workspaceId,
"surface_id": target.surfaceId,
"command": commandText,
"tmux_start_command": commandText
]
if let cwd = parsed.value("-c")?.trimmingCharacters(in: .whitespacesAndNewlines),
!cwd.isEmpty {
params["working_directory"] = resolvePath(cwd)
}
_ = try client.sendV2(method: "surface.respawn", params: params)

case "send-keys", "send":
let parsed = try parseTmuxArguments(rawArgs, valueFlags: ["-t"], boolFlags: ["-l"])
let target = try tmuxResolveSurfaceTarget(parsed.value("-t"), client: client)
Expand Down Expand Up @@ -21120,14 +21165,17 @@ struct CMUXCLI {
let workspaceArg = workspaceOpt ?? (effectiveWindowRaw == nil ? ProcessInfo.processInfo.environment["CMUX_WORKSPACE_ID"] : nil)
let commandText = (commandOpt ?? respawnRem3.dropFirst(respawnRem3.first == "--" ? 1 : 0).joined(separator: " ")).trimmingCharacters(in: .whitespacesAndNewlines)
let finalCommand = commandText.isEmpty ? "exec ${SHELL:-/bin/zsh} -l" : commandText
var params: [String: Any] = ["text": finalCommand + "\n"]
var params: [String: Any] = [
"command": finalCommand,
"tmux_start_command": finalCommand
]
let winId = try normalizeWindowHandle(effectiveWindowRaw, client: client)
if let winId { params["window_id"] = winId }
let wsId = try normalizeWorkspaceHandle(workspaceArg, client: client, windowHandle: winId, allowCurrent: winId == nil)
if let wsId { params["workspace_id"] = wsId }
let sfId = try normalizeSurfaceHandle(surfaceArg, client: client, workspaceHandle: wsId, windowHandle: winId, allowFocused: true)
if let sfId { params["surface_id"] = sfId }
let payload = try client.sendV2(method: "surface.send_text", params: params)
let payload = try client.sendV2(method: "surface.respawn", params: params)
printV2Payload(payload, jsonOutput: jsonOutput, idFormat: idFormat, fallbackText: "OK")

case "display-message":
Expand Down
11 changes: 9 additions & 2 deletions Sources/GhosttyTerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5127,8 +5127,14 @@ final class TerminalSurfaceRegistry {

func unregister(_ surface: TerminalSurface) {
lock.lock()
let surfaceId = surface.id
surfaces.remove(surface)
surfaceFocusPlacements.removeValue(forKey: surface.id)
let stillRegistered = surfaces.allObjects
.compactMap { $0 as? TerminalSurface }
.contains { $0 !== surface && $0.id == surfaceId }
if !stillRegistered {
surfaceFocusPlacements.removeValue(forKey: surfaceId)
}
lock.unlock()

Task { @MainActor in
Expand Down Expand Up @@ -5483,6 +5489,7 @@ final class TerminalSurface: Identifiable, ObservableObject {
}

init(
id: UUID = UUID(),
tabId: UUID,
context: ghostty_surface_context_e,
configTemplate: CmuxSurfaceConfigTemplate?,
Expand All @@ -5499,7 +5506,7 @@ final class TerminalSurface: Identifiable, ObservableObject {
dispatchPrecondition(condition: .onQueue(.main))
#endif

self.id = UUID()
self.id = id
self.tabId = tabId
self.surfaceContext = context
self.configTemplate = configTemplate
Expand Down
4 changes: 4 additions & 0 deletions Sources/GhosttyTerminalViewSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ extension TerminalSurface {
tmuxStartCommand
}

func debugWaitAfterCommand() -> Bool {
configTemplate?.waitAfterCommand ?? false
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

func debugInitialInputMetadata() -> (hasInitialInput: Bool, byteCount: Int) {
let byteCount = initialInput?.utf8.count ?? 0
return (byteCount > 0, byteCount)
Expand Down
2 changes: 2 additions & 0 deletions Sources/Panels/TerminalPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ final class TerminalPanel: Panel, ObservableObject {

/// Create a new terminal panel with a fresh surface
convenience init(
id: UUID = UUID(),
workspaceId: UUID,
context: ghostty_surface_context_e = GHOSTTY_SURFACE_CONTEXT_SPLIT,
configTemplate: CmuxSurfaceConfigTemplate? = nil,
Expand All @@ -168,6 +169,7 @@ final class TerminalPanel: Panel, ObservableObject {
focusPlacement: TerminalSurfaceFocusPlacement = .workspace
) {
let surface = TerminalSurface(
id: id,
tabId: workspaceId,
context: context,
configTemplate: configTemplate,
Expand Down
78 changes: 78 additions & 0 deletions Sources/TerminalController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2845,6 +2845,8 @@ class TerminalController {
return v2Result(id: id, self.v2SurfaceFocus(params: params))
case "surface.split":
return v2Result(id: id, self.v2SurfaceSplit(params: params))
case "surface.respawn":
return v2Result(id: id, self.v2SurfaceRespawn(params: params))
case "surface.create":
return v2Result(id: id, self.v2SurfaceCreate(params: params))
case "surface.close":
Expand Down Expand Up @@ -3312,6 +3314,7 @@ class TerminalController {
"surface.current",
"surface.focus",
"surface.split",
"surface.respawn",
"surface.create",
"surface.close",
"surface.drag_to_split",
Expand Down Expand Up @@ -8672,6 +8675,81 @@ class TerminalController {
}
return result
}

private func v2SurfaceRespawn(params: [String: Any]) -> V2CallResult {
guard let tabManager = v2ResolveTabManager(params: params) else {
return .err(code: "unavailable", message: "TabManager not available", data: nil)
}

let command = v2OptionalTrimmedRawString(params, "command")
?? v2OptionalTrimmedRawString(params, "initial_command")
?? "exec ${SHELL:-/bin/zsh} -l"
let tmuxStartCommand = v2OptionalTrimmedRawString(params, "tmux_start_command") ?? command
let workingDirectory = v2OptionalTrimmedRawString(params, "working_directory")
let focus: Bool?
if v2HasNonNullParam(params, "focus") {
guard let parsedFocus = v2Bool(params, "focus") else {
return .err(code: "invalid_params", message: "Missing or invalid focus", data: nil)
}
focus = v2FocusAllowed(requested: parsedFocus)
} else {
focus = nil
}

var result: V2CallResult = .err(code: "internal_error", message: "Failed to respawn surface", data: nil)
v2MainSync {
guard let ws = v2ResolveWorkspace(params: params, tabManager: tabManager) else {
result = .err(code: "not_found", message: "Workspace not found", data: nil)
return
}

let surfaceId: UUID?
if params["surface_id"] != nil {
surfaceId = v2UUID(params, "surface_id")
guard surfaceId != nil else {
result = .err(code: "not_found", message: "Surface not found for the given surface_id", data: nil)
return
}
} else {
surfaceId = ws.focusedPanelId
}
guard let surfaceId else {
result = .err(code: "not_found", message: "No focused surface", data: nil)
return
}
guard ws.terminalPanel(for: surfaceId) != nil else {
result = .err(code: "invalid_params", message: "Surface is not a terminal", data: ["surface_id": surfaceId.uuidString])
return
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

v2MaybeFocusWindow(for: tabManager)
v2MaybeSelectWorkspace(tabManager, workspace: ws)

guard let replacementPanel = ws.respawnTerminalSurface(
panelId: surfaceId,
command: command,
workingDirectory: workingDirectory,
tmuxStartCommand: tmuxStartCommand,
focus: focus
) else {
result = .err(code: "internal_error", message: "Failed to respawn surface", data: ["surface_id": surfaceId.uuidString])
return
}

let windowId = v2ResolveWindowId(tabManager: tabManager)
result = .ok([
"workspace_id": ws.id.uuidString,
"workspace_ref": v2Ref(kind: .workspace, uuid: ws.id),
"surface_id": surfaceId.uuidString,
"surface_ref": v2Ref(kind: .surface, uuid: surfaceId),
"type": replacementPanel.panelType.rawValue,
"window_id": v2OrNull(windowId?.uuidString),
"window_ref": v2Ref(kind: .window, uuid: windowId)
])
}
return result
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

private func v2SurfaceCreate(params: [String: Any]) -> V2CallResult {
guard let tabManager = v2ResolveTabManager(params: params) else {
return .err(code: "unavailable", message: "TabManager not available", data: nil)
Expand Down
119 changes: 119 additions & 0 deletions Sources/Workspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14632,6 +14632,125 @@ final class Workspace: Identifiable, ObservableObject {
return newPanel
}

/// Replace the terminal process behind an existing surface while preserving its pane and tab identity.
@discardableResult
func respawnTerminalSurface(
panelId: UUID,
command: String,
workingDirectory: String? = nil,
tmuxStartCommand: String? = nil,
focus: Bool? = nil
) -> TerminalPanel? {
guard let oldPanel = terminalPanel(for: panelId),
let tabId = surfaceIdFromPanelId(panelId),
let paneId = paneId(forPanelId: panelId) else {
return nil
}

let trimmedCommand = command.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedCommand.isEmpty else { return nil }

var inheritedConfig = inheritedTerminalConfig(preferredPanelId: panelId, inPane: paneId)
let requestedWorkingDirectory: String? = {
if let workingDirectory = workingDirectory?.trimmingCharacters(in: .whitespacesAndNewlines),
!workingDirectory.isEmpty {
return workingDirectory
}
if let panelDirectory = panelDirectories[panelId]?.trimmingCharacters(in: .whitespacesAndNewlines),
!panelDirectory.isEmpty {
return panelDirectory
}
if let requestedWorkingDirectory = oldPanel.requestedWorkingDirectory?.trimmingCharacters(in: .whitespacesAndNewlines),
!requestedWorkingDirectory.isEmpty {
return requestedWorkingDirectory
}
let workspaceDirectory = currentDirectory.trimmingCharacters(in: .whitespacesAndNewlines)
return workspaceDirectory.isEmpty ? nil : workspaceDirectory
}()
let selectedInPane = bonsplitController.selectedTab(inPane: paneId)?.id == tabId
let paneWasFocused = bonsplitController.focusedPaneId == paneId
let shouldFocus = focus ?? (selectedInPane && paneWasFocused)
let customTitle = panelCustomTitles[panelId]
let wasPinned = pinnedPanelIds.contains(panelId)
let startCommand = tmuxStartCommand?.trimmingCharacters(in: .whitespacesAndNewlines)
let replacementTmuxStartCommand = (startCommand?.isEmpty == false) ? startCommand : trimmedCommand
let focusPlacement = oldPanel.surface.focusPlacement
var template = inheritedConfig ?? CmuxSurfaceConfigTemplate()
template.waitAfterCommand = true
inheritedConfig = template
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

discardClosedPanelLifecycleState(
panelId: panelId,
tabId: tabId,
paneId: paneId,
panel: oldPanel,
origin: "terminal_respawn",
closePanel: true,
publishSurfaceClosedEvent: false,
clearSurfaceNotifications: true,
requestTransferredRemoteCleanup: true,
cleanupControllerSurfaceState: true
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
austinywang marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
TerminalSurfaceRegistry.shared.unregister(oldPanel.surface)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

let replacementPanel = TerminalPanel(
id: panelId,
workspaceId: id,
context: GHOSTTY_SURFACE_CONTEXT_SPLIT,
configTemplate: inheritedConfig,
workingDirectory: requestedWorkingDirectory,
portOrdinal: portOrdinal,
initialCommand: trimmedCommand,
tmuxStartCommand: replacementTmuxStartCommand,
focusPlacement: focusPlacement
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
configureNewTerminalPanel(replacementPanel)
panels[panelId] = replacementPanel
panelTitles[panelId] = replacementPanel.displayTitle
if let customTitle {
panelCustomTitles[panelId] = customTitle
}
if wasPinned {
pinnedPanelIds.insert(panelId)
}
surfaceIdToPanelId[tabId] = panelId
seedTerminalInheritanceFontPoints(panelId: panelId, configTemplate: inheritedConfig)

let resolvedTitle = resolvedPanelTitle(panelId: panelId, fallback: replacementPanel.displayTitle)
bonsplitController.updateTab(
tabId,
title: resolvedTitle,
icon: .some(replacementPanel.displayIcon),
iconImageData: .some(nil),
kind: .some(SurfaceKind.terminal),
hasCustomTitle: customTitle != nil,
isDirty: replacementPanel.isDirty,
showsNotificationBadge: false,
isLoading: false,
isPinned: wasPinned
)

if shouldFocus {
bonsplitController.focusPane(paneId)
bonsplitController.selectTab(tabId)
focusPanel(panelId)
} else if selectedInPane {
bonsplitController.selectTab(tabId)
applyTabSelection(tabId: tabId, inPane: paneId)
} else {
replacementPanel.unfocus()
}

owningTabManager?.scheduleInitialWorkspaceGitMetadataRefreshIfPossible(
workspaceId: id,
panelId: panelId,
reason: "terminalRespawn"
)
scheduleTerminalGeometryReconcile()
scheduleFocusReconcile()
return replacementPanel
}

private func remoteTerminalStartupCommand() -> String? {
guard !suppressRemoteTerminalStartupForSessionRestoreScaffold else {
return nil
Expand Down
Loading
Loading