From 841e02913aa041f6d408ad411241b3bae02874c9 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 05:10:03 -0700 Subject: [PATCH 01/35] test: cover stale surface restore routing --- .../CMUXCLIErrorOutputRegressionTests.swift | 84 ++++++++++++++++++- 1 file changed, 81 insertions(+), 3 deletions(-) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 42d218d362ee..1057d549e34d 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -632,6 +632,70 @@ import Testing XCTAssertEqual(requiredResponder.receivedRequests.count, 1) } + @Test func testRestorePrefersCallerTTYWhenAmbientSurfaceIDIsStale() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let staleSurfaceID = UUID().uuidString + let currentSurfaceID = UUID().uuidString + let workspaceID = UUID().uuidString + let terminalResponse = try jsonResponse(result: [ + "terminals": [[ + "tty": "ttys9380", + "workspace_id": workspaceID, + "surface_id": currentSurfaceID, + ]], + ]) + let restoreResponse = try jsonResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-stale-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [terminalResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = staleSurfaceID + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "debug.terminals", + "surface.resume.get", + ]) + let restoreRequest = try #require(requests.last) + let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == currentSurfaceID) + #expect(restoreParams["surface_id"] as? String != staleSurfaceID) + } + @Test func testBundledCLIInTaggedDebugAppPrefersItsOwnSocketWithoutEnvironmentOverride() throws { let cliPath = try bundledCLIPath() let tagSlug = "cli-socket-\(UUID().uuidString.lowercased())" @@ -2094,7 +2158,7 @@ import Testing final class UnixSocketResponder { let path: String - private let response: String + private let responses: [String] private let responseDelay: TimeInterval private let queue = DispatchQueue(label: "com.cmux.tests.unix-socket-responder") private let lock = NSLock() @@ -2102,9 +2166,20 @@ final class UnixSocketResponder { private var requests: [String] = [] private var listenerFD: Int32 = -1 - init(path: String, response: String, responseDelay: TimeInterval = 0) throws { + convenience init(path: String, response: String, responseDelay: TimeInterval = 0) throws { + try self.init(path: path, responses: [response], responseDelay: responseDelay) + } + + init(path: String, responses: [String], responseDelay: TimeInterval = 0) throws { + guard !responses.isEmpty else { + throw NSError( + domain: NSCocoaErrorDomain, + code: CocoaError.validationMissingMandatoryProperty.rawValue, + userInfo: [NSLocalizedDescriptionKey: "At least one socket response is required"] + ) + } self.path = path - self.response = response + self.responses = responses self.responseDelay = responseDelay unlink(path) @@ -2215,15 +2290,18 @@ final class UnixSocketResponder { break } } + var responseIndex = 0 if let line = String(data: request, encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines) { lock.lock() + responseIndex = requests.count requests.append(line) lock.unlock() } if responseDelay > 0 { Thread.sleep(forTimeInterval: responseDelay) } + let response = responses[min(responseIndex, responses.count - 1)] let payload = response + "\n" payload.withCString { pointer in _ = write(clientFD, pointer, strlen(pointer)) From a224fb4c894306000087d80e4794d41143d173c9 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 05:10:17 -0700 Subject: [PATCH 02/35] Prefer live terminal routing for restore --- CLI/CMUXCLI+Restore.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index affe89e57e37..2c81e6755452 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -52,10 +52,6 @@ extension CMUXCLI { ) } params["surface_id"] = surfaceID - } else if selector.usesCurrentSurface, - let surfaceID = processEnvironment["CMUX_SURFACE_ID"], - !surfaceID.isEmpty { - params["surface_id"] = surfaceID } else if selector.usesCurrentSurface, let ttyName = resolveCallerTTYName(), let caller = resolveTerminalBinding( @@ -63,6 +59,10 @@ extension CMUXCLI { client: client ) { params["surface_id"] = caller.surfaceId + } else if selector.usesCurrentSurface, + let surfaceID = processEnvironment["CMUX_SURFACE_ID"], + !surfaceID.isEmpty { + params["surface_id"] = surfaceID } else { throw CLIError( message: String( From 97a6408068f5af8e2d4a833c74df1ab2158f2f8b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 05:33:04 -0700 Subject: [PATCH 03/35] test: reject ambiguous restore TTY routing --- .../CMUXCLIErrorOutputRegressionTests.swift | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 1057d549e34d..5ed951676fd3 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -696,6 +696,78 @@ import Testing #expect(restoreParams["surface_id"] as? String != staleSurfaceID) } + @Test func testRestoreFallsBackToAmbientSurfaceWhenCallerTTYIsAmbiguous() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let ambientSurfaceID = UUID().uuidString + let firstTTYSurfaceID = UUID().uuidString + let secondTTYSurfaceID = UUID().uuidString + let terminalResponse = try jsonResponse(result: [ + "terminals": [ + [ + "tty": "ttys9380", + "workspace_id": UUID().uuidString, + "surface_id": firstTTYSurfaceID, + ], + [ + "tty": "ttys9380", + "workspace_id": UUID().uuidString, + "surface_id": secondTTYSurfaceID, + ], + ], + ]) + let restoreResponse = try jsonResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-ambiguous-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [terminalResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = ambientSurfaceID + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "debug.terminals", + "surface.resume.get", + ]) + let restoreRequest = try #require(requests.last) + let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == ambientSurfaceID) + #expect(restoreParams["surface_id"] as? String != firstTTYSurfaceID) + #expect(restoreParams["surface_id"] as? String != secondTTYSurfaceID) + } + @Test func testBundledCLIInTaggedDebugAppPrefersItsOwnSocketWithoutEnvironmentOverride() throws { let cliPath = try bundledCLIPath() let tagSlug = "cli-socket-\(UUID().uuidString.lowercased())" From fec1cb040d0615ada134588d6bdcfc2356f96e2c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 05:34:10 -0700 Subject: [PATCH 04/35] Reject ambiguous TTY restore routing --- CLI/CMUXCLI+Restore.swift | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index 2c81e6755452..606763eea9f7 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -53,11 +53,7 @@ extension CMUXCLI { } params["surface_id"] = surfaceID } else if selector.usesCurrentSurface, - let ttyName = resolveCallerTTYName(), - let caller = resolveTerminalBinding( - ttyName: ttyName, - client: client - ) { + let caller = uniqueCallerTerminalBindingByTTY(client: client) { params["surface_id"] = caller.surfaceId } else if selector.usesCurrentSurface, let surfaceID = processEnvironment["CMUX_SURFACE_ID"], From a738eb3bf6229372fb4f10dc68ce3b7a459efd05 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 06:02:25 -0700 Subject: [PATCH 05/35] test: cover live restore target resolution --- .../CMUXCLIErrorOutputRegressionTests.swift | 277 ++++++++++++++---- 1 file changed, 221 insertions(+), 56 deletions(-) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 5ed951676fd3..2cec7ce73b1b 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -112,28 +112,32 @@ import Testing let arguments = [executable.path, "space value", "quote'\"", "日本語", String(repeating: "x", count: 4_000)] let surfaceID = UUID().uuidString.lowercased() let workspaceID = UUID().uuidString.lowercased() - let response = try jsonResponse(result: [ - "terminals": [[ - "tty": "ttys9258", - "workspace_id": workspaceID, - "surface_id": surfaceID, - ]], - "restore_record": [ - "mode": "direct", - "kind": "custom", - "checkpoint_id": checkpointID, - "source": "test", - "working_directory": workingDirectory.path, - "environment": ["RESTORE_VALUE": "値 with spaces"], - "launch_command": [ - "arguments": arguments, - "executable_path": executable.path, + let response = try restoreResponse( + result: [ + "terminals": [[ + "tty": "ttys9258", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ]], + "restore_record": [ + "mode": "direct", + "kind": "custom", + "checkpoint_id": checkpointID, + "source": "test", "working_directory": workingDirectory.path, "environment": ["RESTORE_VALUE": "値 with spaces"], + "launch_command": [ + "arguments": arguments, + "executable_path": executable.path, + "working_directory": workingDirectory.path, + "environment": ["RESTORE_VALUE": "値 with spaces"], + ], + "prepared_arguments": arguments, ], - "prepared_arguments": arguments, ], - ]) + workspaceID: workspaceID, + surfaceID: surfaceID + ) let socketPath = "/tmp/cmux-restore-\(UUID().uuidString.prefix(8)).sock" let responder = try UnixSocketResponder(path: socketPath, response: response) defer { responder.stop() } @@ -166,7 +170,7 @@ import Testing ) return try XCTUnwrap(object["method"] as? String) } - XCTAssertEqual(methods, ["debug.terminals", "surface.resume.get"]) + XCTAssertEqual(methods, ["agent.resolve_delivery_target", "surface.resume.get"]) } @Test func testRestoreDoesNotResolveBareExecutableFromEmptyPATHComponent() throws { @@ -188,7 +192,7 @@ import Testing defer { try? FileManager.default.removeItem(at: root) } let checkpointID = "path-\(UUID().uuidString)" - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "custom", @@ -259,7 +263,7 @@ import Testing let checkpointID = "preflight-\(UUID().uuidString)" let launchEnvironment = ["CUSTOM_BASE_URL": "https://codex.example.test/v1"] - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "resumeAgent", "kind": "hermes-agent", @@ -342,7 +346,7 @@ import Testing "--session", checkpointID, ] - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "resumeAgent", "kind": "cwd-agent", @@ -392,7 +396,7 @@ import Testing defer { try? FileManager.default.removeItem(at: root) } let checkpointID = "legacy-\(UUID().uuidString)" - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "resumeAgent", "kind": "codex", @@ -434,7 +438,7 @@ import Testing defer { try? FileManager.default.removeItem(at: root) } let checkpointID = "fallback-\(UUID().uuidString)" - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "relaunchAgent", "kind": "custom-relaunch", @@ -504,7 +508,7 @@ import Testing @Test func testRestorePositionalFormFailsClosedWhenBindingIdentityDrifts() throws { let cliPath = try bundledCLIPath() let currentCheckpointID = UUID().uuidString.lowercased() - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "codex", @@ -586,7 +590,7 @@ import Testing @Test func testRestoreWaitsForControlSocketDuringAppStartup() throws { let cliPath = try bundledCLIPath() let checkpointID = UUID().uuidString.lowercased() - let response = try jsonResponse(result: [ + let response = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "custom", @@ -629,23 +633,28 @@ import Testing let requiredResponder = try #require(responder) XCTAssertFalse(result.timedOut, result.stdout) XCTAssertEqual(result.status, 0, result.stdout) - XCTAssertEqual(requiredResponder.receivedRequests.count, 1) + XCTAssertEqual(requiredResponder.receivedRequests.count, 2) } - @Test func testRestorePrefersCallerTTYWhenAmbientSurfaceIDIsStale() throws { + @Test func testRestorePrefersLiveProcessTargetOverStaleAmbientRouting() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" let staleSurfaceID = UUID().uuidString + let staleTTYSurfaceID = UUID().uuidString let currentSurfaceID = UUID().uuidString let workspaceID = UUID().uuidString - let terminalResponse = try jsonResponse(result: [ + let callerTargetResponse = try jsonResponse(result: [ "terminals": [[ "tty": "ttys9380", - "workspace_id": workspaceID, - "surface_id": currentSurfaceID, + "workspace_id": UUID().uuidString, + "surface_id": staleTTYSurfaceID, ]], + "source": "pid", + "pid_resolution": "controlling_tty", + "workspace_id": workspaceID, + "surface_id": currentSurfaceID, ]) - let restoreResponse = try jsonResponse(result: [ + let restoreResponse = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "pi", @@ -661,7 +670,7 @@ import Testing let socketPath = "/tmp/cmux-restore-stale-\(UUID().uuidString.prefix(8)).sock" let responder = try UnixSocketResponder( path: socketPath, - responses: [terminalResponse, restoreResponse] + responses: [callerTargetResponse, restoreResponse] ) defer { responder.stop() } var environment = ProcessInfo.processInfo.environment @@ -687,36 +696,29 @@ import Testing return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) } #expect(requests.compactMap { $0["method"] as? String } == [ - "debug.terminals", + "agent.resolve_delivery_target", "surface.resume.get", ]) + let callerTargetRequest = try #require(requests.first) + let callerTargetParams = try #require(callerTargetRequest["params"] as? [String: Any]) + #expect((callerTargetParams["pid"] as? Int).map { $0 > 0 } == true) + #expect(callerTargetParams["pid_resolution"] as? String == "controlling_tty") let restoreRequest = try #require(requests.last) let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) #expect(restoreParams["surface_id"] as? String == currentSurfaceID) #expect(restoreParams["surface_id"] as? String != staleSurfaceID) + #expect(restoreParams["surface_id"] as? String != staleTTYSurfaceID) } - @Test func testRestoreFallsBackToAmbientSurfaceWhenCallerTTYIsAmbiguous() throws { + @Test func testRestoreFallsBackToAmbientSurfaceWhenLiveProcessTargetIsNotFound() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" let ambientSurfaceID = UUID().uuidString - let firstTTYSurfaceID = UUID().uuidString - let secondTTYSurfaceID = UUID().uuidString - let terminalResponse = try jsonResponse(result: [ - "terminals": [ - [ - "tty": "ttys9380", - "workspace_id": UUID().uuidString, - "surface_id": firstTTYSurfaceID, - ], - [ - "tty": "ttys9380", - "workspace_id": UUID().uuidString, - "surface_id": secondTTYSurfaceID, - ], - ], - ]) - let restoreResponse = try jsonResponse(result: [ + let callerTargetResponse = try jsonErrorResponse( + code: "not_found", + message: "No live delivery target" + ) + let restoreResponse = try restoreResponse(result: [ "restore_record": [ "mode": "direct", "kind": "pi", @@ -732,7 +734,7 @@ import Testing let socketPath = "/tmp/cmux-restore-ambiguous-\(UUID().uuidString.prefix(8)).sock" let responder = try UnixSocketResponder( path: socketPath, - responses: [terminalResponse, restoreResponse] + responses: [callerTargetResponse, restoreResponse] ) defer { responder.stop() } var environment = ProcessInfo.processInfo.environment @@ -758,14 +760,140 @@ import Testing return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) } #expect(requests.compactMap { $0["method"] as? String } == [ - "debug.terminals", + "agent.resolve_delivery_target", "surface.resume.get", ]) let restoreRequest = try #require(requests.last) let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) #expect(restoreParams["surface_id"] as? String == ambientSurfaceID) - #expect(restoreParams["surface_id"] as? String != firstTTYSurfaceID) - #expect(restoreParams["surface_id"] as? String != secondTTYSurfaceID) + } + + @Test func testRestoreRejectsMalformedLiveProcessTargetWithoutFallingBack() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let callerTargetResponse = try jsonResponse(result: [ + "terminals": [], + "source": "pid", + "pid_resolution": "controlling_tty", + "workspace_id": UUID().uuidString, + "surface_id": "not-a-surface-id", + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-malformed-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = UUID().uuidString + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect( + result.stdout.contains("the current cmux surface could not be identified"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + ]) + } + + @Test func testRestoreDoesNotReuseSocketAfterCallerTargetTimeout() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let currentSurfaceID = UUID().uuidString + let callerTargetResponse = try jsonResponse(result: [ + "terminals": [[ + "tty": "ttys9380", + "workspace_id": UUID().uuidString, + "surface_id": currentSurfaceID, + ]], + "source": "pid", + "pid_resolution": "controlling_tty", + "workspace_id": UUID().uuidString, + "surface_id": currentSurfaceID, + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-timeout-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, restoreResponse], + responseDelay: 0.3 + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SURFACE_ID"] = UUID().uuidString + environment["CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC"] = "0.2" + environment["TTY"] = "/dev/ttys9380" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect(result.stdout.contains("Command timed out"), Comment(rawValue: result.stdout)) + #expect( + !result.stdout.contains("this session has nothing to restore"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + ]) } @Test func testBundledCLIInTaggedDebugAppPrefersItsOwnSocketWithoutEnvironmentOverride() throws { @@ -2007,6 +2135,33 @@ import Testing return try XCTUnwrap(String(data: data, encoding: .utf8)) } + private func restoreResponse( + result: [String: Any], + workspaceID: String? = nil, + surfaceID: String? = nil + ) throws -> String { + var result = result + result["source"] = "pid" + result["pid_resolution"] = "controlling_tty" + result["workspace_id"] = workspaceID ?? UUID().uuidString + result["surface_id"] = surfaceID ?? UUID().uuidString + return try jsonResponse(result: result) + } + + private func jsonErrorResponse(code: String, message: String) throws -> String { + let data = try JSONSerialization.data( + withJSONObject: [ + "ok": false, + "error": [ + "code": code, + "message": message, + ], + ], + options: [] + ) + return try XCTUnwrap(String(data: data, encoding: .utf8)) + } + /// The stable control-socket path under an injected (temp) home, resolved via /// the canonical ``CmuxStateDirectory`` so the test exercises the real layout. private func stableSocketURL(home: URL) throws -> URL { @@ -2349,6 +2504,16 @@ final class UnixSocketResponder { private func handle(clientFD: Int32) { defer { close(clientFD) } + var noSigPipe: Int32 = 1 + _ = withUnsafePointer(to: &noSigPipe) { pointer in + setsockopt( + clientFD, + SOL_SOCKET, + SO_NOSIGPIPE, + pointer, + socklen_t(MemoryLayout.size) + ) + } while true { var request = Data() while true { From 0f1a9f3cd83b0ecb69c8179638b56300dfefcd1c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 06:10:42 -0700 Subject: [PATCH 06/35] Resolve restore target from live process --- CLI/CMUXCLI+Restore.swift | 69 ++++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 11 deletions(-) diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index 606763eea9f7..01f075684cb3 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -53,19 +53,13 @@ extension CMUXCLI { } params["surface_id"] = surfaceID } else if selector.usesCurrentSurface, - let caller = uniqueCallerTerminalBindingByTTY(client: client) { - params["surface_id"] = caller.surfaceId - } else if selector.usesCurrentSurface, - let surfaceID = processEnvironment["CMUX_SURFACE_ID"], - !surfaceID.isEmpty { + let surfaceID = try currentRestoreSurfaceID( + client: client, + processEnvironment: processEnvironment + ) { params["surface_id"] = surfaceID } else { - throw CLIError( - message: String( - localized: "cli.restore.error.currentSurfaceUnknown", - defaultValue: "restore: the current cmux surface could not be identified. Retry from this terminal or pass --surface ." - ) - ) + throw currentRestoreSurfaceUnknownError() } let payload = try client.sendV2(method: "surface.resume.get", params: params) @@ -186,6 +180,59 @@ extension CMUXCLI { ) } + private func currentRestoreSurfaceID( + client: SocketClient, + processEnvironment: [String: String] + ) throws -> String? { + let ambientSurfaceID = processEnvironment["CMUX_SURFACE_ID"].flatMap { surfaceID in + surfaceID.isEmpty ? nil : surfaceID + } + // The remote relay and the local CLI do not share a PID namespace. + guard !client.isRelayBacked else { return ambientSurfaceID } + + let resolution = AgentProcessBindingResolution.controllingTTY.rawValue + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: [ + "pid": Int(ProcessInfo.processInfo.processIdentifier), + "pid_resolution": resolution, + ] + ) + guard payload["source"] as? String == "pid", + payload["pid_resolution"] as? String == resolution, + let workspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(workspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found", "method_not_found", "unrecognized_method": + // These protocol replies were consumed in full, so the socket + // remains synchronized for the restore request. + return ambientSurfaceID + default: + client.close() + throw error + } + } catch { + client.close() + throw error + } + } + + private func currentRestoreSurfaceUnknownError() -> CLIError { + CLIError( + message: String( + localized: "cli.restore.error.currentSurfaceUnknown", + defaultValue: "restore: the current cmux surface could not be identified. Retry from this terminal or pass --surface ." + ) + ) + } + private func restoreSelector(_ arguments: [String]) throws -> RestoreSelector { if arguments.first == "--surface" { if arguments.count == 1 { From 789a189727bdde4e78a4f5395f18242e3dfffc51 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 06:24:35 -0700 Subject: [PATCH 07/35] test: cover authoritative restore routing failure --- .../CMUXCLIErrorOutputRegressionTests.swift | 75 ++++++++++++++++++- 1 file changed, 71 insertions(+), 4 deletions(-) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 2cec7ce73b1b..2435f6087291 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -710,10 +710,10 @@ import Testing #expect(restoreParams["surface_id"] as? String != staleTTYSurfaceID) } - @Test func testRestoreFallsBackToAmbientSurfaceWhenLiveProcessTargetIsNotFound() throws { + @Test func testRestoreFailsClosedWhenLiveProcessTargetIsNotFound() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" - let ambientSurfaceID = UUID().uuidString + let staleSurfaceID = UUID().uuidString let callerTargetResponse = try jsonErrorResponse( code: "not_found", message: "No live delivery target" @@ -743,7 +743,7 @@ import Testing } environment["CMUX_CLI_SENTRY_DISABLED"] = "1" environment["CMUX_SOCKET_PATH"] = socketPath - environment["CMUX_SURFACE_ID"] = ambientSurfaceID + environment["CMUX_SURFACE_ID"] = staleSurfaceID environment["TTY"] = "/dev/ttys9380" let result = runProcess( @@ -753,6 +753,72 @@ import Testing timeout: 5 ) + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect( + result.stdout.contains("the current cmux surface could not be identified"), + Comment(rawValue: result.stdout) + ) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + ]) + } + + @Test func testRestoreUsesUniqueTTYBindingWhenLiveTargetMethodIsUnsupported() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let callerTargetResponse = try jsonErrorResponse( + code: "method_not_found", + message: "Unknown method" + ) + let terminalsResponse = try jsonResponse(result: [ + "terminals": [[ + "tty": "ttys9380", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ]], + ]) + let restoreResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-legacy-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [callerTargetResponse, terminalsResponse, restoreResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_CLI_TTY_NAME"] = "ttys9380" + environment["TTY"] = "/dev/ttys-stale" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + #expect(!result.timedOut, Comment(rawValue: result.stdout)) #expect(result.status == 0, Comment(rawValue: result.stdout)) let requests = try responder.receivedRequests.map { request in @@ -761,11 +827,12 @@ import Testing } #expect(requests.compactMap { $0["method"] as? String } == [ "agent.resolve_delivery_target", + "debug.terminals", "surface.resume.get", ]) let restoreRequest = try #require(requests.last) let restoreParams = try #require(restoreRequest["params"] as? [String: Any]) - #expect(restoreParams["surface_id"] as? String == ambientSurfaceID) + #expect(restoreParams["surface_id"] as? String == surfaceID) } @Test func testRestoreRejectsMalformedLiveProcessTargetWithoutFallingBack() throws { From 381670c06057bcf0c99e6bfa5cf76e277ebbfd0f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 06:26:42 -0700 Subject: [PATCH 08/35] Fail closed on missing live restore target --- CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift | 11 ++++-- CLI/CMUXCLI+Restore.swift | 37 ++++++++++++++------ 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift b/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift index fd6358dc9733..c03b227edc5d 100644 --- a/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift +++ b/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift @@ -76,10 +76,17 @@ extension CMUXCLI { client: SocketClient, includeAmbientTTY: Bool = true ) -> CallerTerminalBinding? { - guard let ttyName = resolveCallerTTYName(includeAmbientTTY: includeAmbientTTY), - let payload = try? client.sendV2(method: "debug.terminals") else { + guard let ttyName = resolveCallerTTYName(includeAmbientTTY: includeAmbientTTY) else { return nil } + return uniqueCallerTerminalBindingByTTY(ttyName: ttyName, client: client) + } + + func uniqueCallerTerminalBindingByTTY( + ttyName: String, + client: SocketClient + ) -> CallerTerminalBinding? { + guard let payload = try? client.sendV2(method: "debug.terminals") else { return nil } let terminals = payload["terminals"] as? [[String: Any]] ?? [] var matched: [CallerTerminalBinding] = [] for terminal in terminals { diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index 01f075684cb3..052e323478b2 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -54,8 +54,7 @@ extension CMUXCLI { params["surface_id"] = surfaceID } else if selector.usesCurrentSurface, let surfaceID = try currentRestoreSurfaceID( - client: client, - processEnvironment: processEnvironment + client: client ) { params["surface_id"] = surfaceID } else { @@ -181,14 +180,12 @@ extension CMUXCLI { } private func currentRestoreSurfaceID( - client: SocketClient, - processEnvironment: [String: String] + client: SocketClient ) throws -> String? { - let ambientSurfaceID = processEnvironment["CMUX_SURFACE_ID"].flatMap { surfaceID in - surfaceID.isEmpty ? nil : surfaceID - } // The remote relay and the local CLI do not share a PID namespace. - guard !client.isRelayBacked else { return ambientSurfaceID } + guard !client.isRelayBacked else { + return legacyRestoreSurfaceID(client: client) + } let resolution = AgentProcessBindingResolution.controllingTTY.rawValue do { @@ -210,10 +207,13 @@ extension CMUXCLI { return surfaceID } catch let error as CLIError { switch error.v2Code { - case "not_found", "method_not_found", "unrecognized_method": + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": // These protocol replies were consumed in full, so the socket - // remains synchronized for the restore request. - return ambientSurfaceID + // remains synchronized for the legacy discovery request. + return legacyRestoreSurfaceID(client: client) default: client.close() throw error @@ -224,6 +224,21 @@ extension CMUXCLI { } } + private func legacyRestoreSurfaceID(client: SocketClient) -> String? { + // Prefer the live descriptors. Generic TTY variables can be inherited + // across nested shells, so only dedicated cmux hints are a fallback. + let ttyName = resolveCallerDescriptorTTYName() + ?? resolveCallerTTYName(includeAmbientTTY: false) + guard let ttyName, + let binding = uniqueCallerTerminalBindingByTTY( + ttyName: ttyName, + client: client + ) else { + return nil + } + return binding.surfaceId + } + private func currentRestoreSurfaceUnknownError() -> CLIError { CLIError( message: String( From 29eb9e6f47e265dd5d93cbe47fa168bc73281e28 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 06:54:59 -0700 Subject: [PATCH 09/35] test: cover restored TTY registration race --- ...entNotificationMutationBoundaryTests.swift | 33 +++++++++ .../CMUXCLIErrorOutputRegressionTests.swift | 67 +++++++++++++++++++ 2 files changed, 100 insertions(+) diff --git a/cmuxTests/AgentNotificationMutationBoundaryTests.swift b/cmuxTests/AgentNotificationMutationBoundaryTests.swift index c72910c96652..2328b5cca12a 100644 --- a/cmuxTests/AgentNotificationMutationBoundaryTests.swift +++ b/cmuxTests/AgentNotificationMutationBoundaryTests.swift @@ -105,6 +105,39 @@ extension AgentNotificationRegressionTests { #expect(workspace.localAgentDeliveryTTYDevices.isEmpty) } + @Test("Restored TTY metadata requires a fresh runtime registration") + func restoredTTYMetadataRequiresFreshRuntimeRegistration() throws { + let workspace = Workspace() + let panelId = try #require(workspace.focusedPanelId) + let snapshot = SessionPanelSnapshot( + id: panelId, + type: .terminal, + title: "Restored terminal", + customTitle: nil, + directory: nil, + isPinned: false, + isManuallyUnread: false, + listeningPorts: [], + ttyName: "/dev/null", + terminal: SessionTerminalPanelSnapshot(), + browser: nil, + markdown: nil, + filePreview: nil, + rightSidebarTool: nil + ) + + workspace.applySessionPanelMetadata(snapshot, toPanelId: panelId) + + #expect(workspace.surfaceTTYNames[panelId] == "/dev/null") + #expect( + workspace.localAgentDeliveryTTYDevices.isEmpty, + "Persisted TTY metadata is not evidence from the current terminal runtime" + ) + + workspace.surfaceTTYNames[panelId] = "/dev/null" + #expect(workspace.localAgentDeliveryTTYDevices.map(\.surfaceId) == [panelId]) + } + @Test("Live PID routing and runtime mutations include a Dock-owned terminal") func liveTTYBindingsAndRuntimeMutationsIncludeDockOwnedTerminal() throws { let fixture = try makeFixture() diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 2435f6087291..d52b44529e3f 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -710,6 +710,73 @@ import Testing #expect(restoreParams["surface_id"] as? String != staleTTYSurfaceID) } + @Test func testRestoreRetriesUntilFreshTTYRegistrationIsVisible() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let notFoundResponse = try jsonErrorResponse( + code: "not_found", + message: "No live delivery target" + ) + let liveTargetResponse = try restoreResponse( + result: [:], + workspaceID: workspaceID, + surfaceID: surfaceID + ) + let recordResponse = try restoreResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let socketPath = "/tmp/cmux-restore-registration-\(UUID().uuidString.prefix(8)).sock" + let responder = try UnixSocketResponder( + path: socketPath, + responses: [notFoundResponse, liveTargetResponse, recordResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = socketPath + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "agent.resolve_delivery_target", + "surface.resume.get", + ]) + for request in requests.prefix(2) { + let params = try #require(request["params"] as? [String: Any]) + #expect((params["pid"] as? Int).map { $0 > 0 } == true) + #expect(params["pid_resolution"] as? String == "controlling_tty") + } + let restoreParams = try #require(requests.last?["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == surfaceID) + } + @Test func testRestoreFailsClosedWhenLiveProcessTargetIsNotFound() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" From be1b8bd8e7b341fe5e9465dce6fc6936a6cdd668 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 07:00:27 -0700 Subject: [PATCH 10/35] Wait for fresh restore TTY registration --- CLI/CMUXCLI+Restore.swift | 72 +++++++++++-------- Sources/AgentDeliveryTargetResolution.swift | 12 +++- Sources/Workspace.swift | 4 +- .../CMUXCLIErrorOutputRegressionTests.swift | 21 ++---- 4 files changed, 59 insertions(+), 50 deletions(-) diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index 052e323478b2..9804b22628dc 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -1,4 +1,5 @@ import CMUXAgentLaunch +import Darwin import Foundation extension CMUXCLI { @@ -188,39 +189,50 @@ extension CMUXCLI { } let resolution = AgentProcessBindingResolution.controllingTTY.rawValue - do { - let payload = try client.sendV2( - method: "agent.resolve_delivery_target", - params: [ - "pid": Int(ProcessInfo.processInfo.processIdentifier), - "pid_resolution": resolution, - ] - ) - guard payload["source"] as? String == "pid", - payload["pid_resolution"] as? String == resolution, - let workspaceID = normalizedHandleValue(payload["workspace_id"] as? String), - isUUID(workspaceID), - let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), - isUUID(surfaceID) else { - throw currentRestoreSurfaceUnknownError() - } - return surfaceID - } catch let error as CLIError { - switch error.v2Code { - case "not_found": - client.close() - throw currentRestoreSurfaceUnknownError() - case "method_not_found", "unrecognized_method": - // These protocol replies were consumed in full, so the socket - // remains synchronized for the legacy discovery request. - return legacyRestoreSurfaceID(client: client) - default: + let retryDelays: [useconds_t] = [25_000, 50_000, 100_000, 200_000, 400_000] + var retryIndex = 0 + while true { + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: [ + "pid": Int(ProcessInfo.processInfo.processIdentifier), + "pid_resolution": resolution, + ] + ) + guard payload["source"] as? String == "pid", + payload["pid_resolution"] as? String == resolution, + let workspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(workspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found" where retryIndex < retryDelays.count: + // Local shell integration registers its TTY in a background + // child. A complete `not_found` reply leaves this socket + // synchronized, so briefly wait for that registration and + // retry without trusting persisted or ambient surface ids. + usleep(retryDelays[retryIndex]) + retryIndex += 1 + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": + // These protocol replies were consumed in full, so the socket + // remains synchronized for the legacy discovery request. + return legacyRestoreSurfaceID(client: client) + default: + client.close() + throw error + } + } catch { client.close() throw error } - } catch { - client.close() - throw error } } diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index db35d70ed41f..ba5bdcb70899 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -85,7 +85,8 @@ extension Workspace { set { let previous = surfaceRegistry.surfaceTTYNames var devices = surfaceRegistry.surfaceTTYDevices.filter { newValue[$0.key] != nil } - for (panelId, ttyName) in newValue where previous[panelId] != ttyName { + for (panelId, ttyName) in newValue + where previous[panelId] != ttyName || devices[panelId] == nil { devices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) } surfaceRegistry.surfaceTTYNames = newValue @@ -96,6 +97,15 @@ extension Workspace { /// Cached TTY character-device ids, updated with ``surfaceTTYNames``. var surfaceTTYDevices: [UUID: Int64] { surfaceRegistry.surfaceTTYDevices } + /// Restores display/port-scan metadata without treating the previous + /// process's PTY as evidence about the newly created terminal runtime. + /// A subsequent `report_tty`, even with the same name, populates the live + /// device index through ``surfaceTTYNames``. + func restorePersistedSurfaceTTYName(_ ttyName: String?, panelId: UUID) { + surfaceRegistry.surfaceTTYNames[panelId] = ttyName + surfaceRegistry.surfaceTTYDevices.removeValue(forKey: panelId) + } + /// Host-local TTY bindings eligible to identify a process running on this /// Mac. Remote workspaces and remote terminal surfaces use a different /// `/dev` namespace and must never participate in local device matching. diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 2d6399e91330..37047794b346 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1879,9 +1879,9 @@ extension Workspace { surfaceListeningPorts[panelId] = Array(Set(snapshot.listeningPorts)).sorted() if let ttyName = snapshot.ttyName?.trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty { - surfaceTTYNames[panelId] = ttyName + restorePersistedSurfaceTTYName(ttyName, panelId: panelId) } else { - surfaceTTYNames.removeValue(forKey: panelId) + restorePersistedSurfaceTTYName(nil, panelId: panelId) } syncRemotePortScanTTYs() diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index d52b44529e3f..18cb89781c9a 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -785,23 +785,10 @@ import Testing code: "not_found", message: "No live delivery target" ) - let restoreResponse = try restoreResponse(result: [ - "restore_record": [ - "mode": "direct", - "kind": "pi", - "checkpoint_id": checkpointID, - "environment": [:], - "launch_command": [ - "arguments": ["/usr/bin/true"], - "executable_path": "/usr/bin/true", - ], - "prepared_arguments": ["/usr/bin/true"], - ], - ]) let socketPath = "/tmp/cmux-restore-ambiguous-\(UUID().uuidString.prefix(8)).sock" let responder = try UnixSocketResponder( path: socketPath, - responses: [callerTargetResponse, restoreResponse] + response: callerTargetResponse ) defer { responder.stop() } var environment = ProcessInfo.processInfo.environment @@ -830,9 +817,9 @@ import Testing let data = try #require(request.data(using: .utf8)) return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) } - #expect(requests.compactMap { $0["method"] as? String } == [ - "agent.resolve_delivery_target", - ]) + let methods = requests.compactMap { $0["method"] as? String } + #expect(methods.count > 1) + #expect(methods.allSatisfy { $0 == "agent.resolve_delivery_target" }) } @Test func testRestoreUsesUniqueTTYBindingWhenLiveTargetMethodIsUnsupported() throws { From 49af68cee45a883e95495c1e63b842f5d64e320e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 07:19:37 -0700 Subject: [PATCH 11/35] test: scope relay restore TTY routing --- .../CMUXCLIErrorOutputRegressionTests.swift | 241 ++++++++++++++++++ 1 file changed, 241 insertions(+) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 18cb89781c9a..ebe0560ca246 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -889,6 +889,86 @@ import Testing #expect(restoreParams["surface_id"] as? String == surfaceID) } + @Test func testRestoreScopesRelayTTYResolutionToAuthenticatedWorkspace() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let siblingWorkspaceID = UUID().uuidString + let siblingSurfaceID = UUID().uuidString + let liveTargetResponse = try jsonResponse(result: [ + "terminals": [ + [ + "tty": "0", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ], + [ + "tty": "0", + "workspace_id": siblingWorkspaceID, + "surface_id": siblingSurfaceID, + ], + ], + "source": "tty", + "tty_resolution": "reported_tty", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ]) + let recordResponse = try jsonResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let relayID = "relay-\(UUID().uuidString.lowercased())" + let responder = try RelaySocketResponder( + relayID: relayID, + responses: [liveTargetResponse, recordResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = responder.endpoint + environment["CMUX_RELAY_ID"] = relayID + environment["CMUX_RELAY_TOKEN"] = String(repeating: "11", count: 32) + environment["CMUX_WORKSPACE_ID"] = workspaceID + environment["CMUX_CLI_TTY_NAME"] = "0" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "surface.resume.get", + ]) + let targetParams = try #require(requests.first?["params"] as? [String: Any]) + #expect(targetParams["tty_name"] as? String == "0") + #expect(targetParams["tty_resolution"] as? String == "reported_tty") + let restoreParams = try #require(requests.last?["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == surfaceID) + #expect(restoreParams["surface_id"] as? String != siblingSurfaceID) + } + @Test func testRestoreRejectsMalformedLiveProcessTargetWithoutFallingBack() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" @@ -2675,3 +2755,164 @@ final class UnixSocketResponder { ) } } + +final class RelaySocketResponder { + let endpoint: String + private let relayID: String + private let responses: [String] + private let queue = DispatchQueue(label: "com.cmux.tests.relay-socket-responder") + private let lock = NSLock() + private var stopped = false + private var requests: [String] = [] + private var listenerFD: Int32 = -1 + + init(relayID: String, responses: [String]) throws { + guard !responses.isEmpty else { + throw NSError( + domain: NSCocoaErrorDomain, + code: CocoaError.validationMissingMandatoryProperty.rawValue, + userInfo: [NSLocalizedDescriptionKey: "At least one relay response is required"] + ) + } + self.relayID = relayID + self.responses = responses + + let fd = socket(AF_INET, SOCK_STREAM, 0) + guard fd >= 0 else { throw Self.posixError("socket") } + var reuse: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, socklen_t(MemoryLayout.size)) + + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + address.sin_port = 0 + address.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1")) + let bindResult = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in + Darwin.bind(fd, socketPointer, socklen_t(MemoryLayout.size)) + } + } + guard bindResult == 0, listen(fd, 8) == 0 else { + let error = Self.posixError("bind/listen") + close(fd) + throw error + } + + var boundAddress = sockaddr_in() + var boundLength = socklen_t(MemoryLayout.size) + let nameResult = withUnsafeMutablePointer(to: &boundAddress) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in + getsockname(fd, socketPointer, &boundLength) + } + } + guard nameResult == 0 else { + let error = Self.posixError("getsockname") + close(fd) + throw error + } + + listenerFD = fd + endpoint = "127.0.0.1:\(UInt16(bigEndian: boundAddress.sin_port))" + queue.async { [weak self] in + self?.acceptLoop(listenerFD: fd) + } + } + + deinit { + stop() + } + + var receivedRequests: [String] { + lock.lock() + defer { lock.unlock() } + return requests + } + + func stop() { + lock.lock() + guard !stopped else { + lock.unlock() + return + } + stopped = true + let fd = listenerFD + listenerFD = -1 + lock.unlock() + if fd >= 0 { close(fd) } + } + + private var isStopped: Bool { + lock.lock() + defer { lock.unlock() } + return stopped + } + + private func acceptLoop(listenerFD: Int32) { + while !isStopped { + let clientFD = accept(listenerFD, nil, nil) + if clientFD < 0 { + if isStopped { return } + continue + } + handle(clientFD: clientFD) + } + } + + private func handle(clientFD: Int32) { + defer { close(clientFD) } + var noSigPipe: Int32 = 1 + setsockopt( + clientFD, + SOL_SOCKET, + SO_NOSIGPIPE, + &noSigPipe, + socklen_t(MemoryLayout.size) + ) + let challenge = #"{"protocol":"cmux-relay-auth","version":1,"relay_id":"\#(relayID)","nonce":"test-nonce"}"# + guard writeLine(challenge, to: clientFD), readLine(from: clientFD) != nil else { return } + guard writeLine(#"{"ok":true}"#, to: clientFD), + let request = readLine(from: clientFD) else { return } + + lock.lock() + let responseIndex = requests.count + requests.append(request) + lock.unlock() + _ = writeLine(responses[min(responseIndex, responses.count - 1)], to: clientFD) + } + + private func readLine(from fd: Int32) -> String? { + var data = Data() + while true { + var byte: UInt8 = 0 + let count = read(fd, &byte, 1) + if count < 0, errno == EINTR { continue } + guard count > 0 else { return nil } + if byte == 0x0A { return String(data: data, encoding: .utf8) } + data.append(byte) + } + } + + private func writeLine(_ line: String, to fd: Int32) -> Bool { + let data = Data((line + "\n").utf8) + return data.withUnsafeBytes { rawBuffer in + guard var pointer = rawBuffer.bindMemory(to: UInt8.self).baseAddress else { return false } + var remaining = rawBuffer.count + while remaining > 0 { + let count = write(fd, pointer, remaining) + if count < 0, errno == EINTR { continue } + guard count > 0 else { return false } + pointer = pointer.advanced(by: count) + remaining -= count + } + return true + } + } + + private static func posixError(_ operation: String) -> NSError { + NSError( + domain: NSPOSIXErrorDomain, + code: Int(errno), + userInfo: [NSLocalizedDescriptionKey: "\(operation) failed: \(String(cString: strerror(errno)))"] + ) + } +} From 98dd645945fe5a93ce524324b89ebda9bc0cc54b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 07:25:42 -0700 Subject: [PATCH 12/35] test: constrain relay TTY resolution --- .../AgentNotificationLiveRetargetTests.swift | 49 +++++++++++++++++++ cmuxTests/RemoteResumeBindingTests.swift | 30 ++++++++++++ 2 files changed, 79 insertions(+) diff --git a/cmuxTests/AgentNotificationLiveRetargetTests.swift b/cmuxTests/AgentNotificationLiveRetargetTests.swift index 20eaccd152f6..494d9063fc5e 100644 --- a/cmuxTests/AgentNotificationLiveRetargetTests.swift +++ b/cmuxTests/AgentNotificationLiveRetargetTests.swift @@ -1,5 +1,6 @@ import AppKit import CmuxControlSocket +import CmuxCore import Testing #if canImport(cmux_DEV) @testable import cmux_DEV @@ -175,6 +176,54 @@ extension AgentNotificationRegressionTests { #expect(code == "invalid_params") } + @Test + func testRelayTTYResolutionStaysInsideAuthenticatedWorkspace() throws { + let fixture = try makeLiveRetargetFixture() + defer { fixture.restore() } + + let remoteConfiguration = WorkspaceRemoteConfiguration( + destination: "example.invalid", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: nil, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil + ) + fixture.claimedWorkspace.remoteConfiguration = remoteConfiguration + fixture.owningWorkspace.remoteConfiguration = remoteConfiguration + let siblingPanelID = try #require(fixture.claimedWorkspace.focusedPanelId) + #expect(TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.claimedWorkspace.id, + requestedSurfaceID: siblingPanelID, + ttyName: "0" + ) == .recorded(surfaceID: siblingPanelID)) + #expect(TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.owningWorkspace.id, + requestedSurfaceID: fixture.panelId, + ttyName: "0" + ) == .recorded(surfaceID: fixture.panelId)) + + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": "0", + "tty_resolution": "reported_tty", + "workspace_id": fixture.claimedWorkspace.id.uuidString, + "_cmux_remote_workspace_id": fixture.owningWorkspace.id.uuidString, + ]) + guard case .ok(let payload) = result, + let target = payload as? [String: Any] else { + Issue.record("Expected authenticated relay TTY resolution, got \(result)") + return + } + #expect(target["source"] as? String == "tty") + #expect(target["tty_resolution"] as? String == "reported_tty") + #expect(target["workspace_id"] as? String == fixture.owningWorkspace.id.uuidString) + #expect(target["surface_id"] as? String == fixture.panelId.uuidString) + } + @Test func testSurfaceScopedClearDiscardsStaleKeyedPendingNotification() throws { let fixture = try makeLiveRetargetFixture() diff --git a/cmuxTests/RemoteResumeBindingTests.swift b/cmuxTests/RemoteResumeBindingTests.swift index dc2c54fe1179..4d733c67972e 100644 --- a/cmuxTests/RemoteResumeBindingTests.swift +++ b/cmuxTests/RemoteResumeBindingTests.swift @@ -184,6 +184,36 @@ struct RemoteResumeBindingTests { )) } + @Test + func relayDeliveryTargetProvenanceOverridesSpoofedWorkspace() throws { + let workspaceID = UUID() + let spoofedWorkspaceID = UUID() + let request: [String: Any] = [ + "id": "relay-delivery-target", + "method": "agent.resolve_delivery_target", + "params": [ + "tty_name": "0", + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": spoofedWorkspaceID.uuidString, + ], + ] + + let rewritten = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: workspaceID, + remoteRelayTokenHex: String(repeating: "a", count: 64) + ).rewriteRemoteRelayCommandLine( + try requestData(request), + workspaceAliases: [:], + surfaceAliases: [:] + ) + let rewrittenRequest = try jsonRequest(rewritten) + let params = try #require(rewrittenRequest["params"] as? [String: Any]) + + #expect(params["_cmux_remote_workspace_id"] as? String == workspaceID.uuidString) + #expect(params["tty_name"] as? String == "0") + #expect(params["tty_resolution"] as? String == "reported_tty") + } + @Test func remoteResumeProvenanceRequiresExactMethodAndUntamperedAuthentication() throws { let workspaceID = UUID() From 56549f044e25f601ec97a977a4c1dc79837d71e3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 07:43:46 -0700 Subject: [PATCH 13/35] test: preserve relay restore workspace aliases --- .../CMUXCLIErrorOutputRegressionTests.swift | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index ebe0560ca246..547ad1f2f3e4 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -969,6 +969,88 @@ import Testing #expect(restoreParams["surface_id"] as? String != siblingSurfaceID) } + @Test func testRestoreScopesLegacyRelayTTYFallbackToResolvedWorkspace() throws { + let cliPath = try bundledCLIPath() + let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let staleWorkspaceID = UUID().uuidString + let workspaceID = UUID().uuidString + let surfaceID = UUID().uuidString + let siblingWorkspaceID = UUID().uuidString + let siblingSurfaceID = UUID().uuidString + let workspaceResponse = try jsonResponse(result: [ + "source": "workspace", + "workspace_id": workspaceID, + "surface_id": NSNull(), + ]) + let terminalsResponse = try jsonResponse(result: [ + "terminals": [ + [ + "tty": "0", + "workspace_id": workspaceID, + "surface_id": surfaceID, + ], + [ + "tty": "0", + "workspace_id": siblingWorkspaceID, + "surface_id": siblingSurfaceID, + ], + ], + ]) + let recordResponse = try jsonResponse(result: [ + "restore_record": [ + "mode": "direct", + "kind": "pi", + "checkpoint_id": checkpointID, + "environment": [:], + "launch_command": [ + "arguments": ["/usr/bin/true"], + "executable_path": "/usr/bin/true", + ], + "prepared_arguments": ["/usr/bin/true"], + ], + ]) + let relayID = "relay-\(UUID().uuidString.lowercased())" + let responder = try RelaySocketResponder( + relayID: relayID, + responses: [workspaceResponse, terminalsResponse, recordResponse] + ) + defer { responder.stop() } + var environment = ProcessInfo.processInfo.environment + for key in Array(environment.keys) where key.hasPrefix("CMUX_") { + environment.removeValue(forKey: key) + } + environment["CMUX_CLI_SENTRY_DISABLED"] = "1" + environment["CMUX_SOCKET_PATH"] = responder.endpoint + environment["CMUX_RELAY_ID"] = relayID + environment["CMUX_RELAY_TOKEN"] = String(repeating: "11", count: 32) + environment["CMUX_WORKSPACE_ID"] = staleWorkspaceID + environment["CMUX_CLI_TTY_NAME"] = "0" + + let result = runProcess( + executablePath: cliPath, + arguments: ["restore", "pi", checkpointID], + environment: environment, + timeout: 5 + ) + + #expect(!result.timedOut, Comment(rawValue: result.stdout)) + #expect(result.status == 0, Comment(rawValue: result.stdout)) + let requests = try responder.receivedRequests.map { request in + let data = try #require(request.data(using: .utf8)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + #expect(requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target", + "debug.terminals", + "surface.resume.get", + ]) + let targetParams = try #require(requests.first?["params"] as? [String: Any]) + #expect(targetParams["workspace_id"] as? String == staleWorkspaceID) + let restoreParams = try #require(requests.last?["params"] as? [String: Any]) + #expect(restoreParams["surface_id"] as? String == surfaceID) + #expect(restoreParams["surface_id"] as? String != siblingSurfaceID) + } + @Test func testRestoreRejectsMalformedLiveProcessTargetWithoutFallingBack() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" From c27496059561f95f2fd46a7cd0131e7d5175d31c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 07:51:29 -0700 Subject: [PATCH 14/35] Scope relay restore to authenticated terminal --- CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift | 5 +- CLI/CMUXCLI+Restore.swift | 102 ++++++++++++++++-- .../Core/Model/SurfaceRegistryModel.swift | 5 + Sources/AgentDeliveryTargetResolution.swift | 67 +++++++++++- Sources/AgentProcessBindingResolution.swift | 4 + ...nalController+ControlSidebarContext2.swift | 4 +- ...nalController+ControlSurfaceContext4.swift | 2 +- .../Workspace+RemoteRelayCommandRewrite.swift | 2 +- Sources/Workspace.swift | 4 +- ...entNotificationMutationBoundaryTests.swift | 8 +- 10 files changed, 186 insertions(+), 17 deletions(-) diff --git a/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift b/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift index c03b227edc5d..d134b135c6da 100644 --- a/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift +++ b/CLI/CMUXCLI+ClaudeHookWorkspaceRouting.swift @@ -84,14 +84,17 @@ extension CMUXCLI { func uniqueCallerTerminalBindingByTTY( ttyName: String, - client: SocketClient + client: SocketClient, + workspaceId: String? = nil ) -> CallerTerminalBinding? { guard let payload = try? client.sendV2(method: "debug.terminals") else { return nil } let terminals = payload["terminals"] as? [[String: Any]] ?? [] + let scopedWorkspaceId = normalizedHandleValue(workspaceId) var matched: [CallerTerminalBinding] = [] for terminal in terminals { guard normalizedTTYName(terminal["tty"] as? String) == ttyName, let workspaceId = normalizedHandleValue(terminal["workspace_id"] as? String), + scopedWorkspaceId == nil || workspaceId == scopedWorkspaceId, let surfaceId = normalizedHandleValue(terminal["surface_id"] as? String) else { continue } diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index 9804b22628dc..f2ed9e39db37 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -55,7 +55,8 @@ extension CMUXCLI { params["surface_id"] = surfaceID } else if selector.usesCurrentSurface, let surfaceID = try currentRestoreSurfaceID( - client: client + client: client, + processEnvironment: processEnvironment ) { params["surface_id"] = surfaceID } else { @@ -181,11 +182,15 @@ extension CMUXCLI { } private func currentRestoreSurfaceID( - client: SocketClient + client: SocketClient, + processEnvironment: [String: String] ) throws -> String? { // The remote relay and the local CLI do not share a PID namespace. - guard !client.isRelayBacked else { - return legacyRestoreSurfaceID(client: client) + if client.isRelayBacked { + return try relayRestoreSurfaceID( + client: client, + processEnvironment: processEnvironment + ) } let resolution = AgentProcessBindingResolution.controllingTTY.rawValue @@ -224,7 +229,10 @@ extension CMUXCLI { case "method_not_found", "unrecognized_method": // These protocol replies were consumed in full, so the socket // remains synchronized for the legacy discovery request. - return legacyRestoreSurfaceID(client: client) + return legacyRestoreSurfaceID( + client: client, + workspaceID: nil + ) default: client.close() throw error @@ -236,7 +244,86 @@ extension CMUXCLI { } } - private func legacyRestoreSurfaceID(client: SocketClient) -> String? { + private func relayRestoreSurfaceID( + client: SocketClient, + processEnvironment: [String: String] + ) throws -> String? { + let ttyName = resolveCallerDescriptorTTYName() + ?? resolveCallerTTYName(includeAmbientTTY: false) + guard let ttyName else { return nil } + + let resolution = AgentTTYBindingResolution.reportedTTY.rawValue + let workspaceID = normalizedHandleValue(processEnvironment["CMUX_WORKSPACE_ID"]) + var params: [String: Any] = [ + "tty_name": ttyName, + "tty_resolution": resolution, + ] + if let workspaceID { + // Lets an older app identify this probe as an unsupported + // workspace-only resolution. The authenticated relay rewrites + // aliases and separately stamps its authoritative owner id. + params["workspace_id"] = workspaceID + } + + let retryDelays: [useconds_t] = [25_000, 50_000, 100_000, 200_000, 400_000] + var retryIndex = 0 + while true { + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: params + ) + if payload["source"] as? String == "workspace", + payload["surface_id"] == nil || payload["surface_id"] is NSNull, + let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(resolvedWorkspaceID) { + // Previous app versions ignore the TTY probe and resolve + // only workspace_id. Use their alias-rewritten result to + // scope the legacy terminal list, not the stale remote + // shell environment value that produced the request. + return legacyRestoreSurfaceID( + client: client, + workspaceID: resolvedWorkspaceID + ) + } + guard payload["source"] as? String == "tty", + payload["tty_resolution"] as? String == resolution, + let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(resolvedWorkspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found" where retryIndex < retryDelays.count: + usleep(retryDelays[retryIndex]) + retryIndex += 1 + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": + guard let workspaceID, isUUID(workspaceID) else { return nil } + return legacyRestoreSurfaceID( + client: client, + workspaceID: workspaceID + ) + default: + client.close() + throw error + } + } catch { + client.close() + throw error + } + } + } + + private func legacyRestoreSurfaceID( + client: SocketClient, + workspaceID: String? + ) -> String? { // Prefer the live descriptors. Generic TTY variables can be inherited // across nested shells, so only dedicated cmux hints are a fallback. let ttyName = resolveCallerDescriptorTTYName() @@ -244,7 +331,8 @@ extension CMUXCLI { guard let ttyName, let binding = uniqueCallerTerminalBindingByTTY( ttyName: ttyName, - client: client + client: client, + workspaceId: workspaceID ) else { return nil } diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift index cc0dd432084b..0f2b36f9e336 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift @@ -50,6 +50,11 @@ public final class SurfaceRegistryModel { /// routing never performs per-surface filesystem work on the main actor. public var surfaceTTYDevices: [UUID: Int64] = [:] + /// Surface ids whose TTY name was reported by the current terminal + /// runtime. Persisted names stay out of this set until `report_tty` + /// arrives, including when the current runtime reuses the same name. + public var runtimeReportedTTYSurfaceIDs: Set = [] + /// The shell-activity classification reported for each terminal panel, /// keyed by panel id (legacy `Workspace.panelShellActivityStates`). public var panelShellActivityStates: [UUID: PanelShellActivityState] = [:] diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index ba5bdcb70899..8ae793f4843c 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -85,18 +85,29 @@ extension Workspace { set { let previous = surfaceRegistry.surfaceTTYNames var devices = surfaceRegistry.surfaceTTYDevices.filter { newValue[$0.key] != nil } - for (panelId, ttyName) in newValue - where previous[panelId] != ttyName || devices[panelId] == nil { + var runtimeReported = surfaceRegistry.runtimeReportedTTYSurfaceIDs.intersection(newValue.keys) + for (panelId, ttyName) in newValue where previous[panelId] != ttyName { devices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) + runtimeReported.insert(panelId) } surfaceRegistry.surfaceTTYNames = newValue surfaceRegistry.surfaceTTYDevices = devices + surfaceRegistry.runtimeReportedTTYSurfaceIDs = runtimeReported } } /// Cached TTY character-device ids, updated with ``surfaceTTYNames``. var surfaceTTYDevices: [UUID: Int64] { surfaceRegistry.surfaceTTYDevices } + /// Records an explicit `report_tty` from the current terminal runtime. + /// This stays distinct from dictionary metadata writes because a restored + /// runtime can legitimately report the same TTY name as its predecessor. + func registerReportedSurfaceTTYName(_ ttyName: String, panelId: UUID) { + surfaceTTYNames[panelId] = ttyName + surfaceRegistry.surfaceTTYDevices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) + surfaceRegistry.runtimeReportedTTYSurfaceIDs.insert(panelId) + } + /// Restores display/port-scan metadata without treating the previous /// process's PTY as evidence about the newly created terminal runtime. /// A subsequent `report_tty`, even with the same name, populates the live @@ -104,6 +115,32 @@ extension Workspace { func restorePersistedSurfaceTTYName(_ ttyName: String?, panelId: UUID) { surfaceRegistry.surfaceTTYNames[panelId] = ttyName surfaceRegistry.surfaceTTYDevices.removeValue(forKey: panelId) + surfaceRegistry.runtimeReportedTTYSurfaceIDs.remove(panelId) + } + + /// Resolves a remote caller only from a TTY report observed in this app + /// runtime. TTY basenames are unique only inside one authenticated remote + /// workspace because separate hosts commonly reuse `/dev/pts/0`. + func agentDeliveryTarget(forReportedTTYName ttyName: String) -> AgentDeliveryTargetCandidate? { + guard isRemoteWorkspace else { return nil } + let candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = + surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceId + -> (binding: TerminalCallerTTYBinding, ttyName: String)? in + guard panels[surfaceId] != nil, + let reportedTTYName = surfaceRegistry.surfaceTTYNames[surfaceId] else { + return nil + } + return ( + binding: TerminalCallerTTYBinding(workspaceId: id, surfaceId: surfaceId), + ttyName: reportedTTYName + ) + } + let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) + guard let binding = resolver.binding(for: ttyName) else { return nil } + return AgentDeliveryTargetCandidate( + workspaceId: binding.workspaceId, + surfaceId: binding.surfaceId + ) } /// Host-local TTY bindings eligible to identify a process running on this @@ -268,6 +305,8 @@ extension TerminalController { /// - `{surface_id, workspace_id?}`: the workspace that currently hosts a /// known surface (`source: "surface"`), re-homing moved panes. /// - `{workspace_id}`: existence check only (`source: "workspace"`). + /// - `{tty_name, tty_resolution: "reported_tty"}`: a relay-authenticated + /// remote workspace's unique fresh TTY report (`source: "tty"`). func v2AgentResolveDeliveryTarget(params: [String: Any]) -> V2CallResult { let claimedWorkspaceId = v2UUID(params, "workspace_id") let claimedSurfaceId = v2UUID(params, "surface_id") @@ -298,6 +337,30 @@ extension TerminalController { data: nil ) } + if params.keys.contains("tty_name") { + let ttyResolution = AgentTTYBindingResolution.reportedTTY.rawValue + guard params["tty_resolution"] as? String == ttyResolution, + let ttyName = params["tty_name"] as? String, + TerminalCallerTTYResolver.normalizedName(ttyName) != nil, + let remoteWorkspaceId = v2UUID(params, "_cmux_remote_workspace_id"), + let workspace = controlTabForSidebarMutation(id: remoteWorkspaceId), + let target = workspace.agentDeliveryTarget(forReportedTTYName: ttyName) else { + return .err( + code: "not_found", + message: String( + localized: "agent.deliveryTarget.error.notFound", + defaultValue: "No live delivery target" + ), + data: nil + ) + } + return .ok([ + "workspace_id": target.workspaceId.uuidString, + "surface_id": target.surfaceId.uuidString, + "source": "tty", + "tty_resolution": ttyResolution, + ]) + } if params.keys.contains("pid") { // A socket caller controls both the value and its JSON type. Do // not coerce fractional/lossy NSNumber values, trap while diff --git a/Sources/AgentProcessBindingResolution.swift b/Sources/AgentProcessBindingResolution.swift index fdd34fc919e2..208d536b3d0b 100644 --- a/Sources/AgentProcessBindingResolution.swift +++ b/Sources/AgentProcessBindingResolution.swift @@ -2,3 +2,7 @@ enum AgentProcessBindingResolution: String, Sendable { case corroborated case controllingTTY = "controlling_tty" } + +enum AgentTTYBindingResolution: String, Sendable { + case reportedTTY = "reported_tty" +} diff --git a/Sources/TerminalController+ControlSidebarContext2.swift b/Sources/TerminalController+ControlSidebarContext2.swift index 7a652ed99ff7..741e8133ba95 100644 --- a/Sources/TerminalController+ControlSidebarContext2.swift +++ b/Sources/TerminalController+ControlSidebarContext2.swift @@ -291,7 +291,7 @@ extension TerminalController { let validSurfaceIds = Set(tab.panels.keys) tab.pruneSurfaceMetadata(validSurfaceIds: validSurfaceIds) guard validSurfaceIds.contains(scope.panelID) else { return } - tab.surfaceTTYNames[scope.panelID] = ttyName + tab.registerReportedSurfaceTTYName(ttyName, panelId: scope.panelID) if tab.isRemoteWorkspace { tab.syncRemotePortScanTTYs() _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: scope.panelID) @@ -308,7 +308,7 @@ extension TerminalController { prune: false, requireLiveSurface: true ) { tab, surfaceId in - tab.surfaceTTYNames[surfaceId] = ttyName + tab.registerReportedSurfaceTTYName(ttyName, panelId: surfaceId) if tab.isRemoteWorkspace { tab.syncRemotePortScanTTYs() _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: surfaceId) diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index 7f154ec97aaf..a51ce4ed33e6 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -46,7 +46,7 @@ extension TerminalController { return .surfaceNotFound } - tab.surfaceTTYNames[surfaceId] = ttyName + tab.registerReportedSurfaceTTYName(ttyName, panelId: surfaceId) if tab.isRemoteWorkspace { tab.syncRemotePortScanTTYs() _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: surfaceId) diff --git a/Sources/Workspace+RemoteRelayCommandRewrite.swift b/Sources/Workspace+RemoteRelayCommandRewrite.swift index d425104f2511..304310af7e79 100644 --- a/Sources/Workspace+RemoteRelayCommandRewrite.swift +++ b/Sources/Workspace+RemoteRelayCommandRewrite.swift @@ -85,7 +85,7 @@ extension Workspace { surfaceAliases: surfaceAliases, didRewrite: &didRewrite ) as? [String: Any] ?? params - if method == "surface.resume.set", + if method == "surface.resume.set" || method == "agent.resolve_delivery_target", let remoteWorkspaceID { params["_cmux_remote_workspace_id"] = remoteWorkspaceID.uuidString didRewrite = true diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 37047794b346..4fe55760cbf4 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -6517,7 +6517,7 @@ final class Workspace: Identifiable, ObservableObject { if let requestedSurfaceId = pendingRemoteSurfaceTTYSurfaceId, requestedSurfaceId != panelId { return } - surfaceTTYNames[panelId] = ttyName + registerReportedSurfaceTTYName(ttyName, panelId: panelId) pendingRemoteSurfaceTTYName = nil pendingRemoteSurfaceTTYSurfaceId = nil syncRemotePortScanTTYs() @@ -6567,7 +6567,7 @@ final class Workspace: Identifiable, ObservableObject { return } - surfaceTTYNames[candidateSurfaceId] = trimmedTTY + registerReportedSurfaceTTYName(trimmedTTY, panelId: candidateSurfaceId) syncRemotePortScanTTYs() if !applyPendingRemoteSurfacePortKickIfNeeded(to: candidateSurfaceId) { kickRemotePortScan(panelId: candidateSurfaceId, reason: .command) diff --git a/cmuxTests/AgentNotificationMutationBoundaryTests.swift b/cmuxTests/AgentNotificationMutationBoundaryTests.swift index 2328b5cca12a..497c3b1b2e2a 100644 --- a/cmuxTests/AgentNotificationMutationBoundaryTests.swift +++ b/cmuxTests/AgentNotificationMutationBoundaryTests.swift @@ -134,7 +134,13 @@ extension AgentNotificationRegressionTests { "Persisted TTY metadata is not evidence from the current terminal runtime" ) - workspace.surfaceTTYNames[panelId] = "/dev/null" + workspace.pruneSurfaceMetadata(validSurfaceIds: [panelId]) + #expect( + workspace.localAgentDeliveryTTYDevices.isEmpty, + "Metadata pruning must not promote a persisted TTY into live evidence" + ) + + workspace.registerReportedSurfaceTTYName("/dev/null", panelId: panelId) #expect(workspace.localAgentDeliveryTTYDevices.map(\.surfaceId) == [panelId]) } From 30d5bcecc0ce5ab808ca963deeb4be1dcc265c38 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 08:23:56 -0700 Subject: [PATCH 15/35] test: cover live and Dock TTY routing --- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/AgentDeliveryTTYBindingTests.swift | 175 +++++++++++++++++++ 2 files changed, 179 insertions(+) create mode 100644 cmuxTests/AgentDeliveryTTYBindingTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 6e7386cb79d4..d5fe361e17b0 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -45,6 +45,7 @@ ACA7C4A7000000000000000B /* AgentChatTranscriptService.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */; }; ACA7C4A70000000000000009 /* AgentChatTranscriptTailer.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */; }; 79390005AA11BB22CC33DD05 /* AgentDeliveryTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */; }; + 93800001AA11BB22CC33EE01 /* AgentDeliveryTTYBindingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */; }; A9F200000000000000000001 /* AgentExecutableResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000001 /* AgentExecutableResolver.swift */; }; A9F200000000000000000002 /* AgentExecutableResolverError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000002 /* AgentExecutableResolverError.swift */; }; A9E020000000000000000005 /* AgentExecutableResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9E010000000000000000005 /* AgentExecutableResolverTests.swift */; }; @@ -2715,6 +2716,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources ACA7C4A7000000000000000C /* AgentChatTranscriptService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptService.swift"; sourceTree = ""; }; ACA7C4A7000000000000000A /* AgentChatTranscriptTailer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "AgentChatTranscriptTailer.swift"; sourceTree = ""; }; 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTargetResolution.swift; sourceTree = ""; }; + 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDeliveryTTYBindingTests.swift; sourceTree = ""; }; A9F100000000000000000001 /* AgentExecutableResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolver.swift; sourceTree = ""; }; A9F100000000000000000002 /* AgentExecutableResolverError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolverError.swift; sourceTree = ""; }; A9E010000000000000000005 /* AgentExecutableResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentExecutableResolverTests.swift; sourceTree = ""; }; @@ -7810,6 +7812,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 79390004AA11BB22CC33DD04 /* AgentNotificationLiveRetargetTests.swift */, 79390010AA11BB22CC33DD10 /* AgentNotificationMoveRaceTests.swift */, 79460002AA11BB22CC33EE02 /* AgentNotificationMutationBoundaryTests.swift */, + 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */, 79390012AA11BB22CC33DD12 /* ClaudeHookPIDAuthenticationTests.swift */, C7A534000000000000000001 /* ClaudeHookFeedTelemetrySwiftTests.swift */, A5D41223A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift */, @@ -10260,6 +10263,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C7A51E000000000000000002 /* AgentChatSessionRegistryLifecycleTests.swift in Sources */, C7A51D100000000000000002 /* AgentChatSessionRegistryObservationReviewRegressionTests.swift in Sources */, C7A51D000000000000000002 /* AgentChatSessionRegistryObservationTests.swift in Sources */, + 93800001AA11BB22CC33EE01 /* AgentDeliveryTTYBindingTests.swift in Sources */, A9E020000000000000000005 /* AgentExecutableResolverTests.swift in Sources */, 8740E0018740E0018740E001 /* AgentHibernationEvaluationSchedulingTests.swift in Sources */, 9090E0039090E0039090E003 /* AgentHibernationPanelCloseCleanupTests.swift in Sources */, diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift new file mode 100644 index 000000000000..43be732f0287 --- /dev/null +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -0,0 +1,175 @@ +import AppKit +import CmuxCore +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +extension AgentNotificationRegressionTests { + @Test("Local PID bindings use the live Ghostty TTY without a shell report") + func localTTYBindingsUseLiveGhosttyTTYWithoutShellReport() async throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 640, height: 480), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + let contentView = try #require(window.contentView) + let hostedView = terminal.hostedView + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + window.orderFront(nil) + window.displayIfNeeded() + defer { + hostedView.removeFromSuperview() + window.orderOut(nil) + } + let liveTTYName = try #require(await waitForControllingTTYName(for: terminal)) + let liveTTYDevice = try #require( + CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: liveTTYName) + ) + + fixture.source.restorePersistedSurfaceTTYName(nil, panelId: fixture.panelId) + + #expect(fixture.source.surfaceTTYNames[fixture.panelId] == nil) + #expect( + fixture.source.localAgentDeliveryTTYDevices.contains { + $0.surfaceId == fixture.panelId && $0.ttyDevice == liveTTYDevice + }, + "A live terminal must remain PID-routable when shell integration is disabled" + ) + } + + @Test("Generic TTY metadata changes do not become runtime reports") + func genericTTYMetadataDoesNotBecomeRuntimeReport() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration() + workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) + #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) + + workspace.surfaceTTYNames[panelID] = "pts/1" + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/1") == nil, + "Only an explicit report_tty call may establish runtime provenance" + ) + } + + @Test("Relay TTY resolution follows a freshly reported surface into a Dock") + func relayTTYResolutionFollowsFreshReportIntoDock() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/2" + ) == .recorded(surfaceID: fixture.panelId) + ) + + try moveRemoteSurface(fixture, into: dock) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/2", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("A runtime TTY report refreshes a remote surface already in a Dock") + func runtimeTTYReportRefreshesRemoteSurfaceAlreadyInDock() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/3" + ) == .recorded(surfaceID: fixture.panelId) + ) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/3", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + } + + private func moveRemoteSurface(_ fixture: Fixture, into dock: DockSplitStore) throws { + let transfer = try #require(fixture.source.detachSurface(panelId: fixture.panelId)) + let rootPane = try #require(dock.bonsplitController.allPaneIds.first) + #expect( + dock.attachDetachedSurface(transfer, inPane: rootPane, focus: false) + == fixture.panelId + ) + } + + private func waitForControllingTTYName(for terminal: TerminalPanel) async -> String? { + let deadline = ContinuousClock.now + .seconds(15) + while ContinuousClock.now < deadline { + if let ttyName = terminal.surface.controllingTTYName() { + return ttyName + } + try? await Task.sleep(for: .milliseconds(10)) + } + return terminal.surface.controllingTTYName() + } + + private func assertRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String, + expectedWorkspaceID: UUID, + expectedSurfaceID: UUID + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .ok(let payload) = result, + let target = payload as? [String: Any] else { + Issue.record("Expected authenticated relay TTY resolution, got \(result)") + return + } + #expect(target["workspace_id"] as? String == expectedWorkspaceID.uuidString) + #expect(target["surface_id"] as? String == expectedSurfaceID.uuidString) + } + + private func deliveryTargetRemoteConfiguration() -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + destination: "example.invalid", + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: nil, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil + ) + } +} From d3b6294e4bd6acbf34fa6006dfd0252b1497af3b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 08:37:53 -0700 Subject: [PATCH 16/35] fix: complete live TTY restore routing --- Sources/AgentDeliveryTargetResolution.swift | 102 ++++++++++++------ ...ockSplitStore+RemoteTerminalLiveness.swift | 59 ++++++++++ Sources/DockSplitStore+SurfaceTransfer.swift | 1 + ...nalController+ControlSurfaceContext4.swift | 10 ++ .../Workspace+DetachedSurfaceTransfer.swift | 4 +- Sources/Workspace.swift | 7 +- .../AgentNotificationLiveRetargetTests.swift | 2 +- ...entNotificationMutationBoundaryTests.swift | 4 +- 8 files changed, 148 insertions(+), 41 deletions(-) diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index 8ae793f4843c..779275f597b8 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -13,10 +13,10 @@ import Foundation /// /// Two lookups implement this: /// - pid → surface: the agent process's controlling tty device -/// (`proc_bsdinfo.e_tdev`) matched against every live surface's reported -/// tty. A pane's pty device is fixed for the pane's lifetime and the -/// process's controlling terminal is a live kernel fact, so a unique match -/// is authoritative regardless of where the pane has been moved. +/// (`proc_bsdinfo.e_tdev`) matched against every live Ghostty PTY plus fresh +/// runtime TTY reports. A pane's pty device is fixed for the pane's lifetime, +/// and the process's controlling terminal is a live kernel fact, so a unique +/// match is authoritative regardless of where the pane has been moved. /// - surface → notification owner: `AppDelegate.notificationSurfaceOwner`, /// which finds the workspace or Dock that CURRENTLY owns the panel (issue /// #5781 pane moves and Dock transfers). @@ -78,25 +78,25 @@ nonisolated func agentLiveProcessIdentity(pid: pid_t) -> (ttyDevice: Int64?, sco @MainActor extension Workspace { - /// Reported TTY names and their device-id index share one mutation path so - /// live agent resolution never stats every surface on the main actor. + /// TTY metadata writes preserve runtime provenance only when the value is + /// unchanged. Only ``registerReportedSurfaceTTYName(_:panelId:)`` may + /// establish current-runtime evidence. var surfaceTTYNames: [UUID: String] { get { surfaceRegistry.surfaceTTYNames } set { let previous = surfaceRegistry.surfaceTTYNames - var devices = surfaceRegistry.surfaceTTYDevices.filter { newValue[$0.key] != nil } - var runtimeReported = surfaceRegistry.runtimeReportedTTYSurfaceIDs.intersection(newValue.keys) - for (panelId, ttyName) in newValue where previous[panelId] != ttyName { - devices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) - runtimeReported.insert(panelId) - } + let unchangedPanelIds = Set(newValue.compactMap { panelId, ttyName in + previous[panelId] == ttyName ? panelId : nil + }) surfaceRegistry.surfaceTTYNames = newValue - surfaceRegistry.surfaceTTYDevices = devices - surfaceRegistry.runtimeReportedTTYSurfaceIDs = runtimeReported + surfaceRegistry.surfaceTTYDevices = surfaceRegistry.surfaceTTYDevices.filter { + unchangedPanelIds.contains($0.key) + } + surfaceRegistry.runtimeReportedTTYSurfaceIDs.formIntersection(unchangedPanelIds) } } - /// Cached TTY character-device ids, updated with ``surfaceTTYNames``. + /// Cached character-device ids from explicit current-runtime TTY reports. var surfaceTTYDevices: [UUID: Int64] { surfaceRegistry.surfaceTTYDevices } /// Records an explicit `report_tty` from the current terminal runtime. @@ -118,12 +118,25 @@ extension Workspace { surfaceRegistry.runtimeReportedTTYSurfaceIDs.remove(panelId) } + func adoptTransferredSurfaceTTYName(from transfer: DetachedSurfaceTransfer) { + guard let ttyName = transfer.ttyName?.trimmingCharacters(in: .whitespacesAndNewlines), + !ttyName.isEmpty else { + surfaceTTYNames.removeValue(forKey: transfer.panelId) + return + } + if transfer.ttyNameWasReportedByCurrentRuntime { + registerReportedSurfaceTTYName(ttyName, panelId: transfer.panelId) + } else { + restorePersistedSurfaceTTYName(ttyName, panelId: transfer.panelId) + } + } + /// Resolves a remote caller only from a TTY report observed in this app /// runtime. TTY basenames are unique only inside one authenticated remote /// workspace because separate hosts commonly reuse `/dev/pts/0`. func agentDeliveryTarget(forReportedTTYName ttyName: String) -> AgentDeliveryTargetCandidate? { guard isRemoteWorkspace else { return nil } - let candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = + var candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceId -> (binding: TerminalCallerTTYBinding, ttyName: String)? in guard panels[surfaceId] != nil, @@ -135,6 +148,11 @@ extension Workspace { ttyName: reportedTTYName ) } + for dock in DockSplitStore.liveRemoteTerminalStores(presentationWorkspaceID: id) { + candidates.append(contentsOf: dock.runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: id + )) + } let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) guard let binding = resolver.binding(for: ttyName) else { return nil } return AgentDeliveryTargetCandidate( @@ -148,9 +166,23 @@ extension Workspace { /// `/dev` namespace and must never participate in local device matching. var localAgentDeliveryTTYDevices: [(surfaceId: UUID, ttyDevice: Int64)] { guard !isRemoteWorkspace, !isRemoteTmuxMirror else { return [] } - return surfaceTTYDevices.compactMap { panelId, device in - guard panels[panelId] != nil, !isRemoteTerminalSurface(panelId) else { return nil } - return (panelId, device) + return panels.flatMap { panelId, panel -> [(surfaceId: UUID, ttyDevice: Int64)] in + guard let terminal = panel as? TerminalPanel, + !isRemoteTerminalSurface(panelId) else { + return [] + } + var devices: [Int64] = [] + if let liveDevice = terminal.surface.controllingTTYName().flatMap( + CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) + ) { + devices.append(liveDevice) + } + if surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId), + let reportedDevice = surfaceTTYDevices[panelId], + !devices.contains(reportedDevice) { + devices.append(reportedDevice) + } + return devices.map { (panelId, $0) } } } } @@ -161,22 +193,29 @@ extension DockSplitStore { /// /// A surface transfer removes the panel from its Workspace registry, so /// live PID attribution must inspect Dock ownership separately. Prefer the - /// terminal's current Ghostty PTY and fall back to the TTY preserved with - /// the transfer while the live surface is being reattached. + /// terminal's current Ghostty PTY and include a fresh reported TTY as the + /// nested-PTY fallback. var localAgentDeliveryTTYDevices: [(surfaceId: UUID, ttyDevice: Int64)] { - panels.compactMap { panelId, panel in + panels.flatMap { panelId, panel -> [(surfaceId: UUID, ttyDevice: Int64)] in guard let terminal = panel as? TerminalPanel, detachedSurfaceTransfersByPanelId[panelId]?.isRemoteTerminal != true else { - return nil + return [] } - let liveDevice = terminal.surface.controllingTTYName().flatMap { - CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: $0) + var devices: [Int64] = [] + if let liveDevice = terminal.surface.controllingTTYName().flatMap( + CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) + ) { + devices.append(liveDevice) } - let preservedDevice = detachedSurfaceTransfersByPanelId[panelId]?.ttyName.flatMap { - CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: $0) + if let transfer = detachedSurfaceTransfersByPanelId[panelId], + transfer.ttyNameWasReportedByCurrentRuntime, + let reportedDevice = transfer.ttyName.flatMap( + CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) + ), + !devices.contains(reportedDevice) { + devices.append(reportedDevice) } - guard let ttyDevice = liveDevice ?? preservedDevice else { return nil } - return (panelId, ttyDevice) + return devices.map { (panelId, $0) } } } } @@ -197,9 +236,8 @@ extension AppDelegate { var ttyTarget: AgentDeliveryTargetCandidate? if let ttyDevice = identity.ttyDevice { - // TTY device ids are indexed when each surface reports or moves, - // so hook delivery only walks in-memory bindings on MainActor. It - // never stats every live surface while UI work is serialized. + // Query Ghostty's live PTY so shell integration is not required; + // fresh runtime reports remain a nested-PTY fallback. ttyTarget = agentDeliveryTargetMatchingTTYDevice( ttyDevice, surfaceTTYDevices: liveAgentDeliveryTTYBindings() diff --git a/Sources/DockSplitStore+RemoteTerminalLiveness.swift b/Sources/DockSplitStore+RemoteTerminalLiveness.swift index 425c36367176..80e5d702b94f 100644 --- a/Sources/DockSplitStore+RemoteTerminalLiveness.swift +++ b/Sources/DockSplitStore+RemoteTerminalLiveness.swift @@ -108,6 +108,65 @@ extension DockSplitStore { return transfer.sessionRestoreWorkspaceId == presentationWorkspaceID } + static func registerReportedRemoteSurfaceTTYName( + _ ttyName: String, + panelId: UUID, + presentationWorkspaceID: UUID + ) -> Bool { + let owners = liveRemoteTerminalStores( + presentationWorkspaceID: presentationWorkspaceID + ).filter { + $0.ownsRemoteTerminalTransfer( + panelId: panelId, + presentationWorkspaceID: presentationWorkspaceID + ) + } + guard owners.count == 1 else { return false } + return owners[0].registerReportedRemoteSurfaceTTYName( + ttyName, + panelId: panelId, + presentationWorkspaceID: presentationWorkspaceID + ) + } + + func runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: UUID + ) -> [(binding: TerminalCallerTTYBinding, ttyName: String)] { + detachedSurfaceTransfersByPanelId.compactMap { panelId, transfer in + guard panels[panelId] != nil, + transfer.isRemoteTerminal, + transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, + transfer.ttyNameWasReportedByCurrentRuntime, + let ttyName = transfer.ttyName else { + return nil + } + return ( + binding: TerminalCallerTTYBinding( + workspaceId: workspaceId, + surfaceId: panelId + ), + ttyName: ttyName + ) + } + } + + private func registerReportedRemoteSurfaceTTYName( + _ ttyName: String, + panelId: UUID, + presentationWorkspaceID: UUID + ) -> Bool { + guard panels[panelId] != nil, + var transfer = detachedSurfaceTransfersByPanelId[panelId], + transfer.isRemoteTerminal, + transfer.sessionRestoreWorkspaceId == presentationWorkspaceID else { + return false + } + transfer.ttyName = ttyName + transfer.ttyNameWasReportedByCurrentRuntime = true + setDetachedSurfaceTransfer(transfer, forPanelID: panelId) + return true + } + func markRemoteTerminalSessionEnded(panelId: UUID, relayPort: Int?) -> Bool { guard let relayPort, relayPort > 0 else { return false } return markRemoteTerminalSessionEnded( diff --git a/Sources/DockSplitStore+SurfaceTransfer.swift b/Sources/DockSplitStore+SurfaceTransfer.swift index 27613ca4ceb5..b83c382d8293 100644 --- a/Sources/DockSplitStore+SurfaceTransfer.swift +++ b/Sources/DockSplitStore+SurfaceTransfer.swift @@ -276,6 +276,7 @@ extension DockSplitStore { ? preservedTransfer?.directoryDisplayLabel : nil, ttyName: preservedTransfer?.ttyName, + ttyNameWasReportedByCurrentRuntime: preservedTransfer?.ttyNameWasReportedByCurrentRuntime ?? false, cachedTitle: panel.displayTitle, customTitle: preservedTransfer?.customTitle, customTitleSource: preservedTransfer?.customTitleSource, diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index a51ce4ed33e6..e8813b1050fe 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -32,6 +32,16 @@ extension TerminalController { } let validSurfaceIds = Set(tab.panels.keys) tab.pruneSurfaceMetadata(validSurfaceIds: validSurfaceIds) + if let requestedSurfaceID, + tab.isRemoteWorkspace, + !validSurfaceIds.contains(requestedSurfaceID), + DockSplitStore.registerReportedRemoteSurfaceTTYName( + ttyName, + panelId: requestedSurfaceID, + presentationWorkspaceID: workspaceID + ) { + return .recorded(surfaceID: requestedSurfaceID) + } let surfaceId = controlResolveReportedSurfaceId( in: tab, diff --git a/Sources/Workspace+DetachedSurfaceTransfer.swift b/Sources/Workspace+DetachedSurfaceTransfer.swift index 150b8f2ffa6a..5437297d17c7 100644 --- a/Sources/Workspace+DetachedSurfaceTransfer.swift +++ b/Sources/Workspace+DetachedSurfaceTransfer.swift @@ -36,7 +36,8 @@ extension Workspace { let directory: String? let directoryIsTrustedRemoteReport: Bool let directoryDisplayLabel: String? - let ttyName: String? + var ttyName: String? + var ttyNameWasReportedByCurrentRuntime: Bool = false let cachedTitle: String? let customTitle: String? let customTitleSource: Workspace.CustomTitleSource? @@ -89,6 +90,7 @@ extension Workspace { directoryIsTrustedRemoteReport: directoryIsTrustedRemoteReport, directoryDisplayLabel: directoryDisplayLabel, ttyName: ttyName, + ttyNameWasReportedByCurrentRuntime: ttyNameWasReportedByCurrentRuntime, cachedTitle: cachedTitle, customTitle: customTitle, customTitleSource: customTitleSource, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 4fe55760cbf4..fc42fe514bd1 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9620,11 +9620,7 @@ final class Workspace: Identifiable, ObservableObject { } else { panelDirectoryDisplayLabels.removeValue(forKey: detached.panelId) } - if let ttyName = detached.ttyName?.trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty { - surfaceTTYNames[detached.panelId] = ttyName - } else { - surfaceTTYNames.removeValue(forKey: detached.panelId) - } + adoptTransferredSurfaceTTYName(from: detached) syncRemotePortScanTTYs() if let cachedTitle = detached.cachedTitle { panelTitles[detached.panelId] = cachedTitle @@ -12490,6 +12486,7 @@ extension Workspace: BonsplitDelegate { directoryIsTrustedRemoteReport: panelDirectory != nil && remoteDirectoryReportPanelIds.contains(panelId), directoryDisplayLabel: panelDirectoryDisplayLabels[panelId], ttyName: surfaceTTYNames[panelId], + ttyNameWasReportedByCurrentRuntime: surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId), cachedTitle: cachedTitle, customTitle: panelCustomTitles[panelId], customTitleSource: panelCustomTitles[panelId] != nil diff --git a/cmuxTests/AgentNotificationLiveRetargetTests.swift b/cmuxTests/AgentNotificationLiveRetargetTests.swift index 494d9063fc5e..f3063665dfd3 100644 --- a/cmuxTests/AgentNotificationLiveRetargetTests.swift +++ b/cmuxTests/AgentNotificationLiveRetargetTests.swift @@ -513,7 +513,7 @@ extension AgentNotificationRegressionTests { @Test func testTTYDeviceMatchRequiresUniqueSurface() throws { let workspace = Workspace(), panel = try #require(workspace.focusedPanelId) - workspace.surfaceTTYNames[panel] = "/dev/null" + workspace.registerReportedSurfaceTTYName("/dev/null", panelId: panel) #expect(workspace.surfaceTTYDevices[panel] == CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: "/dev/null")) let w1 = UUID(), s1 = UUID(), w2 = UUID(), s2 = UUID() let bindings: [(workspaceId: UUID, surfaceId: UUID, ttyDevice: Int64)] = [ diff --git a/cmuxTests/AgentNotificationMutationBoundaryTests.swift b/cmuxTests/AgentNotificationMutationBoundaryTests.swift index 497c3b1b2e2a..de307e367dcf 100644 --- a/cmuxTests/AgentNotificationMutationBoundaryTests.swift +++ b/cmuxTests/AgentNotificationMutationBoundaryTests.swift @@ -87,7 +87,7 @@ extension AgentNotificationRegressionTests { func localTTYBindingsExcludeRemoteDeviceNamespaces() throws { let workspace = Workspace() let panelId = try #require(workspace.focusedPanelId) - workspace.surfaceTTYNames[panelId] = "/dev/null" + workspace.registerReportedSurfaceTTYName("/dev/null", panelId: panelId) #expect(workspace.localAgentDeliveryTTYDevices.map(\.surfaceId) == [panelId]) workspace.remoteConfiguration = WorkspaceRemoteConfiguration( @@ -155,7 +155,7 @@ extension AgentNotificationRegressionTests { } let dockOwnerId = UUID() let dock = DockSplitStore(workspaceId: dockOwnerId, baseDirectoryProvider: { nil }) - fixture.source.surfaceTTYNames[fixture.panelId] = "/dev/null" + fixture.source.registerReportedSurfaceTTYName("/dev/null", panelId: fixture.panelId) fixture.source.setAgentLifecycle( key: "manual:workspace-loader", panelId: fixture.panelId, From 5db73900a169ac1d18196826c23584b0f9b7987e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 09:01:57 -0700 Subject: [PATCH 17/35] test: cover ended and cached TTY routing --- ...erminalSurfaceCloseConfirmationTests.swift | 36 ++++++++- .../GhosttyRuntimeTestStubs.c | 7 ++ .../include/GhosttyRuntimeTestStubs.h | 1 + cmuxTests/AgentDeliveryTTYBindingTests.swift | 74 ++++++++++++++++++- 4 files changed, 114 insertions(+), 4 deletions(-) diff --git a/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift b/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift index 589c7983d632..9decc2d9b318 100644 --- a/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift +++ b/Packages/macOS/CmuxTerminal/Tests/CmuxTerminalTests/TerminalSurfaceCloseConfirmationTests.swift @@ -9,8 +9,37 @@ private func resetGhosttyRuntimeStubs() @_silgen_name("cmux_test_ghostty_runtime_stubs_set_close_state") private func setGhosttyCloseState(_ needsConfirm: Bool, _ foregroundPID: UInt64, _ ttyName: UnsafePointer?) +@_silgen_name("cmux_test_ghostty_tty_name_call_count") +private func ghosttyTTYNameCallCount() -> UInt32 + @MainActor @Suite(.serialized) struct TerminalSurfaceCloseConfirmationTests { + @Test func controllingTTYNameIsReadOncePerRuntimeLifecycle() { + let registry = FakeSurfaceRegistry() + let surface = makeSurface(registry: registry) + let runtimeSurface = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8) + registry.registerRuntimeSurface(runtimeSurface, ownerId: surface.id) + resetGhosttyRuntimeStubs() + defer { + resetGhosttyRuntimeStubs() + surface.releaseSurfaceForTesting() + runtimeSurface.deallocate() + } + + "/dev/null".withCString { ttyName in + setGhosttyCloseState(false, 0, ttyName) + surface.installRuntimeSurfaceForTesting(runtimeSurface) + + #expect(surface.controllingTTYName() == "/dev/null") + #expect(surface.controllingTTYName() == "/dev/null") + } + + #expect( + ghosttyTTYNameCallCount() == 1, + "PID routing must reuse terminal-lifecycle TTY identity instead of probing every surface" + ) + } + @Test func liveSurfaceWithoutPidOrTtyDoesNotRequireConfirmation() { let surface = makeSurface() let runtimeSurface = fakeRuntimeSurface() @@ -84,7 +113,10 @@ private func setGhosttyCloseState(_ needsConfirm: Bool, _ foregroundPID: UInt64, #expect(reusedPointerLifetime == releasedLifetime &+ 1) } - private func makeSurface(initialCommand: String? = nil) -> TerminalSurface { + private func makeSurface( + initialCommand: String? = nil, + registry: FakeSurfaceRegistry = FakeSurfaceRegistry() + ) -> TerminalSurface { let nativeView = FakeTerminalSurfaceNativeView(frame: NSRect(x: 0, y: 0, width: 800, height: 600)) let paneHost = FakeTerminalSurfacePaneHost(surfaceView: nativeView) return TerminalSurface( @@ -93,7 +125,7 @@ private func setGhosttyCloseState(_ needsConfirm: Bool, _ foregroundPID: UInt64, configTemplate: nil, initialCommand: initialCommand, dependencies: TerminalSurfaceRuntimeDependencies( - registry: FakeSurfaceRegistry(), + registry: registry, engine: FakeTerminalEngine(), viewProvider: FakeTerminalSurfaceViewProvider(surfaceView: nativeView, paneHost: paneHost), spawnPolicy: FakeSpawnPolicyProvider(), diff --git a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c index 359794375f1c..e2d309aff596 100644 --- a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c +++ b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/GhosttyRuntimeTestStubs.c @@ -18,6 +18,7 @@ typedef struct { static bool cmux_test_needs_confirm_quit = false; static uint64_t cmux_test_foreground_pid = 0; static const char* cmux_test_tty_name = NULL; +static uint32_t cmux_test_tty_name_call_count = 0; static void* cmux_test_renderer_realized_target = NULL; static bool cmux_test_renderer_realized_calls[16]; static uint32_t cmux_test_renderer_realized_call_count = 0; @@ -39,6 +40,7 @@ void cmux_test_ghostty_runtime_stubs_reset(void) { cmux_test_needs_confirm_quit = false; cmux_test_foreground_pid = 0; cmux_test_tty_name = NULL; + cmux_test_tty_name_call_count = 0; } void cmux_test_ghostty_renderer_realized_begin(void* surface) { @@ -320,12 +322,17 @@ void ghostty_surface_update_config(void *surface, void *raw_config) { } ghostty_string_s ghostty_surface_tty_name(void *surface) { (void)surface; + cmux_test_tty_name_call_count++; if (cmux_test_tty_name == NULL) { return (ghostty_string_s){0}; } return (ghostty_string_s){.ptr = cmux_test_tty_name, .len = strlen(cmux_test_tty_name), .sentinel = false}; } +uint32_t cmux_test_ghostty_tty_name_call_count(void) { + return cmux_test_tty_name_call_count; +} + bool cmux_test_ghostty_surface_was_updated(void *surface) { return surface == cmux_test_last_updated_surface; } diff --git a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h index 90f9b53cba57..920eaff9c3fa 100644 --- a/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h +++ b/Packages/macOS/CmuxTerminal/Tests/GhosttyRuntimeTestStubs/include/GhosttyRuntimeTestStubs.h @@ -92,6 +92,7 @@ ghostty_string_s ghostty_surface_tty_name(void *surface); void cmux_test_ghostty_runtime_stubs_reset(void); void cmux_test_ghostty_runtime_stubs_set_close_state(bool needs_confirm, uint64_t foreground_pid, const char* tty_name); +uint32_t cmux_test_ghostty_tty_name_call_count(void); void cmux_test_ghostty_renderer_realized_begin(void *surface); void cmux_test_ghostty_renderer_realized_reset(void); uint32_t cmux_test_ghostty_renderer_realized_call_count(void); diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift index 43be732f0287..2885a11939e9 100644 --- a/cmuxTests/AgentDeliveryTTYBindingTests.swift +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -118,6 +118,60 @@ extension AgentNotificationRegressionTests { ) } + @Test("An ended workspace remote terminal cannot resolve a reused TTY") + func endedWorkspaceRemoteTerminalDoesNotResolveReportedTTY() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + workspace.trackRemoteTerminalSurface(panelID) + workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) + #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) + + #expect( + workspace.markRemoteTerminalSessionEnded( + surfaceId: panelID, + relayPort: 64_007 + ) + ) + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") == nil, + "A TTY report from an ended lifecycle must not identify a future remote process" + ) + } + + @Test("An ended Dock remote terminal cannot resolve a reused TTY") + func endedDockRemoteTerminalDoesNotResolveReportedTTY() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/0", panelId: fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + + #expect( + dock.markRemoteTerminalSessionEnded( + panelId: fixture.panelId, + relayPort: 64_007 + ) + ) + + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0" + ) + } + private func moveRemoteSurface(_ fixture: Fixture, into dock: DockSplitStore) throws { let transfer = try #require(fixture.source.detachSurface(panelId: fixture.panelId)) let rootPane = try #require(dock.bonsplitController.allPaneIds.first) @@ -158,14 +212,30 @@ extension AgentNotificationRegressionTests { #expect(target["surface_id"] as? String == expectedSurfaceID.uuidString) } - private func deliveryTargetRemoteConfiguration() -> WorkspaceRemoteConfiguration { + private func assertNoRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .err(let code, _, _) = result else { + Issue.record("Expected ended relay TTY resolution to fail, got \(result)") + return + } + #expect(code == "not_found") + } + + private func deliveryTargetRemoteConfiguration(relayPort: Int? = nil) -> WorkspaceRemoteConfiguration { WorkspaceRemoteConfiguration( destination: "example.invalid", port: nil, identityFile: nil, sshOptions: [], localProxyPort: nil, - relayPort: nil, + relayPort: relayPort, relayID: nil, relayToken: nil, localSocketPath: nil, From c32a53fcf192e326f36e000ab3a95c250ec9bd25 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 09:16:46 -0700 Subject: [PATCH 18/35] fix: retire stale TTY lifecycle evidence --- .../Surface/TerminalSurface+Debug.swift | 1 + .../Surface/TerminalSurface+ProcessInfo.swift | 55 ++++++++++++++++--- .../TerminalSurface+RuntimeLifecycle.swift | 1 + .../Surface/TerminalSurface.swift | 4 ++ Sources/AgentDeliveryTargetResolution.swift | 20 ++++--- ...ockSplitStore+RemoteTerminalLiveness.swift | 9 ++- .../Workspace+RemoteTerminalLiveness.swift | 4 ++ Sources/Workspace.swift | 8 ++- cmuxTests/AgentDeliveryTTYBindingTests.swift | 1 + .../AgentNotificationLiveRetargetTests.swift | 2 + 10 files changed, 85 insertions(+), 20 deletions(-) diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift index 9caaa0de3fbd..98ecc8a1e5e6 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Debug.swift @@ -235,6 +235,7 @@ extension TerminalSurface { surface = runtimeSurface portalLifecycleState = .live runtimeSurfaceFreedOutOfBandForTesting = false + cacheControllingTTYIdentity(for: runtimeSurface) installFontSizeActionObservation( on: runtimeSurface, callbackContext: callbackContext diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift index d2a58706afaf..1cf99e9971ea 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+ProcessInfo.swift @@ -1,3 +1,4 @@ +internal import Darwin public import Foundation public import GhosttyKit @@ -16,22 +17,58 @@ extension TerminalSurface { return pid > 0 ? Int(pid) : nil } - /// The controlling TTY device name (e.g. `/dev/ttys003`) for this surface's - /// PTY, or `nil` when there is no live runtime surface or the runtime has no - /// tty yet. Every process in the pane (shell + descendants + background jobs) - /// shares this controlling tty, so it is the attribution key the guardrail - /// sums process-tree memory by. + /// The controlling TTY device name (e.g. `/dev/ttys003`) captured for this + /// surface's current PTY lifecycle, or `nil` when there is no live runtime + /// surface or the runtime has no TTY. Every process in the pane (shell, + /// descendants, and background jobs) shares this controlling TTY. @MainActor public func controllingTTYName() -> String? { - guard let surface = liveSurfaceForGhosttyAccess(reason: "memGuard.ttyName") else { + guard let surface = liveSurfaceForGhosttyAccess(reason: "processInfo.ttyName") else { return nil } + if runtimeControllingTTYName == nil { + // Ghostty starts its PTY on the IO thread, so the eager lookup at + // runtime installation can race before the device exists. Retry + // only until the lifecycle acquires a TTY, then serve the cache. + cacheControllingTTYIdentity(for: surface) + } + return runtimeControllingTTYName + } + + /// The character-device identifier captured for the current PTY lifecycle. + /// + /// The identifier is resolved once Ghostty's asynchronous PTY startup makes + /// it available, so delivery-time process routing can compare devices without + /// repeatedly allocating a TTY name or accessing the filesystem. + @MainActor + public var controllingTTYDeviceIdentifier: Int64? { + guard let surface = liveSurfaceForGhosttyAccess(reason: "processInfo.ttyDevice") else { + return nil + } + if runtimeControllingTTYName == nil { + cacheControllingTTYIdentity(for: surface) + } + return runtimeControllingTTYDeviceIdentifier + } + + @MainActor + func cacheControllingTTYIdentity(for surface: ghostty_surface_t) { + guard runtimeControllingTTYName == nil else { return } let exported = ghostty_surface_tty_name(surface) defer { ghostty_string_free(exported) } - guard let ptr = exported.ptr, exported.len > 0 else { return nil } + guard let ptr = exported.ptr, exported.len > 0 else { return } let data = Data(bytes: ptr, count: Int(exported.len)) - guard let decoded = String(data: data, encoding: .utf8) else { return nil } + guard let decoded = String(data: data, encoding: .utf8) else { return } let name = decoded.trimmingCharacters(in: .whitespacesAndNewlines) - return name.isEmpty ? nil : name + guard !name.isEmpty else { return } + runtimeControllingTTYName = name + runtimeControllingTTYDeviceIdentifier = ttyDeviceIdentifier(for: name) + } + + private func ttyDeviceIdentifier(for ttyName: String) -> Int64? { + let path = ttyName.hasPrefix("/dev/") ? ttyName : "/dev/\(ttyName)" + var statInfo = stat() + guard stat(path, &statInfo) == 0 else { return nil } + return Int64(statInfo.st_rdev) } } diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift index 7e66bed32266..c3a1f3b6766c 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+RuntimeLifecycle.swift @@ -697,6 +697,7 @@ extension TerminalSurface { requiresRestoreSpawnPacing = false } registry.registerRuntimeSurface(createdSurface, ownerId: id) + cacheControllingTTYIdentity(for: createdSurface) recordRuntimeSurfaceCreation() // Install the shared PTY tee so output consumers receive every byte // the read thread produces, in order, before the VT parser runs. diff --git a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift index b4807d1d8c8c..5456f35f8673 100644 --- a/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift +++ b/Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface.swift @@ -57,12 +57,16 @@ public final class TerminalSurface: Identifiable, ObservableObject { public typealias CodexCommandShim = TerminalSurfaceCodexCommandShim public typealias CmuxContextEnvironment = TerminalSurfaceCmuxContextEnvironment private var runtimeSurface: ghostty_surface_t? + var runtimeControllingTTYName: String? + var runtimeControllingTTYDeviceIdentifier: Int64? /// The live runtime surface pointer, or nil before creation/after teardown. public internal(set) var surface: ghostty_surface_t? { get { runtimeSurface } set { guard runtimeSurface != newValue else { return } runtimeSurface = newValue + runtimeControllingTTYName = nil + runtimeControllingTTYDeviceIdentifier = nil runtimeSurfaceGeneration &+= 1 } } diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index 779275f597b8..f04d26823407 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -114,6 +114,11 @@ extension Workspace { /// device index through ``surfaceTTYNames``. func restorePersistedSurfaceTTYName(_ ttyName: String?, panelId: UUID) { surfaceRegistry.surfaceTTYNames[panelId] = ttyName + invalidateReportedSurfaceTTYRuntime(panelId: panelId) + } + + /// Discards live-process evidence while preserving display-only TTY metadata. + func invalidateReportedSurfaceTTYRuntime(panelId: UUID) { surfaceRegistry.surfaceTTYDevices.removeValue(forKey: panelId) surfaceRegistry.runtimeReportedTTYSurfaceIDs.remove(panelId) } @@ -139,7 +144,8 @@ extension Workspace { var candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceId -> (binding: TerminalCallerTTYBinding, ttyName: String)? in - guard panels[surfaceId] != nil, + guard activeRemoteTerminalSurfaceIds.contains(surfaceId), + panels[surfaceId] != nil, let reportedTTYName = surfaceRegistry.surfaceTTYNames[surfaceId] else { return nil } @@ -172,9 +178,7 @@ extension Workspace { return [] } var devices: [Int64] = [] - if let liveDevice = terminal.surface.controllingTTYName().flatMap( - CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) - ) { + if let liveDevice = terminal.surface.controllingTTYDeviceIdentifier { devices.append(liveDevice) } if surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId), @@ -202,9 +206,7 @@ extension DockSplitStore { return [] } var devices: [Int64] = [] - if let liveDevice = terminal.surface.controllingTTYName().flatMap( - CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) - ) { + if let liveDevice = terminal.surface.controllingTTYDeviceIdentifier { devices.append(liveDevice) } if let transfer = detachedSurfaceTransfersByPanelId[panelId], @@ -236,8 +238,8 @@ extension AppDelegate { var ttyTarget: AgentDeliveryTargetCandidate? if let ttyDevice = identity.ttyDevice { - // Query Ghostty's live PTY so shell integration is not required; - // fresh runtime reports remain a nested-PTY fallback. + // Read the lifecycle-cached Ghostty PTY so shell integration is not + // required; fresh runtime reports remain a nested-PTY fallback. ttyTarget = agentDeliveryTargetMatchingTTYDevice( ttyDevice, surfaceTTYDevices: liveAgentDeliveryTTYBindings() diff --git a/Sources/DockSplitStore+RemoteTerminalLiveness.swift b/Sources/DockSplitStore+RemoteTerminalLiveness.swift index 80e5d702b94f..271d567b0fbf 100644 --- a/Sources/DockSplitStore+RemoteTerminalLiveness.swift +++ b/Sources/DockSplitStore+RemoteTerminalLiveness.swift @@ -63,9 +63,13 @@ extension DockSplitStore { transfer.remoteTerminalLifecycleID == terminalLifecycleID { return false } + let beginsNewLifecycle = transfer.remoteTerminalLifecycleID != terminalLifecycleID transfer.remoteTerminalSessionPhase = .launching transfer.remoteTerminalLifecycleID = terminalLifecycleID transfer.remoteTerminalAttemptID = attemptID + if beginsNewLifecycle { + transfer.ttyNameWasReportedByCurrentRuntime = false + } setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true } @@ -136,6 +140,7 @@ extension DockSplitStore { guard panels[panelId] != nil, transfer.isRemoteTerminal, transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, + transfer.remoteTerminalSessionPhase != .ended, transfer.ttyNameWasReportedByCurrentRuntime, let ttyName = transfer.ttyName else { return nil @@ -158,7 +163,8 @@ extension DockSplitStore { guard panels[panelId] != nil, var transfer = detachedSurfaceTransfersByPanelId[panelId], transfer.isRemoteTerminal, - transfer.sessionRestoreWorkspaceId == presentationWorkspaceID else { + transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, + transfer.remoteTerminalSessionPhase != .ended else { return false } transfer.ttyName = ttyName @@ -211,6 +217,7 @@ extension DockSplitStore { transfer.remoteTerminalLifecycleID = terminalLifecycleID ?? transfer.remoteTerminalLifecycleID transfer.remoteTerminalAttemptID = nil + transfer.ttyNameWasReportedByCurrentRuntime = false setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true } diff --git a/Sources/Workspace+RemoteTerminalLiveness.swift b/Sources/Workspace+RemoteTerminalLiveness.swift index 6171de456d85..eee9bb6c7eb1 100644 --- a/Sources/Workspace+RemoteTerminalLiveness.swift +++ b/Sources/Workspace+RemoteTerminalLiveness.swift @@ -94,6 +94,10 @@ extension Workspace { if terminalLifecycleID != nil { endedRemoteTerminalLifecycleIDsBySurfaceId.removeValue(forKey: surfaceId) } + let previousState = remoteTerminalSessionStatesBySurfaceId[surfaceId] + if previousState == nil || previousState?.terminalLifecycleID != terminalLifecycleID { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + } remoteTerminalSessionStatesBySurfaceId[surfaceId] = WorkspaceRemoteTerminalSessionState( phase: .launching, authority: authority, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index fc42fe514bd1..36959dd2f88b 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -6690,6 +6690,7 @@ final class Workspace: Identifiable, ObservableObject { endedPendingConnection = nil } if cleanupTransferredRemoteConnectionIfNeeded(surfaceId: surfaceId, relayPort: relayPort) { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) return true } guard let configuration = remoteConfiguration, @@ -6699,8 +6700,13 @@ final class Workspace: Identifiable, ObservableObject { configuration: configuration, allowUntracked: allowUntracked ) else { - return endedPendingConnection != nil || recordedLifecycleTombstone + let didEnd = endedPendingConnection != nil || recordedLifecycleTombstone + if didEnd { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + } + return didEnd } + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) let preservesRemotePTYSession = configuration.preserveAfterTerminalExit let previousPresentedDirectory = presentedCurrentDirectory if !preservesRemotePTYSession { diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift index 2885a11939e9..bda36c467361 100644 --- a/cmuxTests/AgentDeliveryTTYBindingTests.swift +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -52,6 +52,7 @@ extension AgentNotificationRegressionTests { let workspace = Workspace() let panelID = try #require(workspace.focusedPanelId) workspace.remoteConfiguration = deliveryTargetRemoteConfiguration() + workspace.trackRemoteTerminalSurface(panelID) workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) diff --git a/cmuxTests/AgentNotificationLiveRetargetTests.swift b/cmuxTests/AgentNotificationLiveRetargetTests.swift index f3063665dfd3..d58340a1d903 100644 --- a/cmuxTests/AgentNotificationLiveRetargetTests.swift +++ b/cmuxTests/AgentNotificationLiveRetargetTests.swift @@ -196,6 +196,8 @@ extension AgentNotificationRegressionTests { fixture.claimedWorkspace.remoteConfiguration = remoteConfiguration fixture.owningWorkspace.remoteConfiguration = remoteConfiguration let siblingPanelID = try #require(fixture.claimedWorkspace.focusedPanelId) + fixture.claimedWorkspace.trackRemoteTerminalSurface(siblingPanelID) + fixture.owningWorkspace.trackRemoteTerminalSurface(fixture.panelId) #expect(TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.claimedWorkspace.id, requestedSurfaceID: siblingPanelID, From d2759b3b24ed3f234eabac8365c4fd3f114b8b3b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 09:45:56 -0700 Subject: [PATCH 19/35] test: cover fail-closed restore and reconnect routing --- cmuxTests/AgentDeliveryTTYBindingTests.swift | 79 +++++++++++++++++++ .../CMUXCLIErrorOutputRegressionTests.swift | 70 +++++++--------- 2 files changed, 108 insertions(+), 41 deletions(-) diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift index bda36c467361..5cc87cd662cf 100644 --- a/cmuxTests/AgentDeliveryTTYBindingTests.swift +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -173,6 +173,85 @@ extension AgentNotificationRegressionTests { ) } + @Test("A workspace reconnect invalidates the previous attempt's TTY report") + func workspaceReconnectInvalidatesReportedTTY() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + let terminal = try #require(workspace.panels[panelID] as? TerminalPanel) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration() + workspace.trackRemoteTerminalSurface(panelID) + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + workspace.registerReportedSurfaceTTYName("pts/0", panelId: panelID) + #expect(workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") != nil) + + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/0") == nil, + "A new attach attempt must wait for its own report_tty before becoming routable" + ) + } + + @Test("A Dock reconnect invalidates the previous attempt's TTY report") + func dockReconnectInvalidatesReportedTTY() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/0", panelId: fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + #expect( + dock.markRemoteTerminalSessionLaunching( + panelId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/0" + ) == .recorded(surfaceID: fixture.panelId) + ) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + + #expect( + dock.markRemoteTerminalSessionLaunching( + panelId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/0" + ) + } + private func moveRemoteSurface(_ fixture: Fixture, into dock: DockSplitStore) throws { let transfer = try #require(fixture.source.detachSurface(panelId: fixture.panelId)) let rootPane = try #require(dock.bonsplitController.allPaneIds.first) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index 547ad1f2f3e4..b03587e78797 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -710,37 +710,18 @@ import Testing #expect(restoreParams["surface_id"] as? String != staleTTYSurfaceID) } - @Test func testRestoreRetriesUntilFreshTTYRegistrationIsVisible() throws { + @Test func testRelayRestoreFailsClosedOnFirstMissingTTYTarget() throws { let cliPath = try bundledCLIPath() let checkpointID = "pi-\(UUID().uuidString.lowercased())" let workspaceID = UUID().uuidString - let surfaceID = UUID().uuidString let notFoundResponse = try jsonErrorResponse( code: "not_found", message: "No live delivery target" ) - let liveTargetResponse = try restoreResponse( - result: [:], - workspaceID: workspaceID, - surfaceID: surfaceID - ) - let recordResponse = try restoreResponse(result: [ - "restore_record": [ - "mode": "direct", - "kind": "pi", - "checkpoint_id": checkpointID, - "environment": [:], - "launch_command": [ - "arguments": ["/usr/bin/true"], - "executable_path": "/usr/bin/true", - ], - "prepared_arguments": ["/usr/bin/true"], - ], - ]) - let socketPath = "/tmp/cmux-restore-registration-\(UUID().uuidString.prefix(8)).sock" - let responder = try UnixSocketResponder( - path: socketPath, - responses: [notFoundResponse, liveTargetResponse, recordResponse] + let relayID = "relay-\(UUID().uuidString.lowercased())" + let responder = try RelaySocketResponder( + relayID: relayID, + responses: [notFoundResponse] ) defer { responder.stop() } var environment = ProcessInfo.processInfo.environment @@ -748,7 +729,11 @@ import Testing environment.removeValue(forKey: key) } environment["CMUX_CLI_SENTRY_DISABLED"] = "1" - environment["CMUX_SOCKET_PATH"] = socketPath + environment["CMUX_SOCKET_PATH"] = responder.endpoint + environment["CMUX_RELAY_ID"] = relayID + environment["CMUX_RELAY_TOKEN"] = String(repeating: "11", count: 32) + environment["CMUX_WORKSPACE_ID"] = workspaceID + environment["CMUX_CLI_TTY_NAME"] = "0" let result = runProcess( executablePath: cliPath, @@ -758,23 +743,24 @@ import Testing ) #expect(!result.timedOut, Comment(rawValue: result.stdout)) - #expect(result.status == 0, Comment(rawValue: result.stdout)) + #expect(result.status != 0, Comment(rawValue: result.stdout)) + #expect( + result.stdout.contains("the current cmux surface could not be identified"), + Comment(rawValue: result.stdout) + ) let requests = try responder.receivedRequests.map { request in let data = try #require(request.data(using: .utf8)) return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) } - #expect(requests.compactMap { $0["method"] as? String } == [ - "agent.resolve_delivery_target", - "agent.resolve_delivery_target", - "surface.resume.get", - ]) - for request in requests.prefix(2) { - let params = try #require(request["params"] as? [String: Any]) - #expect((params["pid"] as? Int).map { $0 > 0 } == true) - #expect(params["pid_resolution"] as? String == "controlling_tty") - } - let restoreParams = try #require(requests.last?["params"] as? [String: Any]) - #expect(restoreParams["surface_id"] as? String == surfaceID) + #expect( + requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target" + ] + ) + let params = try #require(requests.first?["params"] as? [String: Any]) + #expect(params["tty_name"] as? String == "0") + #expect(params["tty_resolution"] as? String == "reported_tty") + #expect(params["workspace_id"] as? String == workspaceID) } @Test func testRestoreFailsClosedWhenLiveProcessTargetIsNotFound() throws { @@ -817,9 +803,11 @@ import Testing let data = try #require(request.data(using: .utf8)) return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) } - let methods = requests.compactMap { $0["method"] as? String } - #expect(methods.count > 1) - #expect(methods.allSatisfy { $0 == "agent.resolve_delivery_target" }) + #expect( + requests.compactMap { $0["method"] as? String } == [ + "agent.resolve_delivery_target" + ] + ) } @Test func testRestoreUsesUniqueTTYBindingWhenLiveTargetMethodIsUnsupported() throws { From 0a9d22111e811a30000c2c91ff6ddacbf83d2475 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 09:49:27 -0700 Subject: [PATCH 20/35] fix: make restore routing readiness authoritative --- CLI/CMUXCLI+Restore.swift | 164 ++++++++---------- ...ockSplitStore+RemoteTerminalLiveness.swift | 6 +- .../Workspace+RemoteTerminalLiveness.swift | 3 + 3 files changed, 80 insertions(+), 93 deletions(-) diff --git a/CLI/CMUXCLI+Restore.swift b/CLI/CMUXCLI+Restore.swift index f2ed9e39db37..d06160baca19 100644 --- a/CLI/CMUXCLI+Restore.swift +++ b/CLI/CMUXCLI+Restore.swift @@ -194,53 +194,42 @@ extension CMUXCLI { } let resolution = AgentProcessBindingResolution.controllingTTY.rawValue - let retryDelays: [useconds_t] = [25_000, 50_000, 100_000, 200_000, 400_000] - var retryIndex = 0 - while true { - do { - let payload = try client.sendV2( - method: "agent.resolve_delivery_target", - params: [ - "pid": Int(ProcessInfo.processInfo.processIdentifier), - "pid_resolution": resolution, - ] + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: [ + "pid": Int(ProcessInfo.processInfo.processIdentifier), + "pid_resolution": resolution, + ] + ) + guard payload["source"] as? String == "pid", + payload["pid_resolution"] as? String == resolution, + let workspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(workspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": + // These protocol replies were consumed in full, so the socket + // remains synchronized for the legacy discovery request. + return legacyRestoreSurfaceID( + client: client, + workspaceID: nil ) - guard payload["source"] as? String == "pid", - payload["pid_resolution"] as? String == resolution, - let workspaceID = normalizedHandleValue(payload["workspace_id"] as? String), - isUUID(workspaceID), - let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), - isUUID(surfaceID) else { - throw currentRestoreSurfaceUnknownError() - } - return surfaceID - } catch let error as CLIError { - switch error.v2Code { - case "not_found" where retryIndex < retryDelays.count: - // Local shell integration registers its TTY in a background - // child. A complete `not_found` reply leaves this socket - // synchronized, so briefly wait for that registration and - // retry without trusting persisted or ambient surface ids. - usleep(retryDelays[retryIndex]) - retryIndex += 1 - case "not_found": - client.close() - throw currentRestoreSurfaceUnknownError() - case "method_not_found", "unrecognized_method": - // These protocol replies were consumed in full, so the socket - // remains synchronized for the legacy discovery request. - return legacyRestoreSurfaceID( - client: client, - workspaceID: nil - ) - default: - client.close() - throw error - } - } catch { + default: client.close() throw error } + } catch { + client.close() + throw error } } @@ -265,58 +254,51 @@ extension CMUXCLI { params["workspace_id"] = workspaceID } - let retryDelays: [useconds_t] = [25_000, 50_000, 100_000, 200_000, 400_000] - var retryIndex = 0 - while true { - do { - let payload = try client.sendV2( - method: "agent.resolve_delivery_target", - params: params + do { + let payload = try client.sendV2( + method: "agent.resolve_delivery_target", + params: params + ) + if payload["source"] as? String == "workspace", + payload["surface_id"] == nil || payload["surface_id"] is NSNull, + let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(resolvedWorkspaceID) { + // Previous app versions ignore the TTY probe and resolve + // only workspace_id. Use their alias-rewritten result to + // scope the legacy terminal list, not the stale remote + // shell environment value that produced the request. + return legacyRestoreSurfaceID( + client: client, + workspaceID: resolvedWorkspaceID ) - if payload["source"] as? String == "workspace", - payload["surface_id"] == nil || payload["surface_id"] is NSNull, - let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), - isUUID(resolvedWorkspaceID) { - // Previous app versions ignore the TTY probe and resolve - // only workspace_id. Use their alias-rewritten result to - // scope the legacy terminal list, not the stale remote - // shell environment value that produced the request. - return legacyRestoreSurfaceID( - client: client, - workspaceID: resolvedWorkspaceID - ) - } - guard payload["source"] as? String == "tty", - payload["tty_resolution"] as? String == resolution, - let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), - isUUID(resolvedWorkspaceID), - let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), - isUUID(surfaceID) else { - throw currentRestoreSurfaceUnknownError() - } - return surfaceID - } catch let error as CLIError { - switch error.v2Code { - case "not_found" where retryIndex < retryDelays.count: - usleep(retryDelays[retryIndex]) - retryIndex += 1 - case "not_found": - client.close() - throw currentRestoreSurfaceUnknownError() - case "method_not_found", "unrecognized_method": - guard let workspaceID, isUUID(workspaceID) else { return nil } - return legacyRestoreSurfaceID( - client: client, - workspaceID: workspaceID - ) - default: - client.close() - throw error - } - } catch { + } + guard payload["source"] as? String == "tty", + payload["tty_resolution"] as? String == resolution, + let resolvedWorkspaceID = normalizedHandleValue(payload["workspace_id"] as? String), + isUUID(resolvedWorkspaceID), + let surfaceID = normalizedHandleValue(payload["surface_id"] as? String), + isUUID(surfaceID) else { + throw currentRestoreSurfaceUnknownError() + } + return surfaceID + } catch let error as CLIError { + switch error.v2Code { + case "not_found": + client.close() + throw currentRestoreSurfaceUnknownError() + case "method_not_found", "unrecognized_method": + guard let workspaceID, isUUID(workspaceID) else { return nil } + return legacyRestoreSurfaceID( + client: client, + workspaceID: workspaceID + ) + default: client.close() throw error } + } catch { + client.close() + throw error } } diff --git a/Sources/DockSplitStore+RemoteTerminalLiveness.swift b/Sources/DockSplitStore+RemoteTerminalLiveness.swift index 271d567b0fbf..27754d509b69 100644 --- a/Sources/DockSplitStore+RemoteTerminalLiveness.swift +++ b/Sources/DockSplitStore+RemoteTerminalLiveness.swift @@ -63,11 +63,13 @@ extension DockSplitStore { transfer.remoteTerminalLifecycleID == terminalLifecycleID { return false } - let beginsNewLifecycle = transfer.remoteTerminalLifecycleID != terminalLifecycleID + let beginsNewRuntime = + transfer.remoteTerminalLifecycleID != terminalLifecycleID || + transfer.remoteTerminalAttemptID != attemptID transfer.remoteTerminalSessionPhase = .launching transfer.remoteTerminalLifecycleID = terminalLifecycleID transfer.remoteTerminalAttemptID = attemptID - if beginsNewLifecycle { + if beginsNewRuntime { transfer.ttyNameWasReportedByCurrentRuntime = false } setDetachedSurfaceTransfer(transfer, forPanelID: panelId) diff --git a/Sources/Workspace+RemoteTerminalLiveness.swift b/Sources/Workspace+RemoteTerminalLiveness.swift index eee9bb6c7eb1..f666c6c55597 100644 --- a/Sources/Workspace+RemoteTerminalLiveness.swift +++ b/Sources/Workspace+RemoteTerminalLiveness.swift @@ -117,6 +117,9 @@ extension Workspace { return false } endedRemoteTerminalLifecycleIDsBySurfaceId.removeValue(forKey: surfaceId) + if remoteTerminalAttemptIDsBySurfaceId[surfaceId] != attemptID { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + } remoteTerminalAttemptIDsBySurfaceId[surfaceId] = attemptID markRemoteTerminalSessionLaunching(surfaceId: surfaceId) applyRemoteTerminalLaunchingPresentation() From 2c625bde77f290d5830af1b4b24f4fc9cc113f36 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 10:06:22 -0700 Subject: [PATCH 21/35] test: cover transferred and persistent TTY routing --- cmuxTests/AgentDeliveryTTYBindingTests.swift | 100 ++++++++++++++++++- 1 file changed, 98 insertions(+), 2 deletions(-) diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift index 5cc87cd662cf..3a324917ced4 100644 --- a/cmuxTests/AgentDeliveryTTYBindingTests.swift +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -92,6 +92,26 @@ extension AgentNotificationRegressionTests { ) } + @Test("Relay TTY resolution follows a freshly reported surface into another workspace") + func relayTTYResolutionFollowsFreshReportIntoWorkspace() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let configuration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + fixture.source.remoteConfiguration = configuration + fixture.destination.remoteConfiguration = configuration + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/4", panelId: fixture.panelId) + + try movePanel(fixture) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.destination.id, + ttyName: "pts/4", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + } + @Test("A runtime TTY report refreshes a remote surface already in a Dock") func runtimeTTYReportRefreshesRemoteSurfaceAlreadyInDock() throws { let fixture = try makeFixture() @@ -204,6 +224,38 @@ extension AgentNotificationRegressionTests { ) } + @Test("A persistent workspace bridge retry preserves the remote PTY's TTY report") + func persistentWorkspaceRetryPreservesReportedTTY() throws { + let workspace = Workspace() + let panelID = try #require(workspace.focusedPanelId) + let terminal = try #require(workspace.panels[panelID] as? TerminalPanel) + workspace.remoteConfiguration = deliveryTargetRemoteConfiguration( + preserveAfterTerminalExit: true + ) + workspace.trackRemoteTerminalSurface(panelID) + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + workspace.registerReportedSurfaceTTYName("pts/5", panelId: panelID) + + #expect( + workspace.markRemoteTerminalSessionLaunching( + surfaceId: panelID, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + #expect( + workspace.agentDeliveryTarget(forReportedTTYName: "pts/5") != nil, + "A bridge retry for the same persistent PTY must keep its report-once shell proof" + ) + } + @Test("A Dock reconnect invalidates the previous attempt's TTY report") func dockReconnectInvalidatesReportedTTY() throws { let fixture = try makeFixture() @@ -252,6 +304,45 @@ extension AgentNotificationRegressionTests { ) } + @Test("A persistent Dock bridge retry preserves the remote PTY's TTY report") + func persistentDockRetryPreservesReportedTTY() throws { + let fixture = try makeFixture() + let dock = DockSplitStore(workspaceId: UUID(), baseDirectoryProvider: { nil }) + defer { + dock.closeAllPanels() + fixture.restore() + } + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration( + preserveAfterTerminalExit: true + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect( + fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + fixture.source.registerReportedSurfaceTTYName("pts/6", panelId: fixture.panelId) + try moveRemoteSurface(fixture, into: dock) + + #expect( + dock.markRemoteTerminalSessionLaunching( + panelId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/6", + expectedWorkspaceID: dock.workspaceId, + expectedSurfaceID: fixture.panelId + ) + } + private func moveRemoteSurface(_ fixture: Fixture, into dock: DockSplitStore) throws { let transfer = try #require(fixture.source.detachSurface(panelId: fixture.panelId)) let rootPane = try #require(dock.bonsplitController.allPaneIds.first) @@ -308,7 +399,10 @@ extension AgentNotificationRegressionTests { #expect(code == "not_found") } - private func deliveryTargetRemoteConfiguration(relayPort: Int? = nil) -> WorkspaceRemoteConfiguration { + private func deliveryTargetRemoteConfiguration( + relayPort: Int? = nil, + preserveAfterTerminalExit: Bool = false + ) -> WorkspaceRemoteConfiguration { WorkspaceRemoteConfiguration( destination: "example.invalid", port: nil, @@ -319,7 +413,9 @@ extension AgentNotificationRegressionTests { relayID: nil, relayToken: nil, localSocketPath: nil, - terminalStartupCommand: nil + terminalStartupCommand: nil, + preserveAfterTerminalExit: preserveAfterTerminalExit, + persistentDaemonSlot: preserveAfterTerminalExit ? "delivery-target-test" : nil ) } } From 413d5a487d8b97129fb75a0db1bf88c20ae75a26 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 10:09:53 -0700 Subject: [PATCH 22/35] fix: preserve live TTY proof across bridge retries --- Sources/AgentDeliveryTargetResolution.swift | 8 ++++++++ Sources/DockSplitStore+RemoteTerminalLiveness.swift | 3 ++- Sources/Workspace+RemoteTerminalLiveness.swift | 8 +++++++- Sources/Workspace.swift | 1 + 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index f04d26823407..e59bda2b30a4 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -136,6 +136,14 @@ extension Workspace { } } + func restoreTransferredSurfaceTTYRuntimeProofIfNeeded(from transfer: DetachedSurfaceTransfer) { + guard transfer.ttyNameWasReportedByCurrentRuntime, + !surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(transfer.panelId) else { + return + } + adoptTransferredSurfaceTTYName(from: transfer) + } + /// Resolves a remote caller only from a TTY report observed in this app /// runtime. TTY basenames are unique only inside one authenticated remote /// workspace because separate hosts commonly reuse `/dev/pts/0`. diff --git a/Sources/DockSplitStore+RemoteTerminalLiveness.swift b/Sources/DockSplitStore+RemoteTerminalLiveness.swift index 27754d509b69..b6d1f840fdca 100644 --- a/Sources/DockSplitStore+RemoteTerminalLiveness.swift +++ b/Sources/DockSplitStore+RemoteTerminalLiveness.swift @@ -65,7 +65,8 @@ extension DockSplitStore { } let beginsNewRuntime = transfer.remoteTerminalLifecycleID != terminalLifecycleID || - transfer.remoteTerminalAttemptID != attemptID + (transfer.remoteTerminalAttemptID != attemptID && + transfer.remoteTerminalAuthority?.preservesRemotePTYAcrossAttachAttempts != true) transfer.remoteTerminalSessionPhase = .launching transfer.remoteTerminalLifecycleID = terminalLifecycleID transfer.remoteTerminalAttemptID = attemptID diff --git a/Sources/Workspace+RemoteTerminalLiveness.swift b/Sources/Workspace+RemoteTerminalLiveness.swift index f666c6c55597..e9eb6b85e670 100644 --- a/Sources/Workspace+RemoteTerminalLiveness.swift +++ b/Sources/Workspace+RemoteTerminalLiveness.swift @@ -14,6 +14,11 @@ enum WorkspaceRemoteTerminalAuthority: Equatable, Sendable { case relayPort(Int) case persistentTransport(String) + var preservesRemotePTYAcrossAttachAttempts: Bool { + if case .persistentTransport = self { return true } + return false + } + init?(configuration: WorkspaceRemoteConfiguration) { if configuration.preserveAfterTerminalExit { self = .persistentTransport(configuration.proxyBrokerTransportKey) @@ -117,7 +122,8 @@ extension Workspace { return false } endedRemoteTerminalLifecycleIDsBySurfaceId.removeValue(forKey: surfaceId) - if remoteTerminalAttemptIDsBySurfaceId[surfaceId] != attemptID { + if remoteTerminalAttemptIDsBySurfaceId[surfaceId] != attemptID, + remoteConfiguration?.preserveAfterTerminalExit != true { invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) } remoteTerminalAttemptIDsBySurfaceId[surfaceId] = attemptID diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 36959dd2f88b..239f87806018 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9806,6 +9806,7 @@ final class Workspace: Identifiable, ObservableObject { ) } } + restoreTransferredSurfaceTTYRuntimeProofIfNeeded(from: detached) if let cleanupConfiguration = detached.remoteCleanupConfiguration { if didAdoptWorkspaceRemoteTracking { transferredRemoteCleanupConfigurationsByPanelId.removeValue(forKey: detached.panelId) From 942469d093003e7e5b0b7660f24441dacf509e5d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 10:26:12 -0700 Subject: [PATCH 23/35] test: cover relay restore after new workspace move --- cmuxTests/AgentDeliveryTTYBindingTests.swift | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift index 3a324917ced4..e7db90f12e25 100644 --- a/cmuxTests/AgentDeliveryTTYBindingTests.swift +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -112,6 +112,42 @@ extension AgentNotificationRegressionTests { ) } + @Test("Relay TTY resolution follows a surface into a newly created ordinary workspace") + func relayTTYResolutionFollowsSurfaceIntoNewOrdinaryWorkspace() throws { + let fixture = try makeFixture() + var destinationWorkspaceID: UUID? + defer { + if let destinationWorkspaceID, + let destination = fixture.manager.tabs.first(where: { $0.id == destinationWorkspaceID }) { + fixture.manager.closeWorkspace(destination) + } + fixture.restore() + } + fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration(relayPort: 64_007) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/7", panelId: fixture.panelId) + let paneID = try #require(fixture.source.bonsplitController.allPaneIds.first) + _ = try #require(fixture.source.newTerminalSurface(inPane: paneID, focus: false)) + + let move = try #require(fixture.appDelegate.moveSurfaceToNewWorkspace( + panelId: fixture.panelId, + focus: false, + focusWindow: false + )) + destinationWorkspaceID = move.destinationWorkspaceId + let destination = try #require( + fixture.manager.tabs.first(where: { $0.id == move.destinationWorkspaceId }) + ) + #expect(!destination.isRemoteWorkspace) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/7", + expectedWorkspaceID: destination.id, + expectedSurfaceID: fixture.panelId + ) + } + @Test("A runtime TTY report refreshes a remote surface already in a Dock") func runtimeTTYReportRefreshesRemoteSurfaceAlreadyInDock() throws { let fixture = try makeFixture() From ca95cc4185fce813f2188fec1a2ee3cd73d547f9 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 10:38:11 -0700 Subject: [PATCH 24/35] fix: preserve relay routing across workspace moves --- .../Core/Model/SurfaceRegistryModel.swift | 4 + Sources/AgentDeliveryTargetResolution.swift | 41 ++-------- Sources/AgentRelayTTYTargetResolution.swift | 81 +++++++++++++++++++ Sources/Workspace.swift | 17 +++- cmux.xcodeproj/project.pbxproj | 4 + 5 files changed, 112 insertions(+), 35 deletions(-) create mode 100644 Sources/AgentRelayTTYTargetResolution.swift diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift index 0f2b36f9e336..d8de088661cd 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift @@ -55,6 +55,10 @@ public final class SurfaceRegistryModel { /// arrives, including when the current runtime reuses the same name. public var runtimeReportedTTYSurfaceIDs: Set = [] + /// Authenticated remote workspace that originated each live TTY report. + /// This provenance follows a remote terminal through container moves. + public var remoteTTYReportOriginWorkspaceIDs: [UUID: UUID] = [:] + /// The shell-activity classification reported for each terminal panel, /// keyed by panel id (legacy `Workspace.panelShellActivityStates`). public var panelShellActivityStates: [UUID: PanelShellActivityState] = [:] diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index e59bda2b30a4..1b88d017fe2f 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -144,37 +144,6 @@ extension Workspace { adoptTransferredSurfaceTTYName(from: transfer) } - /// Resolves a remote caller only from a TTY report observed in this app - /// runtime. TTY basenames are unique only inside one authenticated remote - /// workspace because separate hosts commonly reuse `/dev/pts/0`. - func agentDeliveryTarget(forReportedTTYName ttyName: String) -> AgentDeliveryTargetCandidate? { - guard isRemoteWorkspace else { return nil } - var candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = - surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceId - -> (binding: TerminalCallerTTYBinding, ttyName: String)? in - guard activeRemoteTerminalSurfaceIds.contains(surfaceId), - panels[surfaceId] != nil, - let reportedTTYName = surfaceRegistry.surfaceTTYNames[surfaceId] else { - return nil - } - return ( - binding: TerminalCallerTTYBinding(workspaceId: id, surfaceId: surfaceId), - ttyName: reportedTTYName - ) - } - for dock in DockSplitStore.liveRemoteTerminalStores(presentationWorkspaceID: id) { - candidates.append(contentsOf: dock.runtimeReportedRemoteTTYCandidates( - presentationWorkspaceID: id - )) - } - let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) - guard let binding = resolver.binding(for: ttyName) else { return nil } - return AgentDeliveryTargetCandidate( - workspaceId: binding.workspaceId, - surfaceId: binding.surfaceId - ) - } - /// Host-local TTY bindings eligible to identify a process running on this /// Mac. Remote workspaces and remote terminal surfaces use a different /// `/dev` namespace and must never participate in local device matching. @@ -332,7 +301,7 @@ extension AppDelegate { return (owner.tabID, owner.surfaceID) } - private func agentDeliveryTabManagers() -> [TabManager] { + func agentDeliveryTabManagers() -> [TabManager] { var managers: [TabManager] = [] func append(_ manager: TabManager?) { guard let manager, !managers.contains(where: { $0 === manager }) else { return } @@ -391,8 +360,12 @@ extension TerminalController { let ttyName = params["tty_name"] as? String, TerminalCallerTTYResolver.normalizedName(ttyName) != nil, let remoteWorkspaceId = v2UUID(params, "_cmux_remote_workspace_id"), - let workspace = controlTabForSidebarMutation(id: remoteWorkspaceId), - let target = workspace.agentDeliveryTarget(forReportedTTYName: ttyName) else { + let authenticatedWorkspace = controlTabForSidebarMutation(id: remoteWorkspaceId), + authenticatedWorkspace.isRemoteWorkspace, + let target = appDelegate.liveRelayAgentDeliveryTarget( + authenticatedWorkspaceID: remoteWorkspaceId, + ttyName: ttyName + ) else { return .err( code: "not_found", message: String( diff --git a/Sources/AgentRelayTTYTargetResolution.swift b/Sources/AgentRelayTTYTargetResolution.swift new file mode 100644 index 000000000000..d1dcf282a05b --- /dev/null +++ b/Sources/AgentRelayTTYTargetResolution.swift @@ -0,0 +1,81 @@ +import Foundation + +@MainActor +extension Workspace { + /// Fresh remote TTY reports whose authenticated relay origin matches the + /// requested workspace. The binding points at the surface's current owner. + func runtimeReportedRemoteTTYCandidates( + authenticatedWorkspaceID: UUID + ) -> [(binding: TerminalCallerTTYBinding, ttyName: String)] { + surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceID in + guard panels[surfaceID] is TerminalPanel, + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[surfaceID] == + authenticatedWorkspaceID, + remoteTerminalSessionStatesBySurfaceId[surfaceID]?.phase != .ended, + let ttyName = surfaceRegistry.surfaceTTYNames[surfaceID] else { + return nil + } + return ( + binding: TerminalCallerTTYBinding( + workspaceId: id, + surfaceId: surfaceID + ), + ttyName: ttyName + ) + } + } + + /// Resolves one authenticated remote workspace without inspecting another + /// relay's TTY namespace. + func agentDeliveryTarget(forReportedTTYName ttyName: String) -> AgentDeliveryTargetCandidate? { + guard isRemoteWorkspace else { return nil } + var candidates = runtimeReportedRemoteTTYCandidates( + authenticatedWorkspaceID: id + ) + for dock in DockSplitStore.liveRemoteTerminalStores( + presentationWorkspaceID: id + ) { + candidates.append(contentsOf: dock.runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: id + )) + } + let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) + guard let binding = resolver.binding(for: ttyName) else { return nil } + return AgentDeliveryTargetCandidate( + workspaceId: binding.workspaceId, + surfaceId: binding.surfaceId + ) + } +} + +@MainActor +extension AppDelegate { + /// Resolves a relay-authenticated TTY across the live containers that may + /// now own a surface launched by that remote workspace. + func liveRelayAgentDeliveryTarget( + authenticatedWorkspaceID: UUID, + ttyName: String + ) -> AgentDeliveryTargetCandidate? { + var candidates: [(binding: TerminalCallerTTYBinding, ttyName: String)] = [] + for manager in agentDeliveryTabManagers() { + for workspace in manager.tabs { + candidates.append(contentsOf: workspace.runtimeReportedRemoteTTYCandidates( + authenticatedWorkspaceID: authenticatedWorkspaceID + )) + } + } + for dock in DockSplitStore.liveRemoteTerminalStores( + presentationWorkspaceID: authenticatedWorkspaceID + ) { + candidates.append(contentsOf: dock.runtimeReportedRemoteTTYCandidates( + presentationWorkspaceID: authenticatedWorkspaceID + )) + } + let resolver = TerminalCallerTTYResolver(reportedCandidates: candidates) + guard let binding = resolver.binding(for: ttyName) else { return nil } + return AgentDeliveryTargetCandidate( + workspaceId: binding.workspaceId, + surfaceId: binding.surfaceId + ) + } +} diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 239f87806018..169ee0927db9 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -5330,6 +5330,10 @@ final class Workspace: Identifiable, ObservableObject { manualUnreadMarkedAt = manualUnreadMarkedAt.filter { validSurfaceIds.contains($0.key) } surfaceListeningPorts = surfaceListeningPorts.filter { validSurfaceIds.contains($0.key) } surfaceTTYNames = surfaceTTYNames.filter { validSurfaceIds.contains($0.key) } + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs = + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.filter { + validSurfaceIds.contains($0.key) + } restoredGuardedWorkingDirectoriesByPanelId = restoredGuardedWorkingDirectoriesByPanelId.filter { validSurfaceIds.contains($0.key) } @@ -6006,6 +6010,7 @@ final class Workspace: Identifiable, ObservableObject { } func trackRemoteTerminalSurface(_ panelId: UUID, preserveTrustedRemoteDirectory: Bool = false) { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelId] = id let previousPresentedDirectory = presentedCurrentDirectory let existingDirectory = panelDirectories[panelId]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let removedTrustedDirectory: Bool @@ -6042,6 +6047,7 @@ final class Workspace: Identifiable, ObservableObject { } func untrackRemoteTerminalSurface(_ panelId: UUID) { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: panelId) let previousPresentedDirectory = presentedCurrentDirectory let removedTrustedDirectory = remoteDirectoryReportPanelIds.remove(panelId) != nil; if removedTrustedDirectory { clearPanelGitBranch(panelId: panelId) } clearRemoteTerminalSessionPhase(surfaceId: panelId) @@ -6691,6 +6697,7 @@ final class Workspace: Identifiable, ObservableObject { } if cleanupTransferredRemoteConnectionIfNeeded(surfaceId: surfaceId, relayPort: relayPort) { invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: surfaceId) return true } guard let configuration = remoteConfiguration, @@ -6703,6 +6710,7 @@ final class Workspace: Identifiable, ObservableObject { let didEnd = endedPendingConnection != nil || recordedLifecycleTombstone if didEnd { invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: surfaceId) } return didEnd } @@ -9806,6 +9814,12 @@ final class Workspace: Identifiable, ObservableObject { ) } } + if detached.isRemoteTerminal, detached.remoteTerminalSessionPhase != .ended { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[detached.panelId] = + didAdoptWorkspaceRemoteTracking ? id : detached.sessionRestoreWorkspaceId + } else { + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: detached.panelId) + } restoreTransferredSurfaceTTYRuntimeProofIfNeeded(from: detached) if let cleanupConfiguration = detached.remoteCleanupConfiguration { if didAdoptWorkspaceRemoteTracking { @@ -12480,7 +12494,8 @@ extension Workspace: BonsplitDelegate { let panelDirectory = panelDirectories[panelId] splitLayout.storeDetachedTransfer(DetachedSurfaceTransfer( sourceWorkspaceId: id, - sessionRestoreSourceWorkspaceId: id, + sessionRestoreSourceWorkspaceId: + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelId] ?? id, panelId: panelId, panel: panel, title: resolvedPanelTitle(panelId: panelId, fallback: transferFallbackTitle), diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index d5fe361e17b0..eaf498c6b558 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -133,6 +133,7 @@ 89930002AABBCCDDEEFF0001 /* AgentProcessBindingResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */; }; 89930002AABBCCDDEEFF0002 /* AgentProcessBindingResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */; }; 0A1107110000000000000012 /* AgentRelaunchCommandBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000013 /* AgentRelaunchCommandBuilder.swift */; }; + 93840003AA11BB22CC33EE03 /* AgentRelayTTYTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */; }; 0A1107110000000000000014 /* AgentRestoreMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000015 /* AgentRestoreMode.swift */; }; D8DFFAEC2DBC3ACCF87D563E /* AgentResumeLaunchGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */; }; E8DF7FD45DA2E55E4DA65B38 /* AgentResumeLaunchGuardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21EBB654187F880170B92ED9 /* AgentResumeLaunchGuardTests.swift */; }; @@ -2801,6 +2802,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B79500110000000000000002 /* AgentPortTrackingState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPortTrackingState.swift; sourceTree = ""; }; 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentProcessBindingResolution.swift; sourceTree = ""; }; 0A1107110000000000000013 /* AgentRelaunchCommandBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelaunchCommandBuilder.swift; sourceTree = ""; }; + 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelayTTYTargetResolution.swift; sourceTree = ""; }; 0A1107110000000000000015 /* AgentRestoreMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRestoreMode.swift; sourceTree = ""; }; 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentResumeLaunchGuard.swift; sourceTree = ""; }; 21EBB654187F880170B92ED9 /* AgentResumeLaunchGuardTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentResumeLaunchGuardTests.swift; sourceTree = ""; }; @@ -6507,6 +6509,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F1A0C0DE0000000000000001 /* FindTextFieldSupport.swift */, A5A5A502A1B2C3D4E5F60718 /* TerminalNotificationQueue.swift */, 79390006AA11BB22CC33DD06 /* AgentDeliveryTargetResolution.swift */, + 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */, 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */, 8362A0020000000000000002 /* TerminalCallerTTYResolver.swift */, 8362A0040000000000000004 /* TerminalCallerTTYBinding.swift */, @@ -8479,6 +8482,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B79500110000000000000001 /* AgentPortTrackingState.swift in Sources */, 89930002AABBCCDDEEFF0001 /* AgentProcessBindingResolution.swift in Sources */, 0A1107110000000000000012 /* AgentRelaunchCommandBuilder.swift in Sources */, + 93840003AA11BB22CC33EE03 /* AgentRelayTTYTargetResolution.swift in Sources */, 0A1107110000000000000014 /* AgentRestoreMode.swift in Sources */, D8DFFAEC2DBC3ACCF87D563E /* AgentResumeLaunchGuard.swift in Sources */, CC2D14DFE13EFF544A25BEAF /* AgentResumeLiveness.swift in Sources */, From 6654fa14862d8caf21587227a9b8e0674ec128db Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 10:57:18 -0700 Subject: [PATCH 25/35] test: cover relay ownership after surface moves --- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/AgentRelayTTYOwnershipTests.swift | 127 ++++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 cmuxTests/AgentRelayTTYOwnershipTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index eaf498c6b558..385bea103c40 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -133,6 +133,7 @@ 89930002AABBCCDDEEFF0001 /* AgentProcessBindingResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */; }; 89930002AABBCCDDEEFF0002 /* AgentProcessBindingResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */; }; 0A1107110000000000000012 /* AgentRelaunchCommandBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000013 /* AgentRelaunchCommandBuilder.swift */; }; + 93840005AA11BB22CC33EE05 /* AgentRelayTTYOwnershipTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93840006AA11BB22CC33EE06 /* AgentRelayTTYOwnershipTests.swift */; }; 93840003AA11BB22CC33EE03 /* AgentRelayTTYTargetResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */; }; 0A1107110000000000000014 /* AgentRestoreMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A1107110000000000000015 /* AgentRestoreMode.swift */; }; D8DFFAEC2DBC3ACCF87D563E /* AgentResumeLaunchGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */; }; @@ -2802,6 +2803,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B79500110000000000000002 /* AgentPortTrackingState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPortTrackingState.swift; sourceTree = ""; }; 89930002AABBCCDDEEFF0003 /* AgentProcessBindingResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentProcessBindingResolution.swift; sourceTree = ""; }; 0A1107110000000000000013 /* AgentRelaunchCommandBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelaunchCommandBuilder.swift; sourceTree = ""; }; + 93840006AA11BB22CC33EE06 /* AgentRelayTTYOwnershipTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelayTTYOwnershipTests.swift; sourceTree = ""; }; 93840004AA11BB22CC33EE04 /* AgentRelayTTYTargetResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRelayTTYTargetResolution.swift; sourceTree = ""; }; 0A1107110000000000000015 /* AgentRestoreMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRestoreMode.swift; sourceTree = ""; }; 5977EB347EF8D7692B3759E2 /* AgentResumeLaunchGuard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentResumeLaunchGuard.swift; sourceTree = ""; }; @@ -7816,6 +7818,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 79390010AA11BB22CC33DD10 /* AgentNotificationMoveRaceTests.swift */, 79460002AA11BB22CC33EE02 /* AgentNotificationMutationBoundaryTests.swift */, 93800002AA11BB22CC33EE02 /* AgentDeliveryTTYBindingTests.swift */, + 93840006AA11BB22CC33EE06 /* AgentRelayTTYOwnershipTests.swift */, 79390012AA11BB22CC33DD12 /* ClaudeHookPIDAuthenticationTests.swift */, C7A534000000000000000001 /* ClaudeHookFeedTelemetrySwiftTests.swift */, A5D41223A1B2C3D4E5F60718 /* ClaudeNotificationStatusLifecycleTests.swift */, @@ -10290,6 +10293,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 79390003AA11BB22CC33DD03 /* AgentNotificationLiveRetargetTests.swift in Sources */, 7939000FAA11BB22CC33DD0F /* AgentNotificationMoveRaceTests.swift in Sources */, 79460001AA11BB22CC33EE01 /* AgentNotificationMutationBoundaryTests.swift in Sources */, + 93840005AA11BB22CC33EE05 /* AgentRelayTTYOwnershipTests.swift in Sources */, E8DF7FD45DA2E55E4DA65B38 /* AgentResumeLaunchGuardTests.swift in Sources */, B679CCBA4CF56982C8564009 /* AgentResumeLivenessTests.swift in Sources */, 8837A0010000000000000001 /* AgentResumeReturnShellStartupTests.swift in Sources */, diff --git a/cmuxTests/AgentRelayTTYOwnershipTests.swift b/cmuxTests/AgentRelayTTYOwnershipTests.swift new file mode 100644 index 000000000000..4da02f8e9ccf --- /dev/null +++ b/cmuxTests/AgentRelayTTYOwnershipTests.swift @@ -0,0 +1,127 @@ +import CmuxCore +import Foundation +import Testing +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +extension AgentNotificationRegressionTests { + @Test("Relay provenance does not cross remote hosts sharing a port") + func relayTTYProvenanceDoesNotCrossRemoteHostsSharingPort() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.destination.remoteConfiguration = relayConfiguration( + destination: "destination.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/20", panelId: fixture.panelId) + + try movePanel(fixture) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/20", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.destination.id, + ttyName: "pts/20" + ) + } + + @Test("A fresh TTY report follows a remote surface into an ordinary workspace") + func freshRelayTTYReportFollowsSurfaceIntoOrdinaryWorkspace() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/21", panelId: fixture.panelId) + let paneID = try #require(fixture.source.bonsplitController.allPaneIds.first) + _ = try #require(fixture.source.newTerminalSurface(inPane: paneID, focus: false)) + + try movePanel(fixture) + + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/22" + ) == .recorded(surfaceID: fixture.panelId) + ) + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/22", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/21" + ) + } + + private func relayConfiguration( + destination: String, + relayPort: Int + ) -> WorkspaceRemoteConfiguration { + WorkspaceRemoteConfiguration( + destination: destination, + port: nil, + identityFile: nil, + sshOptions: [], + localProxyPort: nil, + relayPort: relayPort, + relayID: nil, + relayToken: nil, + localSocketPath: nil, + terminalStartupCommand: nil + ) + } + + private func assertRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String, + expectedWorkspaceID: UUID, + expectedSurfaceID: UUID + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .ok(let payload) = result, + let target = payload as? [String: Any] else { + Issue.record("Expected authenticated relay TTY resolution, got \(result)") + return + } + #expect(target["workspace_id"] as? String == expectedWorkspaceID.uuidString) + #expect(target["surface_id"] as? String == expectedSurfaceID.uuidString) + } + + private func assertNoRelayTTYTarget( + authenticatedWorkspaceID: UUID, + ttyName: String + ) { + let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ + "tty_name": ttyName, + "tty_resolution": "reported_tty", + "_cmux_remote_workspace_id": authenticatedWorkspaceID.uuidString, + ]) + guard case .err(let code, _, _) = result else { + Issue.record("Expected relay TTY resolution to fail, got \(result)") + return + } + #expect(code == "not_found") + } +} From d1292008352b2eef3012d35cfab178f949f5245d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 11:02:35 -0700 Subject: [PATCH 26/35] fix: keep relay provenance scoped through moves --- Sources/AgentRelayTTYTargetResolution.swift | 41 +++++++++++++++++++ Sources/DockSplitStore+SurfaceTransfer.swift | 1 + ...nalController+ControlSurfaceContext4.swift | 10 +++++ .../Workspace+DetachedSurfaceTransfer.swift | 2 + Sources/Workspace.swift | 11 ++--- 5 files changed, 60 insertions(+), 5 deletions(-) diff --git a/Sources/AgentRelayTTYTargetResolution.swift b/Sources/AgentRelayTTYTargetResolution.swift index d1dcf282a05b..301763eb3e7e 100644 --- a/Sources/AgentRelayTTYTargetResolution.swift +++ b/Sources/AgentRelayTTYTargetResolution.swift @@ -2,6 +2,27 @@ import Foundation @MainActor extension Workspace { + /// Records a fresh report only when this workspace owns the surface for + /// the relay-authenticated workspace that originally launched it. + func registerRelayReportedTTY( + _ ttyName: String, + panelID: UUID, + authenticatedWorkspaceID: UUID + ) -> Bool { + guard panels[panelID] is TerminalPanel, + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelID] == + authenticatedWorkspaceID, + remoteTerminalSessionStatesBySurfaceId[panelID]?.phase != .ended else { + return false + } + registerReportedSurfaceTTYName(ttyName, panelId: panelID) + if isRemoteWorkspace { + syncRemotePortScanTTYs() + _ = applyPendingRemoteSurfacePortKickIfNeeded(to: panelID) + } + return true + } + /// Fresh remote TTY reports whose authenticated relay origin matches the /// requested workspace. The binding points at the surface's current owner. func runtimeReportedRemoteTTYCandidates( @@ -50,6 +71,26 @@ extension Workspace { @MainActor extension AppDelegate { + /// Routes a fresh relay report to the unique live Workspace owner without + /// allowing the authenticated origin to change during a container move. + func registerLiveRelayReportedTTY( + _ ttyName: String, + panelID: UUID, + authenticatedWorkspaceID: UUID + ) -> Bool { + let owners = agentDeliveryTabManagers().flatMap(\.tabs).filter { + $0.panels[panelID] != nil + && $0.surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelID] == + authenticatedWorkspaceID + } + guard owners.count == 1 else { return false } + return owners[0].registerRelayReportedTTY( + ttyName, + panelID: panelID, + authenticatedWorkspaceID: authenticatedWorkspaceID + ) + } + /// Resolves a relay-authenticated TTY across the live containers that may /// now own a surface launched by that remote workspace. func liveRelayAgentDeliveryTarget( diff --git a/Sources/DockSplitStore+SurfaceTransfer.swift b/Sources/DockSplitStore+SurfaceTransfer.swift index b83c382d8293..5bc735b28ef8 100644 --- a/Sources/DockSplitStore+SurfaceTransfer.swift +++ b/Sources/DockSplitStore+SurfaceTransfer.swift @@ -296,6 +296,7 @@ extension DockSplitStore { remoteTerminalLifecycleID: preservedTransfer?.remoteTerminalLifecycleID, remoteTerminalAttemptID: preservedTransfer?.remoteTerminalAttemptID, remoteRelayPort: preservedTransfer?.remoteRelayPort, + remoteRelayNamespaceConfiguration: preservedTransfer?.remoteRelayNamespaceConfiguration, remotePTYSessionID: preservedTransfer?.remotePTYSessionID, remoteCleanupConfiguration: preservedTransfer?.remoteCleanupConfiguration ) diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index e8813b1050fe..20f5b03ce72e 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -42,6 +42,16 @@ extension TerminalController { ) { return .recorded(surfaceID: requestedSurfaceID) } + if let requestedSurfaceID, + tab.isRemoteWorkspace, + !validSurfaceIds.contains(requestedSurfaceID), + AppDelegate.shared?.registerLiveRelayReportedTTY( + ttyName, + panelID: requestedSurfaceID, + authenticatedWorkspaceID: workspaceID + ) == true { + return .recorded(surfaceID: requestedSurfaceID) + } let surfaceId = controlResolveReportedSurfaceId( in: tab, diff --git a/Sources/Workspace+DetachedSurfaceTransfer.swift b/Sources/Workspace+DetachedSurfaceTransfer.swift index 5437297d17c7..569c9b57d120 100644 --- a/Sources/Workspace+DetachedSurfaceTransfer.swift +++ b/Sources/Workspace+DetachedSurfaceTransfer.swift @@ -59,6 +59,7 @@ extension Workspace { var remoteTerminalLifecycleID: UUID? = nil var remoteTerminalAttemptID: UUID? = nil let remoteRelayPort: Int? + var remoteRelayNamespaceConfiguration: WorkspaceRemoteConfiguration? = nil let remotePTYSessionID: String? let remoteCleanupConfiguration: WorkspaceRemoteConfiguration? @@ -110,6 +111,7 @@ extension Workspace { remoteTerminalLifecycleID: remoteTerminalLifecycleID, remoteTerminalAttemptID: remoteTerminalAttemptID, remoteRelayPort: remoteRelayPort, + remoteRelayNamespaceConfiguration: remoteRelayNamespaceConfiguration, remotePTYSessionID: remotePTYSessionID, remoteCleanupConfiguration: configuration ) diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 169ee0927db9..22f4e42640c9 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9861,13 +9861,11 @@ final class Workspace: Identifiable, ObservableObject { private func shouldAdoptDetachedWorkspaceRemoteTracking(_ detached: DetachedSurfaceTransfer) -> Bool { guard detached.isRemoteTerminal, detached.remoteTerminalSessionPhase != .ended else { return false } if detached.sourceWorkspaceId == id { return true } - guard let detachedRelayPort = detached.remoteRelayPort, - detachedRelayPort > 0, - let currentRelayPort = remoteConfiguration?.relayPort, - currentRelayPort > 0 else { + guard let destinationConfiguration = remoteConfiguration, + let originConfiguration = detached.remoteRelayNamespaceConfiguration else { return false } - return detachedRelayPort == currentRelayPort + return destinationConfiguration.hasSameRemoteRelayNamespace(as: originConfiguration) } // MARK: - Focus Management @@ -12535,6 +12533,9 @@ extension Workspace: BonsplitDelegate { remoteRelayPort: activeRemoteTerminalSurfaceIds.contains(panelId) ? remoteConfiguration?.relayPort : nil, + remoteRelayNamespaceConfiguration: activeRemoteTerminalSurfaceIds.contains(panelId) + ? remoteConfiguration + : transferredRemoteCleanupConfiguration, remotePTYSessionID: remotePTYSessionIDForSnapshot(panelId: panelId), remoteCleanupConfiguration: transferredRemoteCleanupConfiguration ), for: tabId) From 13f3b1e7a24d5e4c2b6be4c56371df861d8cc33b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 11:17:01 -0700 Subject: [PATCH 27/35] test: cover stale relay TTY lifecycle --- cmuxTests/AgentRelayTTYOwnershipTests.swift | 60 +++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/cmuxTests/AgentRelayTTYOwnershipTests.swift b/cmuxTests/AgentRelayTTYOwnershipTests.swift index 4da02f8e9ccf..172ba7640c49 100644 --- a/cmuxTests/AgentRelayTTYOwnershipTests.swift +++ b/cmuxTests/AgentRelayTTYOwnershipTests.swift @@ -71,6 +71,66 @@ extension AgentNotificationRegressionTests { ) } + @Test("A disconnected remote terminal cannot resolve or register another TTY") + func disconnectedRemoteTerminalCannotResolveOrRegisterTTY() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/23", panelId: fixture.panelId) + + fixture.source.disconnectRemoteConnection() + + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/23" + ) + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/24" + ) == .surfaceNotFound + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/24" + ) + } + + @Test("A delayed TTY report cannot revive an ended remote terminal") + func delayedTTYReportCannotReviveEndedRemoteTerminal() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/25", panelId: fixture.panelId) + #expect( + fixture.source.markRemoteTerminalSessionEnded( + surfaceId: fixture.panelId, + relayPort: 64_007 + ) + ) + + #expect( + TerminalController.shared.controlSurfaceReportTTY( + workspaceID: fixture.source.id, + requestedSurfaceID: fixture.panelId, + ttyName: "pts/26" + ) == .surfaceNotFound + ) + assertNoRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/26" + ) + } + private func relayConfiguration( destination: String, relayPort: Int From b1d61ad219dcc47e9ce7b0a2b9d0a82eea4f7f70 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 11:29:00 -0700 Subject: [PATCH 28/35] fix: retire relay TTY provenance on terminal end --- Sources/AgentRelayTTYTargetResolution.swift | 4 +--- .../TerminalController+ControlSurfaceContext4.swift | 11 ++++++++--- Sources/Workspace+RemoteTerminalLiveness.swift | 9 +++++++++ Sources/Workspace.swift | 3 +-- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/Sources/AgentRelayTTYTargetResolution.swift b/Sources/AgentRelayTTYTargetResolution.swift index 301763eb3e7e..7a5ec0bc7f94 100644 --- a/Sources/AgentRelayTTYTargetResolution.swift +++ b/Sources/AgentRelayTTYTargetResolution.swift @@ -11,8 +11,7 @@ extension Workspace { ) -> Bool { guard panels[panelID] is TerminalPanel, surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelID] == - authenticatedWorkspaceID, - remoteTerminalSessionStatesBySurfaceId[panelID]?.phase != .ended else { + authenticatedWorkspaceID else { return false } registerReportedSurfaceTTYName(ttyName, panelId: panelID) @@ -32,7 +31,6 @@ extension Workspace { guard panels[surfaceID] is TerminalPanel, surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[surfaceID] == authenticatedWorkspaceID, - remoteTerminalSessionStatesBySurfaceId[surfaceID]?.phase != .ended, let ttyName = surfaceRegistry.surfaceTTYNames[surfaceID] else { return nil } diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index 20f5b03ce72e..a30d386340a4 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -66,11 +66,16 @@ extension TerminalController { return .surfaceNotFound } - tab.registerReportedSurfaceTTYName(ttyName, panelId: surfaceId) if tab.isRemoteWorkspace { - tab.syncRemotePortScanTTYs() - _ = tab.applyPendingRemoteSurfacePortKickIfNeeded(to: surfaceId) + guard tab.registerRelayReportedTTY( + ttyName, + panelID: surfaceId, + authenticatedWorkspaceID: workspaceID + ) else { + return .surfaceNotFound + } } else { + tab.registerReportedSurfaceTTYName(ttyName, panelId: surfaceId) PortScanner.shared.registerTTY(workspaceId: workspaceID, panelId: surfaceId, ttyName: ttyName) } return .recorded(surfaceID: surfaceId) diff --git a/Sources/Workspace+RemoteTerminalLiveness.swift b/Sources/Workspace+RemoteTerminalLiveness.swift index e9eb6b85e670..8ceeeb3d060d 100644 --- a/Sources/Workspace+RemoteTerminalLiveness.swift +++ b/Sources/Workspace+RemoteTerminalLiveness.swift @@ -451,11 +451,20 @@ extension Workspace { } func clearRemoteTerminalSessionPhase(surfaceId: UUID) { + invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: surfaceId) remoteTerminalSessionStatesBySurfaceId.removeValue(forKey: surfaceId) pendingRemoteTerminalConnectionsBySurfaceId.removeValue(forKey: surfaceId) remoteTerminalAttemptIDsBySurfaceId.removeValue(forKey: surfaceId) } + func clearActiveRemoteTerminalSessionPhases() { + for surfaceId in activeRemoteTerminalSurfaceIds { + clearRemoteTerminalSessionPhase(surfaceId: surfaceId) + } + activeRemoteTerminalSurfaceIds.removeAll() + } + func restoreRemoteTerminalSessionPhase( _ phase: WorkspaceRemoteTerminalSessionPhase?, authority: WorkspaceRemoteTerminalAuthority?, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 22f4e42640c9..f4d8021f9dd4 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -5928,7 +5928,7 @@ final class Workspace: Identifiable, ObservableObject { ) cancelPendingRemoteControlMasterAdoption() remoteDisconnectPlaceholderPanelIds.formUnion(activeRemoteTerminalSurfaceIds) - activeRemoteTerminalSurfaceIds.removeAll() + clearActiveRemoteTerminalSessionPhases() remoteTerminalSessionStatesBySurfaceId.removeAll() pendingRemoteTerminalConnectionsBySurfaceId.removeAll() remoteTerminalAttemptIDsBySurfaceId.removeAll() @@ -6047,7 +6047,6 @@ final class Workspace: Identifiable, ObservableObject { } func untrackRemoteTerminalSurface(_ panelId: UUID) { - surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: panelId) let previousPresentedDirectory = presentedCurrentDirectory let removedTrustedDirectory = remoteDirectoryReportPanelIds.remove(panelId) != nil; if removedTrustedDirectory { clearPanelGitBranch(panelId: panelId) } clearRemoteTerminalSessionPhase(surfaceId: panelId) From f85da04bf578078f90caafca996346ff52202dbc Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 11:42:46 -0700 Subject: [PATCH 29/35] test: cover durable relay identity after moves --- cmuxTests/AgentRelayTTYOwnershipTests.swift | 86 ++++++++++++++++++++- 1 file changed, 84 insertions(+), 2 deletions(-) diff --git a/cmuxTests/AgentRelayTTYOwnershipTests.swift b/cmuxTests/AgentRelayTTYOwnershipTests.swift index 172ba7640c49..55417e141674 100644 --- a/cmuxTests/AgentRelayTTYOwnershipTests.swift +++ b/cmuxTests/AgentRelayTTYOwnershipTests.swift @@ -131,9 +131,89 @@ extension AgentNotificationRegressionTests { ) } + @Test("Relay provenance survives repeated ordinary workspace moves") + func relayTTYProvenanceSurvivesRepeatedOrdinaryWorkspaceMoves() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.source.registerReportedSurfaceTTYName("pts/27", panelId: fixture.panelId) + + try movePanel(fixture) + let secondDestination = fixture.manager.addWorkspace(select: false) + defer { + if fixture.manager.tabs.contains(where: { $0.id == secondDestination.id }) { + fixture.manager.closeWorkspace(secondDestination) + } + } + let transfer = try #require( + fixture.destination.detachSurface(panelId: fixture.panelId) + ) + let destinationPaneID = try #require( + secondDestination.bonsplitController.allPaneIds.first + ) + #expect( + secondDestination.attachDetachedSurface( + transfer, + inPane: destinationPaneID, + focus: false + ) == fixture.panelId + ) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/27", + expectedWorkspaceID: secondDestination.id, + expectedSurfaceID: fixture.panelId + ) + } + + @Test("A persistent retry after an ordinary workspace move preserves TTY proof") + func persistentRetryAfterOrdinaryWorkspaceMovePreservesTTYProof() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let terminal = try #require( + fixture.source.panels[fixture.panelId] as? TerminalPanel + ) + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007, + preserveAfterTerminalExit: true + ) + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect( + fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + fixture.source.registerReportedSurfaceTTYName("pts/28", panelId: fixture.panelId) + + try movePanel(fixture) + #expect( + fixture.destination.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: UUID() + ) + ) + + assertRelayTTYTarget( + authenticatedWorkspaceID: fixture.source.id, + ttyName: "pts/28", + expectedWorkspaceID: fixture.destination.id, + expectedSurfaceID: fixture.panelId + ) + } + private func relayConfiguration( destination: String, - relayPort: Int + relayPort: Int, + preserveAfterTerminalExit: Bool = false ) -> WorkspaceRemoteConfiguration { WorkspaceRemoteConfiguration( destination: destination, @@ -145,7 +225,9 @@ extension AgentNotificationRegressionTests { relayID: nil, relayToken: nil, localSocketPath: nil, - terminalStartupCommand: nil + terminalStartupCommand: nil, + preserveAfterTerminalExit: preserveAfterTerminalExit, + persistentDaemonSlot: preserveAfterTerminalExit ? "relay-tty-test" : nil ) } From 01494812d600396f6d077feb8812ca1e8ab6b6c2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 11:47:04 -0700 Subject: [PATCH 30/35] fix: keep relay identity durable across moves --- .../Workspace+RemoteTerminalLiveness.swift | 5 ++++- Sources/Workspace.swift | 20 ++++++++++--------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/Sources/Workspace+RemoteTerminalLiveness.swift b/Sources/Workspace+RemoteTerminalLiveness.swift index 8ceeeb3d060d..bfd71912518a 100644 --- a/Sources/Workspace+RemoteTerminalLiveness.swift +++ b/Sources/Workspace+RemoteTerminalLiveness.swift @@ -123,7 +123,10 @@ extension Workspace { } endedRemoteTerminalLifecycleIDsBySurfaceId.removeValue(forKey: surfaceId) if remoteTerminalAttemptIDsBySurfaceId[surfaceId] != attemptID, - remoteConfiguration?.preserveAfterTerminalExit != true { + (activeRemoteTerminalSurfaceIds.contains(surfaceId) + ? remoteConfiguration + : transferredRemoteCleanupConfigurationsByPanelId[surfaceId])? + .preserveAfterTerminalExit != true { invalidateReportedSurfaceTTYRuntime(panelId: surfaceId) } remoteTerminalAttemptIDsBySurfaceId[surfaceId] = attemptID diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index f4d8021f9dd4..eca2afd8e48a 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -12489,10 +12489,16 @@ extension Workspace: BonsplitDelegate { ) let agentRuntime = agentRuntimeState(forPanelId: panelId) let panelDirectory = panelDirectories[panelId] + let remoteTTYReportOriginWorkspaceID = + surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelId] + let isRemoteTerminal = activeRemoteTerminalSurfaceIds.contains(panelId) + || remoteTTYReportOriginWorkspaceID != nil + let remoteRelayNamespaceConfiguration = activeRemoteTerminalSurfaceIds.contains(panelId) + ? remoteConfiguration + : transferredRemoteCleanupConfiguration splitLayout.storeDetachedTransfer(DetachedSurfaceTransfer( sourceWorkspaceId: id, - sessionRestoreSourceWorkspaceId: - surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelId] ?? id, + sessionRestoreSourceWorkspaceId: remoteTTYReportOriginWorkspaceID ?? id, panelId: panelId, panel: panel, title: resolvedPanelTitle(panelId: panelId, fallback: transferFallbackTitle), @@ -12523,18 +12529,14 @@ extension Workspace: BonsplitDelegate { $0.hasCompleteManagedSessionIdentity ? $0 : nil }, agentRuntime: agentRuntime, - isRemoteTerminal: activeRemoteTerminalSurfaceIds.contains(panelId), + isRemoteTerminal: isRemoteTerminal, remoteTerminalSessionPhase: remoteTerminalSessionStatesBySurfaceId[panelId]?.phase, remoteTerminalAuthority: remoteTerminalSessionStatesBySurfaceId[panelId]?.authority, remoteTerminalLifecycleID: remoteTerminalSessionStatesBySurfaceId[panelId]? .terminalLifecycleID, remoteTerminalAttemptID: remoteTerminalAttemptIDsBySurfaceId[panelId], - remoteRelayPort: activeRemoteTerminalSurfaceIds.contains(panelId) - ? remoteConfiguration?.relayPort - : nil, - remoteRelayNamespaceConfiguration: activeRemoteTerminalSurfaceIds.contains(panelId) - ? remoteConfiguration - : transferredRemoteCleanupConfiguration, + remoteRelayPort: remoteRelayNamespaceConfiguration?.relayPort, + remoteRelayNamespaceConfiguration: remoteRelayNamespaceConfiguration, remotePTYSessionID: remotePTYSessionIDForSnapshot(panelId: panelId), remoteCleanupConfiguration: transferredRemoteCleanupConfiguration ), for: tabId) From d78041b2f7100cb23fd22867c38c5fea4b2312ca Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 12:00:53 -0700 Subject: [PATCH 31/35] test: cover authoritative TTY trust boundaries --- cmuxTests/AgentRelayTTYOwnershipTests.swift | 172 ++++++++++++++++++++ 1 file changed, 172 insertions(+) diff --git a/cmuxTests/AgentRelayTTYOwnershipTests.swift b/cmuxTests/AgentRelayTTYOwnershipTests.swift index 55417e141674..db22b64472d7 100644 --- a/cmuxTests/AgentRelayTTYOwnershipTests.swift +++ b/cmuxTests/AgentRelayTTYOwnershipTests.swift @@ -1,3 +1,5 @@ +import AppKit +import CmuxControlSocket import CmuxCore import Foundation import Testing @@ -210,6 +212,157 @@ extension AgentNotificationRegressionTests { ) } + @Test("The relay stamps its owner onto TTY reports") + func relayTTYReportProvenanceOverridesSpoofedWorkspace() throws { + let authenticatedWorkspaceID = UUID() + let spoofedWorkspaceID = UUID() + let request: [String: Any] = [ + "id": "relay-tty-report", + "method": "surface.report_tty", + "params": [ + "workspace_id": spoofedWorkspaceID.uuidString, + "surface_id": UUID().uuidString, + "tty_name": "pts/29", + "_cmux_remote_workspace_id": spoofedWorkspaceID.uuidString, + ], + ] + let commandLine = try JSONSerialization.data(withJSONObject: request) + + let rewritten = WorkspaceRemoteRelayCommandRewriter( + remoteWorkspaceID: authenticatedWorkspaceID, + remoteRelayTokenHex: String(repeating: "a", count: 64) + ).rewriteRemoteRelayCommandLine( + commandLine, + workspaceAliases: [:], + surfaceAliases: [:] + ) + let rewrittenRequest = try #require( + JSONSerialization.jsonObject(with: rewritten) as? [String: Any] + ) + let params = try #require(rewrittenRequest["params"] as? [String: Any]) + + #expect( + params["_cmux_remote_workspace_id"] as? String + == authenticatedWorkspaceID.uuidString + ) + } + + @Test("Relay TTY reports require the authenticated owner and current attempt") + func relayTTYReportsRejectSpoofedOwnerAndStaleAttempt() throws { + let fixture = try makeFixture() + defer { fixture.restore() } + fixture.source.remoteConfiguration = relayConfiguration( + destination: "source.example.invalid", + relayPort: 64_007 + ) + fixture.destination.remoteConfiguration = relayConfiguration( + destination: "destination.example.invalid", + relayPort: 64_008 + ) + let sourceTerminal = try #require( + fixture.source.panels[fixture.panelId] as? TerminalPanel + ) + let destinationPanelID = try #require(fixture.destination.focusedPanelId) + let destinationTerminal = try #require( + fixture.destination.panels[destinationPanelID] as? TerminalPanel + ) + let sourceAttemptID = UUID() + let destinationAttemptID = UUID() + fixture.source.trackRemoteTerminalSurface(fixture.panelId) + fixture.destination.trackRemoteTerminalSurface(destinationPanelID) + #expect( + fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: sourceTerminal.surface.terminalLifecycleId, + attemptID: sourceAttemptID + ) + ) + #expect( + fixture.destination.markRemoteTerminalSessionLaunching( + surfaceId: destinationPanelID, + terminalLifecycleID: destinationTerminal.surface.terminalLifecycleId, + attemptID: destinationAttemptID + ) + ) + let coordinator = ControlCommandCoordinator(context: TerminalController.shared) + + assertTTYReportRejected(coordinator.handle(ControlRequest( + id: .string("spoofed-owner"), + method: "surface.report_tty", + params: [ + "workspace_id": .string(fixture.destination.id.uuidString), + "surface_id": .string(destinationPanelID.uuidString), + "tty_name": .string("pts/30"), + "_cmux_remote_workspace_id": .string(fixture.source.id.uuidString), + "terminal_lifecycle_id": .string( + destinationTerminal.surface.terminalLifecycleId.uuidString + ), + "attempt_id": .string(destinationAttemptID.uuidString), + ] + ))) + #expect( + !fixture.destination.surfaceRegistry.runtimeReportedTTYSurfaceIDs + .contains(destinationPanelID) + ) + + assertTTYReportRejected(coordinator.handle(ControlRequest( + id: .string("stale-attempt"), + method: "surface.report_tty", + params: [ + "workspace_id": .string(fixture.source.id.uuidString), + "surface_id": .string(fixture.panelId.uuidString), + "tty_name": .string("pts/31"), + "_cmux_remote_workspace_id": .string(fixture.source.id.uuidString), + "terminal_lifecycle_id": .string( + sourceTerminal.surface.terminalLifecycleId.uuidString + ), + "attempt_id": .string(UUID().uuidString), + ] + ))) + #expect( + !fixture.source.surfaceRegistry.runtimeReportedTTYSurfaceIDs + .contains(fixture.panelId) + ) + } + + @Test("A local TTY report expires when its runtime generation changes") + func localTTYReportExpiresAfterRuntimeGenerationChanges() async throws { + let fixture = try makeFixture() + defer { fixture.restore() } + let terminal = try #require( + fixture.source.panels[fixture.panelId] as? TerminalPanel + ) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 640, height: 480), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + let contentView = try #require(window.contentView) + let hostedView = terminal.hostedView + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + window.orderFront(nil) + window.displayIfNeeded() + defer { + hostedView.removeFromSuperview() + window.orderOut(nil) + } + let ttyName = try #require(await waitForControllingTTYName(for: terminal)) + fixture.source.registerReportedSurfaceTTYName( + ttyName, + panelId: fixture.panelId + ) + #expect(!fixture.source.localAgentDeliveryTTYDevices.isEmpty) + let reportedGeneration = terminal.surface.runtimeSurfaceGeneration + + terminal.surface.releaseSurfaceForTesting() + + #expect(terminal.surface.runtimeSurfaceGeneration != reportedGeneration) + #expect(fixture.source.localAgentDeliveryTTYDevices.isEmpty) + } + private func relayConfiguration( destination: String, relayPort: Int, @@ -266,4 +419,23 @@ extension AgentNotificationRegressionTests { } #expect(code == "not_found") } + + private func assertTTYReportRejected(_ result: ControlCallResult?) { + guard case .err(let code, _, _) = result else { + Issue.record("Expected relay TTY report rejection, got \(String(describing: result))") + return + } + #expect(code == "not_found") + } + + private func waitForControllingTTYName(for terminal: TerminalPanel) async -> String? { + let deadline = ContinuousClock.now + .seconds(15) + while ContinuousClock.now < deadline { + if let ttyName = terminal.surface.controllingTTYName() { + return ttyName + } + try? await Task.sleep(for: .milliseconds(10)) + } + return terminal.surface.controllingTTYName() + } } From c482c7a54a296c775516bcccf83d52eeae0bb9fd Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 12:26:33 -0700 Subject: [PATCH 32/35] fix: bind TTY reports to terminal runtime --- CLI/cmux.swift | 4 +- .../ControlCommandCoordinator+Surface3.swift | 46 ------------ ...lCommandCoordinator+SurfaceReportTTY.swift | 70 +++++++++++++++++++ .../Surface/ControlSurfaceContext.swift | 8 ++- .../ControlCommandContextTestStubs.swift | 9 ++- .../MoshTerminalCommandBuilder.swift | 20 ++++-- ...RemoteBootstrapStagingCommandBuilder.swift | 6 +- .../MoshTerminalCommandBuilderTests.swift | 24 +++++++ ...eBootstrapStagingCommandBuilderTests.swift | 8 ++- .../Core/Model/SurfaceRegistryModel.swift | 3 + .../cmux-bash-integration.bash | 3 +- .../cmux-zsh-integration.zsh | 3 +- Resources/shell-integration/fish/config.fish | 4 +- Sources/AgentDeliveryTargetResolution.swift | 26 ++++++- Sources/AgentRelayTTYTargetResolution.swift | 33 +++++++-- ...ockSplitStore+RemoteTerminalLiveness.swift | 27 +++++-- Sources/DockSplitStore+SurfaceTransfer.swift | 1 + ...moteInteractiveShellBootstrapBuilder.swift | 10 +-- ...nalController+ControlSurfaceContext4.swift | 38 +++++++--- .../Workspace+DetachedSurfaceTransfer.swift | 2 + .../Workspace+RemoteRelayCommandRewrite.swift | 3 +- Sources/Workspace.swift | 3 + cmuxTests/AgentDeliveryTTYBindingTests.swift | 32 +++++++-- .../AgentNotificationLiveRetargetTests.swift | 12 +--- cmuxTests/AgentRelayTTYOwnershipTests.swift | 36 +++++++++- cmuxTests/GhosttyConfigTests.swift | 12 +++- 26 files changed, 330 insertions(+), 113 deletions(-) create mode 100644 Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift diff --git a/CLI/cmux.swift b/CLI/cmux.swift index 329a9404f802..70eb8906cf11 100644 --- a/CLI/cmux.swift +++ b/CLI/cmux.swift @@ -10234,10 +10234,10 @@ struct CMUXCLI { " cmux_relay_cli=\"$HOME/.cmux/bin/cmux\"", " if [ ! -x \"$cmux_relay_cli\" ]; then cmux_relay_cli=\"$(command -v cmux 2>/dev/null || true)\"; fi", " if [ -n \"$cmux_relay_cli\" ]; then", - " ( cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\"}'", + " ( cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\",\"terminal_lifecycle_id\":\"__CMUX_TERMINAL_LIFECYCLE_ID__\",\"attempt_id\":\"__CMUX_SSH_ATTEMPT_ID__\"}'", " cmux_relay_ports_kick='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"reason\":\"command\"}'", " if [ -n \"__CMUX_SURFACE_ID__\" ]; then", - " cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\"}'", + " cmux_relay_report_tty='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"tty_name\":\"'$cmux_bootstrap_tty'\",\"terminal_lifecycle_id\":\"__CMUX_TERMINAL_LIFECYCLE_ID__\",\"attempt_id\":\"__CMUX_SSH_ATTEMPT_ID__\"}'", " cmux_relay_ports_kick='{\"workspace_id\":\"__CMUX_WORKSPACE_ID__\",\"surface_id\":\"__CMUX_SURFACE_ID__\",\"reason\":\"command\"}'", " fi", " env -u CMUX_SOCKET CMUX_SOCKET_PATH=\"127.0.0.1:\(remoteRelayPort)\" \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift index 6beda80c9574..3db9a1190799 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface3.swift @@ -325,52 +325,6 @@ extension ControlCommandCoordinator { } } - // MARK: - report_tty - - /// `surface.report_tty` — record a reported TTY name. - func surfaceReportTTY(_ params: [String: JSONValue]) -> ControlCallResult { - guard let workspaceID = uuid(params, "workspace_id") else { - return .err(code: "invalid_params", message: "Missing or invalid workspace_id", data: nil) - } - let requestedSurfaceID = uuid(params, "surface_id") - if hasNonNull(params, "surface_id"), requestedSurfaceID == nil { - return .err(code: "invalid_params", message: "Missing or invalid surface_id", data: nil) - } - guard let ttyName = rawString(params, "tty_name")? - .trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty else { - return .err(code: "invalid_params", message: "Missing tty_name", data: nil) - } - - let resolution = context?.controlSurfaceReportTTY( - workspaceID: workspaceID, - requestedSurfaceID: requestedSurfaceID, - ttyName: ttyName - ) ?? .workspaceNotFound - let requestedSurfaceData = surfaceReportSurfaceFields( - workspaceID: workspaceID, - requestedSurfaceID: requestedSurfaceID - ) - switch resolution { - case .workspaceNotFound: - return .err(code: "not_found", message: "Workspace not found", data: .object(requestedSurfaceData)) - case .surfaceNotFound: - return .err(code: "not_found", message: "Surface not found", data: .object(requestedSurfaceData)) - case .pending: - var payload = requestedSurfaceData - payload["tty_name"] = .string(ttyName) - payload["pending"] = .bool(true) - return .ok(.object(payload)) - case .recorded(let surfaceID): - return .ok(.object([ - "workspace_id": .string(workspaceID.uuidString), - "workspace_ref": ref(.workspace, workspaceID), - "surface_id": .string(surfaceID.uuidString), - "surface_ref": ref(.surface, surfaceID), - "tty_name": .string(ttyName), - ])) - } - } - // MARK: - report_pwd /// `surface.report_pwd` — record a surface's current working directory. diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift new file mode 100644 index 000000000000..ce8c20c58b77 --- /dev/null +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+SurfaceReportTTY.swift @@ -0,0 +1,70 @@ +internal import Foundation + +/// The authenticated `surface.report_tty` write path. Kept separate because +/// remote reports carry terminal-runtime identity in addition to surface scope. +extension ControlCommandCoordinator { + func surfaceReportTTY(_ params: [String: JSONValue]) -> ControlCallResult { + guard let workspaceID = uuid(params, "workspace_id") else { + return .err(code: "invalid_params", message: "Missing or invalid workspace_id", data: nil) + } + let requestedSurfaceID = uuid(params, "surface_id") + if hasNonNull(params, "surface_id"), requestedSurfaceID == nil { + return .err(code: "invalid_params", message: "Missing or invalid surface_id", data: nil) + } + guard let ttyName = rawString(params, "tty_name")? + .trimmingCharacters(in: .whitespacesAndNewlines), !ttyName.isEmpty else { + return .err(code: "invalid_params", message: "Missing tty_name", data: nil) + } + + let authenticatedRemoteWorkspaceID = string( + params, + "_cmux_remote_workspace_id" + ).flatMap(UUID.init(uuidString:)) + let terminalLifecycleID = string(params, "terminal_lifecycle_id") + .flatMap(UUID.init(uuidString:)) + let attemptID = string(params, "attempt_id").flatMap(UUID.init(uuidString:)) + for (key, value) in [ + ("_cmux_remote_workspace_id", authenticatedRemoteWorkspaceID), + ("terminal_lifecycle_id", terminalLifecycleID), + ("attempt_id", attemptID), + ] where hasNonNull(params, key) && value == nil { + return .err( + code: "invalid_params", + message: "Missing or invalid \(key)", + data: nil + ) + } + + let resolution = context?.controlSurfaceReportTTY( + workspaceID: workspaceID, + requestedSurfaceID: requestedSurfaceID, + ttyName: ttyName, + authenticatedRemoteWorkspaceID: authenticatedRemoteWorkspaceID, + terminalLifecycleID: terminalLifecycleID, + attemptID: attemptID + ) ?? .workspaceNotFound + let requestedSurfaceData = surfaceReportSurfaceFields( + workspaceID: workspaceID, + requestedSurfaceID: requestedSurfaceID + ) + switch resolution { + case .workspaceNotFound: + return .err(code: "not_found", message: "Workspace not found", data: .object(requestedSurfaceData)) + case .surfaceNotFound: + return .err(code: "not_found", message: "Surface not found", data: .object(requestedSurfaceData)) + case .pending: + var payload = requestedSurfaceData + payload["tty_name"] = .string(ttyName) + payload["pending"] = .bool(true) + return .ok(.object(payload)) + case .recorded(let surfaceID): + return .ok(.object([ + "workspace_id": .string(workspaceID.uuidString), + "workspace_ref": ref(.workspace, workspaceID), + "surface_id": .string(surfaceID.uuidString), + "surface_ref": ref(.surface, surfaceID), + "tty_name": .string(ttyName), + ])) + } + } +} diff --git a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift index 8f7938b57f10..810e7f1f98e0 100644 --- a/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift +++ b/Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlSurfaceContext.swift @@ -287,11 +287,17 @@ public protocol ControlSurfaceContext: AnyObject { /// - workspaceID: The target workspace. /// - requestedSurfaceID: The explicit `surface_id`, or `nil` to resolve. /// - ttyName: The reported (trimmed, non-empty) TTY name. + /// - authenticatedRemoteWorkspaceID: Relay-authenticated origin, when remote. + /// - terminalLifecycleID: Runtime lifecycle carried by a remote report. + /// - attemptID: Attach attempt carried by a remote report. /// - Returns: The report resolution. func controlSurfaceReportTTY( workspaceID: UUID, requestedSurfaceID: UUID?, - ttyName: String + ttyName: String, + authenticatedRemoteWorkspaceID: UUID?, + terminalLifecycleID: UUID?, + attemptID: UUID? ) -> ControlSurfaceReportTTYResolution /// Records a reported current working directory for `surface.report_pwd`. diff --git a/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift b/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift index 3f2b980db477..c3302a8a9c7d 100644 --- a/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift +++ b/Packages/macOS/CmuxControlSocket/Tests/CmuxControlSocketTests/ControlCommandContextTestStubs.swift @@ -515,7 +515,14 @@ extension ControlSurfaceContext { nonisolated func controlSurfaceParseShellActivityState(_ rawState: String) -> String? { nil } nonisolated func controlSurfaceParsePortScanKickReason(_ rawReason: String) -> String? { nil } - func controlSurfaceReportTTY(workspaceID: UUID, requestedSurfaceID: UUID?, ttyName: String) + func controlSurfaceReportTTY( + workspaceID: UUID, + requestedSurfaceID: UUID?, + ttyName: String, + authenticatedRemoteWorkspaceID: UUID?, + terminalLifecycleID: UUID?, + attemptID: UUID? + ) -> ControlSurfaceReportTTYResolution { .workspaceNotFound } func controlSurfaceReportPWD(workspaceID: UUID, requestedSurfaceID: UUID?, path: String) -> ControlSurfaceReportPWDResolution { .workspaceNotFound } diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift index 590c7d54b72e..6de38d3e3558 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/MoshTerminalCommandBuilder.swift @@ -135,6 +135,10 @@ public struct MoshTerminalCommandBuilder: Sendable { "fi", "unset cmux_mosh_probe_status", ] + let reportsTerminalLifecycle = remoteRelayPort.map { (1...65_535).contains($0) } ?? false + if reportsTerminalLifecycle { + script += terminalLifecycleAttemptShellLines() + } if let preparationShellScript = preparationShellScript? .trimmingCharacters(in: .whitespacesAndNewlines), !preparationShellScript.isEmpty { @@ -153,9 +157,8 @@ public struct MoshTerminalCommandBuilder: Sendable { !managementReadyShellScript.isEmpty { script.append(managementReadyShellScript) } - if let remoteRelayPort, - (1...65_535).contains(remoteRelayPort) { - script += terminalLifecycleLaunchingShellLines() + if reportsTerminalLifecycle { + script += terminalLifecycleRegistrationShellLines() } // Mosh exposes no reliable post-UDP-handshake callback, so this // pre-exec launcher must not claim authoritative connected readiness. @@ -163,13 +166,18 @@ public struct MoshTerminalCommandBuilder: Sendable { return "/bin/sh -c \(script.joined(separator: "\n").remoteCommandShellQuoted)" } - private func terminalLifecycleLaunchingShellLines() -> [String] { + private func terminalLifecycleAttemptShellLines() -> [String] { + [ + "CMUX_SSH_ATTEMPT_ID=$(/usr/bin/uuidgen | /usr/bin/tr '[:upper:]' '[:lower:]') || cmux_mosh_fallback", + "export CMUX_SSH_ATTEMPT_ID", + ] + } + + private func terminalLifecycleRegistrationShellLines() -> [String] { [ "cmux_mosh_lifecycle_cli=\"${CMUX_BUNDLED_CLI_PATH:-}\"", "if [ -z \"$cmux_mosh_lifecycle_cli\" ] || [ ! -x \"$cmux_mosh_lifecycle_cli\" ]; then cmux_mosh_lifecycle_cli=\"$(command -v cmux 2>/dev/null || true)\"; fi", "if [ -z \"$cmux_mosh_lifecycle_cli\" ] || [ -z \"${CMUX_SOCKET_PATH:-}\" ] || [ -z \"${CMUX_WORKSPACE_ID:-}\" ] || [ -z \"${CMUX_SURFACE_ID:-}\" ] || [ -z \"${CMUX_TERMINAL_LIFECYCLE_ID:-}\" ]; then cmux_mosh_fallback; fi", - "CMUX_SSH_ATTEMPT_ID=$(/usr/bin/uuidgen | /usr/bin/tr '[:upper:]' '[:lower:]') || cmux_mosh_fallback", - "export CMUX_SSH_ATTEMPT_ID", "cmux_mosh_lifecycle_rpc() { cmux_mosh_lifecycle_method=\"$1\"; cmux_mosh_lifecycle_payload=\"$2\"; cmux_mosh_lifecycle_retry=0; while ! CMUXTERM_CLI_RESPONSE_TIMEOUT_SEC=2 \"$cmux_mosh_lifecycle_cli\" --socket \"$CMUX_SOCKET_PATH\" rpc \"$cmux_mosh_lifecycle_method\" \"$cmux_mosh_lifecycle_payload\" >/dev/null 2>&1; do cmux_mosh_lifecycle_retry=$((cmux_mosh_lifecycle_retry + 1)); if [ \"$cmux_mosh_lifecycle_retry\" -ge 4 ]; then return 1; fi; /bin/sleep 0.1; done; }", "cmux_mosh_launch_payload=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", "cmux_mosh_lifecycle_rpc workspace.remote.terminal_session_launching \"$cmux_mosh_launch_payload\" || cmux_mosh_fallback", diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift index 5e48c707977f..34878d53530c 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteBootstrapStagingCommandBuilder.swift @@ -52,16 +52,18 @@ public struct RemoteBootstrapStagingCommandBuilder: Sendable { "cmux_workspace_id=\"${CMUX_WORKSPACE_ID:-}\"", "cmux_surface_id=\"${CMUX_SURFACE_ID:-}\"", "cmux_terminal_lifecycle_id=\"${CMUX_TERMINAL_LIFECYCLE_ID:-}\"", + "cmux_ssh_attempt_id=\"${CMUX_SSH_ATTEMPT_ID:-}\"", "cmux_remote_bootstrap_b64=\(encodedBootstrapScript.remoteCommandShellQuoted)", "cmux_remote_bootstrap=\"$(printf %s \"$cmux_remote_bootstrap_b64\" | base64 -d 2>/dev/null || printf %s \"$cmux_remote_bootstrap_b64\" | base64 -D 2>/dev/null)\"", "cmux_sed_escape() { printf '%s' \"$1\" | sed 's/[\\/&\\\\]/\\\\&/g'; }", "cmux_workspace_id_escaped=\"$(cmux_sed_escape \"$cmux_workspace_id\")\"", "cmux_surface_id_escaped=\"$(cmux_sed_escape \"$cmux_surface_id\")\"", "cmux_terminal_lifecycle_id_escaped=\"$(cmux_sed_escape \"$cmux_terminal_lifecycle_id\")\"", - "cmux_remote_bootstrap=\"$(printf '%s' \"$cmux_remote_bootstrap\" | sed \"s/__CMUX_WORKSPACE_ID__/$cmux_workspace_id_escaped/g; s/__CMUX_SURFACE_ID__/$cmux_surface_id_escaped/g; s/__CMUX_TERMINAL_LIFECYCLE_ID__/$cmux_terminal_lifecycle_id_escaped/g\")\"", + "cmux_ssh_attempt_id_escaped=\"$(cmux_sed_escape \"$cmux_ssh_attempt_id\")\"", + "cmux_remote_bootstrap=\"$(printf '%s' \"$cmux_remote_bootstrap\" | sed \"s/__CMUX_WORKSPACE_ID__/$cmux_workspace_id_escaped/g; s/__CMUX_SURFACE_ID__/$cmux_surface_id_escaped/g; s/__CMUX_TERMINAL_LIFECYCLE_ID__/$cmux_terminal_lifecycle_id_escaped/g; s/__CMUX_SSH_ATTEMPT_ID__/$cmux_ssh_attempt_id_escaped/g\")\"", "printf '%s' \"$cmux_remote_bootstrap\" | command \(sshPrefix) -T \(destination.remoteCommandShellQuoted) \(installCommand.remoteCommandShellQuoted)", "cmux_remote_install_status=$?", - "unset cmux_remote_bootstrap cmux_remote_bootstrap_b64 cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id cmux_workspace_id_escaped cmux_surface_id_escaped cmux_terminal_lifecycle_id_escaped", + "unset cmux_remote_bootstrap cmux_remote_bootstrap_b64 cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id cmux_ssh_attempt_id cmux_workspace_id_escaped cmux_surface_id_escaped cmux_terminal_lifecycle_id_escaped cmux_ssh_attempt_id_escaped", "(exit \"$cmux_remote_install_status\")", ].joined(separator: "\n") } diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift index 1f0fbdb78a9b..6e6a2d502686 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/MoshTerminalCommandBuilderTests.swift @@ -192,6 +192,30 @@ struct MoshTerminalCommandBuilderTests { } } + @Test("creates the attach attempt before staging the remote bootstrap") + func preparationSeesCurrentAttempt() throws { + try withFakeCommands(sshStatus: 0) { directory, environment in + let attemptFile = directory.appendingPathComponent("staged-attempt") + let result = try run( + builder( + preparationShellScript: + "printf '%s' \"$CMUX_SSH_ATTEMPT_ID\" > '\(attemptFile.path)'", + remoteRelayPort: 64_007 + ), + environment: environment + ) + let stagedAttempt = try String(contentsOf: attemptFile, encoding: .utf8) + let lifecycleCalls = try String( + contentsOf: directory.appendingPathComponent("cmux.args"), + encoding: .utf8 + ) + + #expect(result.status == 0) + #expect(UUID(uuidString: stagedAttempt) != nil) + #expect(lifecycleCalls.contains(#""attempt_id":"\#(stagedAttempt)""#)) + } + } + @Test("does not report connected before the Mosh transport establishes") func failedMoshDoesNotReportConnected() throws { try withFakeCommands(sshStatus: 0, moshStatus: 71) { directory, environment in diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift index 4b9e20741dd0..e25e37857103 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteBootstrapStagingCommandBuilderTests.swift @@ -27,7 +27,7 @@ struct RemoteBootstrapStagingCommandBuilderTests { let padding = String(repeating: "# bootstrap padding 0123456789\n", count: 20_000) let bootstrap = """ - printf '%s\\n' 'workspace=__CMUX_WORKSPACE_ID__ surface=__CMUX_SURFACE_ID__ lifecycle=__CMUX_TERMINAL_LIFECYCLE_ID__' + printf '%s\\n' 'workspace=__CMUX_WORKSPACE_ID__ surface=__CMUX_SURFACE_ID__ lifecycle=__CMUX_TERMINAL_LIFECYCLE_ID__ attempt=__CMUX_SSH_ATTEMPT_ID__' \(padding) """ let builder = try #require(RemoteBootstrapStagingCommandBuilder( @@ -41,6 +41,7 @@ struct RemoteBootstrapStagingCommandBuilderTests { "CMUX_WORKSPACE_ID": "workspace-123", "CMUX_SURFACE_ID": "surface-456", "CMUX_TERMINAL_LIFECYCLE_ID": "lifecycle-789", + "CMUX_SSH_ATTEMPT_ID": "attempt-012", "CMUX_REMOTE_HOME": remoteHome.path, "CMUX_SSH_ARGUMENTS": directory.appendingPathComponent("ssh.args").path, ] @@ -56,11 +57,12 @@ struct RemoteBootstrapStagingCommandBuilderTests { let stagedURL = remoteHome.appendingPathComponent(".cmux/relay/52261.bootstrap.sh") let staged = String(decoding: try Data(contentsOf: stagedURL), as: UTF8.self) #expect(staged.contains( - "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789" + "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789 attempt=attempt-012" )) #expect(!staged.contains("__CMUX_WORKSPACE_ID__")) #expect(!staged.contains("__CMUX_SURFACE_ID__")) #expect(!staged.contains("__CMUX_TERMINAL_LIFECYCLE_ID__")) + #expect(!staged.contains("__CMUX_SSH_ATTEMPT_ID__")) #expect(staged.utf8.count > 500_000) let sshArguments = String( @@ -82,7 +84,7 @@ struct RemoteBootstrapStagingCommandBuilderTests { #expect(execution.status == 0) #expect( execution.stdout == - "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789\n" + "workspace=workspace-123 surface=surface-456 lifecycle=lifecycle-789 attempt=attempt-012\n" ) #expect(execution.stderr.isEmpty) } diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift index d8de088661cd..a89cd08ed904 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Core/Model/SurfaceRegistryModel.swift @@ -55,6 +55,9 @@ public final class SurfaceRegistryModel { /// arrives, including when the current runtime reuses the same name. public var runtimeReportedTTYSurfaceIDs: Set = [] + /// Native runtime generation that emitted each current TTY report. + public var runtimeReportedTTYSurfaceGenerations: [UUID: UInt64] = [:] + /// Authenticated remote workspace that originated each live TTY report. /// This provenance follows a remote terminal through container moves. public var remoteTTYReportOriginWorkspaceIDs: [UUID: UUID] = [:] diff --git a/Resources/shell-integration/cmux-bash-integration.bash b/Resources/shell-integration/cmux-bash-integration.bash index 75d6ac47227e..0485aaf821b6 100644 --- a/Resources/shell-integration/cmux-bash-integration.bash +++ b/Resources/shell-integration/cmux-bash-integration.bash @@ -159,10 +159,11 @@ _cmux_report_tty_via_relay() { local workspace_id="" workspace_id="$(_cmux_relay_workspace_id)" || return 1 [[ -n "$_CMUX_TTY_NAME" ]] || return 1 + [[ -n "$CMUX_TERMINAL_LIFECYCLE_ID" && -n "$CMUX_SSH_ATTEMPT_ID" ]] || return 1 local tty_name_json params tty_name_json="$(_cmux_json_escape "$_CMUX_TTY_NAME")" - params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\"" + params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\",\"terminal_lifecycle_id\":\"$CMUX_TERMINAL_LIFECYCLE_ID\",\"attempt_id\":\"$CMUX_SSH_ATTEMPT_ID\"" if [[ -n "$CMUX_PANEL_ID" ]]; then params+=",\"surface_id\":\"$CMUX_PANEL_ID\"" fi diff --git a/Resources/shell-integration/cmux-zsh-integration.zsh b/Resources/shell-integration/cmux-zsh-integration.zsh index 80e60632811e..c3fbdb105263 100644 --- a/Resources/shell-integration/cmux-zsh-integration.zsh +++ b/Resources/shell-integration/cmux-zsh-integration.zsh @@ -169,10 +169,11 @@ _cmux_report_tty_via_relay() { local workspace_id="" workspace_id="$(_cmux_relay_workspace_id)" || return 1 [[ -n "$_CMUX_TTY_NAME" ]] || return 1 + [[ -n "$CMUX_TERMINAL_LIFECYCLE_ID" && -n "$CMUX_SSH_ATTEMPT_ID" ]] || return 1 local tty_name_json params tty_name_json="$(_cmux_json_escape "$_CMUX_TTY_NAME")" - params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\"" + params="{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\",\"terminal_lifecycle_id\":\"$CMUX_TERMINAL_LIFECYCLE_ID\",\"attempt_id\":\"$CMUX_SSH_ATTEMPT_ID\"" if [[ -n "$CMUX_PANEL_ID" ]]; then params+=",\"surface_id\":\"$CMUX_PANEL_ID\"" fi diff --git a/Resources/shell-integration/fish/config.fish b/Resources/shell-integration/fish/config.fish index 884f651d1b19..c4665d6edb9f 100644 --- a/Resources/shell-integration/fish/config.fish +++ b/Resources/shell-integration/fish/config.fish @@ -243,9 +243,11 @@ if test "$_cmux_integration_enabled" != 0 function _cmux_report_tty_via_relay _cmux_socket_uses_remote_relay; or return 1 test -n "$_CMUX_TTY_NAME"; or return 1 + test -n "$CMUX_TERMINAL_LIFECYCLE_ID"; or return 1 + test -n "$CMUX_SSH_ATTEMPT_ID"; or return 1 set -l workspace_id (_cmux_relay_workspace_id); or return 1 set -l tty_name_json (_cmux_json_escape "$_CMUX_TTY_NAME") - set -l params "{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\"" + set -l params "{\"workspace_id\":\"$workspace_id\",\"tty_name\":\"$tty_name_json\",\"terminal_lifecycle_id\":\"$CMUX_TERMINAL_LIFECYCLE_ID\",\"attempt_id\":\"$CMUX_SSH_ATTEMPT_ID\"" if test -n "$CMUX_PANEL_ID" set params "$params,\"surface_id\":\"$CMUX_PANEL_ID\"" end diff --git a/Sources/AgentDeliveryTargetResolution.swift b/Sources/AgentDeliveryTargetResolution.swift index 1b88d017fe2f..459a454ae7ec 100644 --- a/Sources/AgentDeliveryTargetResolution.swift +++ b/Sources/AgentDeliveryTargetResolution.swift @@ -93,6 +93,10 @@ extension Workspace { unchangedPanelIds.contains($0.key) } surfaceRegistry.runtimeReportedTTYSurfaceIDs.formIntersection(unchangedPanelIds) + surfaceRegistry.runtimeReportedTTYSurfaceGenerations = + surfaceRegistry.runtimeReportedTTYSurfaceGenerations.filter { + unchangedPanelIds.contains($0.key) + } } } @@ -104,8 +108,14 @@ extension Workspace { /// runtime can legitimately report the same TTY name as its predecessor. func registerReportedSurfaceTTYName(_ ttyName: String, panelId: UUID) { surfaceTTYNames[panelId] = ttyName + guard let terminal = panels[panelId] as? TerminalPanel else { + invalidateReportedSurfaceTTYRuntime(panelId: panelId) + return + } surfaceRegistry.surfaceTTYDevices[panelId] = CmuxTopProcessSnapshot.deviceIdentifier(forTTYName: ttyName) surfaceRegistry.runtimeReportedTTYSurfaceIDs.insert(panelId) + surfaceRegistry.runtimeReportedTTYSurfaceGenerations[panelId] = + terminal.surface.runtimeSurfaceGeneration } /// Restores display/port-scan metadata without treating the previous @@ -121,6 +131,13 @@ extension Workspace { func invalidateReportedSurfaceTTYRuntime(panelId: UUID) { surfaceRegistry.surfaceTTYDevices.removeValue(forKey: panelId) surfaceRegistry.runtimeReportedTTYSurfaceIDs.remove(panelId) + surfaceRegistry.runtimeReportedTTYSurfaceGenerations.removeValue(forKey: panelId) + } + + func hasCurrentRuntimeReportedTTY(panelId: UUID, terminal: TerminalPanel) -> Bool { + surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId) + && surfaceRegistry.runtimeReportedTTYSurfaceGenerations[panelId] + == terminal.surface.runtimeSurfaceGeneration } func adoptTransferredSurfaceTTYName(from transfer: DetachedSurfaceTransfer) { @@ -129,7 +146,10 @@ extension Workspace { surfaceTTYNames.removeValue(forKey: transfer.panelId) return } - if transfer.ttyNameWasReportedByCurrentRuntime { + if transfer.ttyNameWasReportedByCurrentRuntime, + let terminal = panels[transfer.panelId] as? TerminalPanel, + transfer.ttyReportRuntimeSurfaceGeneration == + terminal.surface.runtimeSurfaceGeneration { registerReportedSurfaceTTYName(ttyName, panelId: transfer.panelId) } else { restorePersistedSurfaceTTYName(ttyName, panelId: transfer.panelId) @@ -158,7 +178,7 @@ extension Workspace { if let liveDevice = terminal.surface.controllingTTYDeviceIdentifier { devices.append(liveDevice) } - if surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId), + if hasCurrentRuntimeReportedTTY(panelId: panelId, terminal: terminal), let reportedDevice = surfaceTTYDevices[panelId], !devices.contains(reportedDevice) { devices.append(reportedDevice) @@ -188,6 +208,8 @@ extension DockSplitStore { } if let transfer = detachedSurfaceTransfersByPanelId[panelId], transfer.ttyNameWasReportedByCurrentRuntime, + transfer.ttyReportRuntimeSurfaceGeneration + == terminal.surface.runtimeSurfaceGeneration, let reportedDevice = transfer.ttyName.flatMap( CmuxTopProcessSnapshot.deviceIdentifier(forTTYName:) ), diff --git a/Sources/AgentRelayTTYTargetResolution.swift b/Sources/AgentRelayTTYTargetResolution.swift index 7a5ec0bc7f94..46a8729e5425 100644 --- a/Sources/AgentRelayTTYTargetResolution.swift +++ b/Sources/AgentRelayTTYTargetResolution.swift @@ -7,11 +7,15 @@ extension Workspace { func registerRelayReportedTTY( _ ttyName: String, panelID: UUID, - authenticatedWorkspaceID: UUID + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID ) -> Bool { - guard panels[panelID] is TerminalPanel, + guard let terminal = panels[panelID] as? TerminalPanel, surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[panelID] == - authenticatedWorkspaceID else { + authenticatedWorkspaceID, + terminal.surface.terminalLifecycleId == terminalLifecycleID, + remoteTerminalAttemptIDsBySurfaceId[panelID] == attemptID else { return false } registerReportedSurfaceTTYName(ttyName, panelId: panelID) @@ -28,7 +32,8 @@ extension Workspace { authenticatedWorkspaceID: UUID ) -> [(binding: TerminalCallerTTYBinding, ttyName: String)] { surfaceRegistry.runtimeReportedTTYSurfaceIDs.compactMap { surfaceID in - guard panels[surfaceID] is TerminalPanel, + guard let terminal = panels[surfaceID] as? TerminalPanel, + hasCurrentRuntimeReportedTTY(panelId: surfaceID, terminal: terminal), surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[surfaceID] == authenticatedWorkspaceID, let ttyName = surfaceRegistry.surfaceTTYNames[surfaceID] else { @@ -65,6 +70,18 @@ extension Workspace { surfaceId: binding.surfaceId ) } + + /// Keeps the launch attempt with a live remote terminal even when its new + /// container is an ordinary workspace with no remote configuration. + func restoreTransferredRelayTTYIdentity(from transfer: DetachedSurfaceTransfer) { + guard transfer.isRemoteTerminal, + transfer.remoteTerminalSessionPhase != .ended, + let attemptID = transfer.remoteTerminalAttemptID else { + remoteTerminalAttemptIDsBySurfaceId.removeValue(forKey: transfer.panelId) + return + } + remoteTerminalAttemptIDsBySurfaceId[transfer.panelId] = attemptID + } } @MainActor @@ -74,7 +91,9 @@ extension AppDelegate { func registerLiveRelayReportedTTY( _ ttyName: String, panelID: UUID, - authenticatedWorkspaceID: UUID + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID ) -> Bool { let owners = agentDeliveryTabManagers().flatMap(\.tabs).filter { $0.panels[panelID] != nil @@ -85,7 +104,9 @@ extension AppDelegate { return owners[0].registerRelayReportedTTY( ttyName, panelID: panelID, - authenticatedWorkspaceID: authenticatedWorkspaceID + authenticatedWorkspaceID: authenticatedWorkspaceID, + terminalLifecycleID: terminalLifecycleID, + attemptID: attemptID ) } diff --git a/Sources/DockSplitStore+RemoteTerminalLiveness.swift b/Sources/DockSplitStore+RemoteTerminalLiveness.swift index b6d1f840fdca..eb4a69ee1c85 100644 --- a/Sources/DockSplitStore+RemoteTerminalLiveness.swift +++ b/Sources/DockSplitStore+RemoteTerminalLiveness.swift @@ -72,6 +72,7 @@ extension DockSplitStore { transfer.remoteTerminalAttemptID = attemptID if beginsNewRuntime { transfer.ttyNameWasReportedByCurrentRuntime = false + transfer.ttyReportRuntimeSurfaceGeneration = nil } setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true @@ -118,7 +119,10 @@ extension DockSplitStore { static func registerReportedRemoteSurfaceTTYName( _ ttyName: String, panelId: UUID, - presentationWorkspaceID: UUID + presentationWorkspaceID: UUID, + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID ) -> Bool { let owners = liveRemoteTerminalStores( presentationWorkspaceID: presentationWorkspaceID @@ -132,7 +136,10 @@ extension DockSplitStore { return owners[0].registerReportedRemoteSurfaceTTYName( ttyName, panelId: panelId, - presentationWorkspaceID: presentationWorkspaceID + presentationWorkspaceID: presentationWorkspaceID, + authenticatedWorkspaceID: authenticatedWorkspaceID, + terminalLifecycleID: terminalLifecycleID, + attemptID: attemptID ) } @@ -145,6 +152,8 @@ extension DockSplitStore { transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, transfer.remoteTerminalSessionPhase != .ended, transfer.ttyNameWasReportedByCurrentRuntime, + transfer.ttyReportRuntimeSurfaceGeneration + == (panels[panelId] as? TerminalPanel)?.surface.runtimeSurfaceGeneration, let ttyName = transfer.ttyName else { return nil } @@ -161,17 +170,24 @@ extension DockSplitStore { private func registerReportedRemoteSurfaceTTYName( _ ttyName: String, panelId: UUID, - presentationWorkspaceID: UUID + presentationWorkspaceID: UUID, + authenticatedWorkspaceID: UUID, + terminalLifecycleID: UUID, + attemptID: UUID ) -> Bool { - guard panels[panelId] != nil, + guard let terminal = panels[panelId] as? TerminalPanel, var transfer = detachedSurfaceTransfersByPanelId[panelId], transfer.isRemoteTerminal, transfer.sessionRestoreWorkspaceId == presentationWorkspaceID, - transfer.remoteTerminalSessionPhase != .ended else { + transfer.sessionRestoreWorkspaceId == authenticatedWorkspaceID, + transfer.remoteTerminalSessionPhase != .ended, + terminal.surface.terminalLifecycleId == terminalLifecycleID, + transfer.remoteTerminalAttemptID == attemptID else { return false } transfer.ttyName = ttyName transfer.ttyNameWasReportedByCurrentRuntime = true + transfer.ttyReportRuntimeSurfaceGeneration = terminal.surface.runtimeSurfaceGeneration setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true } @@ -221,6 +237,7 @@ extension DockSplitStore { terminalLifecycleID ?? transfer.remoteTerminalLifecycleID transfer.remoteTerminalAttemptID = nil transfer.ttyNameWasReportedByCurrentRuntime = false + transfer.ttyReportRuntimeSurfaceGeneration = nil setDetachedSurfaceTransfer(transfer, forPanelID: panelId) return true } diff --git a/Sources/DockSplitStore+SurfaceTransfer.swift b/Sources/DockSplitStore+SurfaceTransfer.swift index 5bc735b28ef8..2cc7e7294e02 100644 --- a/Sources/DockSplitStore+SurfaceTransfer.swift +++ b/Sources/DockSplitStore+SurfaceTransfer.swift @@ -277,6 +277,7 @@ extension DockSplitStore { : nil, ttyName: preservedTransfer?.ttyName, ttyNameWasReportedByCurrentRuntime: preservedTransfer?.ttyNameWasReportedByCurrentRuntime ?? false, + ttyReportRuntimeSurfaceGeneration: preservedTransfer?.ttyReportRuntimeSurfaceGeneration, cachedTitle: panel.displayTitle, customTitle: preservedTransfer?.customTitle, customTitleSource: preservedTransfer?.customTitleSource, diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index 29f53e1ed22b..468a999b6056 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -265,7 +265,9 @@ enum RemoteInteractiveShellBootstrapBuilder { "case \"$cmux_surface_id\" in \"\"|'__CMUX_''SURFACE_ID__') ;; *) export CMUX_SURFACE_ID=\"$cmux_surface_id\"; export CMUX_PANEL_ID=\"$cmux_surface_id\" ;; esac", "cmux_terminal_lifecycle_id='__CMUX_TERMINAL_LIFECYCLE_ID__'", "case \"$cmux_terminal_lifecycle_id\" in \"\"|'__CMUX_''TERMINAL_LIFECYCLE_ID__') ;; *) export CMUX_TERMINAL_LIFECYCLE_ID=\"$cmux_terminal_lifecycle_id\" ;; esac", - "unset cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id", + "cmux_ssh_attempt_id='__CMUX_SSH_ATTEMPT_ID__'", + "case \"$cmux_ssh_attempt_id\" in \"\"|'__CMUX_''SSH_ATTEMPT_ID__') ;; *) export CMUX_SSH_ATTEMPT_ID=\"$cmux_ssh_attempt_id\" ;; esac", + "unset cmux_workspace_id cmux_surface_id cmux_terminal_lifecycle_id cmux_ssh_attempt_id", "hash -r >/dev/null 2>&1 || true", "rehash >/dev/null 2>&1 || true", ]) @@ -373,12 +375,12 @@ enum RemoteInteractiveShellBootstrapBuilder { " mkdir -p \"$HOME/.cmux/relay\" >/dev/null 2>&1 || true", " printf '%s' \"$cmux_relay_tty\" > \"$HOME/.cmux/relay/\(remoteRelayPort).tty\" 2>/dev/null || true", "fi", - "if [ -n \"$cmux_relay_cli\" ] && [ -n \"$CMUX_WORKSPACE_ID\" ] && [ -n \"$cmux_relay_tty\" ] && [ \"$cmux_relay_tty\" != \"not a tty\" ]; then", + "if [ -n \"$cmux_relay_cli\" ] && [ -n \"$CMUX_WORKSPACE_ID\" ] && [ -n \"$CMUX_TERMINAL_LIFECYCLE_ID\" ] && [ -n \"$CMUX_SSH_ATTEMPT_ID\" ] && [ -n \"$cmux_relay_tty\" ] && [ \"$cmux_relay_tty\" != \"not a tty\" ]; then", " (", - " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\"}\"", + " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", " if [ -n \"$CMUX_SURFACE_ID\" ]; then", - " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\"}\"", + " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", " fi", " \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", diff --git a/Sources/TerminalController+ControlSurfaceContext4.swift b/Sources/TerminalController+ControlSurfaceContext4.swift index a30d386340a4..1d80579bf3ae 100644 --- a/Sources/TerminalController+ControlSurfaceContext4.swift +++ b/Sources/TerminalController+ControlSurfaceContext4.swift @@ -25,30 +25,45 @@ extension TerminalController { func controlSurfaceReportTTY( workspaceID: UUID, requestedSurfaceID: UUID?, - ttyName: String + ttyName: String, + authenticatedRemoteWorkspaceID: UUID?, + terminalLifecycleID: UUID?, + attemptID: UUID? ) -> ControlSurfaceReportTTYResolution { guard let tab = controlTabForSidebarMutation(id: workspaceID) else { return .workspaceNotFound } + let relayIdentity = authenticatedRemoteWorkspaceID.flatMap { workspaceID in + terminalLifecycleID.flatMap { lifecycleID in + attemptID.map { (workspaceID, lifecycleID, $0) } + } + } + let hasRelayIdentity = authenticatedRemoteWorkspaceID != nil || + terminalLifecycleID != nil || attemptID != nil let validSurfaceIds = Set(tab.panels.keys) tab.pruneSurfaceMetadata(validSurfaceIds: validSurfaceIds) if let requestedSurfaceID, - tab.isRemoteWorkspace, !validSurfaceIds.contains(requestedSurfaceID), + let relayIdentity, DockSplitStore.registerReportedRemoteSurfaceTTYName( ttyName, panelId: requestedSurfaceID, - presentationWorkspaceID: workspaceID + presentationWorkspaceID: workspaceID, + authenticatedWorkspaceID: relayIdentity.0, + terminalLifecycleID: relayIdentity.1, + attemptID: relayIdentity.2 ) { return .recorded(surfaceID: requestedSurfaceID) } if let requestedSurfaceID, - tab.isRemoteWorkspace, !validSurfaceIds.contains(requestedSurfaceID), + let relayIdentity, AppDelegate.shared?.registerLiveRelayReportedTTY( ttyName, panelID: requestedSurfaceID, - authenticatedWorkspaceID: workspaceID + authenticatedWorkspaceID: relayIdentity.0, + terminalLifecycleID: relayIdentity.1, + attemptID: relayIdentity.2 ) == true { return .recorded(surfaceID: requestedSurfaceID) } @@ -59,18 +74,19 @@ extension TerminalController { validSurfaceIds: validSurfaceIds ) guard let surfaceId, validSurfaceIds.contains(surfaceId) else { - if tab.isRemoteWorkspace, validSurfaceIds.isEmpty { - tab.rememberPendingRemoteSurfaceTTY(ttyName, requestedSurfaceId: requestedSurfaceID) - return .pending - } return .surfaceNotFound } - if tab.isRemoteWorkspace { + if tab.isRemoteWorkspace || + tab.surfaceRegistry.remoteTTYReportOriginWorkspaceIDs[surfaceId] != nil || + hasRelayIdentity { + guard let relayIdentity else { return .surfaceNotFound } guard tab.registerRelayReportedTTY( ttyName, panelID: surfaceId, - authenticatedWorkspaceID: workspaceID + authenticatedWorkspaceID: relayIdentity.0, + terminalLifecycleID: relayIdentity.1, + attemptID: relayIdentity.2 ) else { return .surfaceNotFound } diff --git a/Sources/Workspace+DetachedSurfaceTransfer.swift b/Sources/Workspace+DetachedSurfaceTransfer.swift index 569c9b57d120..1165f0209f2d 100644 --- a/Sources/Workspace+DetachedSurfaceTransfer.swift +++ b/Sources/Workspace+DetachedSurfaceTransfer.swift @@ -38,6 +38,7 @@ extension Workspace { let directoryDisplayLabel: String? var ttyName: String? var ttyNameWasReportedByCurrentRuntime: Bool = false + var ttyReportRuntimeSurfaceGeneration: UInt64? = nil let cachedTitle: String? let customTitle: String? let customTitleSource: Workspace.CustomTitleSource? @@ -92,6 +93,7 @@ extension Workspace { directoryDisplayLabel: directoryDisplayLabel, ttyName: ttyName, ttyNameWasReportedByCurrentRuntime: ttyNameWasReportedByCurrentRuntime, + ttyReportRuntimeSurfaceGeneration: ttyReportRuntimeSurfaceGeneration, cachedTitle: cachedTitle, customTitle: customTitle, customTitleSource: customTitleSource, diff --git a/Sources/Workspace+RemoteRelayCommandRewrite.swift b/Sources/Workspace+RemoteRelayCommandRewrite.swift index 304310af7e79..b71a65060612 100644 --- a/Sources/Workspace+RemoteRelayCommandRewrite.swift +++ b/Sources/Workspace+RemoteRelayCommandRewrite.swift @@ -85,7 +85,8 @@ extension Workspace { surfaceAliases: surfaceAliases, didRewrite: &didRewrite ) as? [String: Any] ?? params - if method == "surface.resume.set" || method == "agent.resolve_delivery_target", + if method == "surface.resume.set" || method == "surface.report_tty" || + method == "agent.resolve_delivery_target", let remoteWorkspaceID { params["_cmux_remote_workspace_id"] = remoteWorkspaceID.uuidString didRewrite = true diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index eca2afd8e48a..85f5eb8334e7 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9819,6 +9819,7 @@ final class Workspace: Identifiable, ObservableObject { } else { surfaceRegistry.remoteTTYReportOriginWorkspaceIDs.removeValue(forKey: detached.panelId) } + restoreTransferredRelayTTYIdentity(from: detached) restoreTransferredSurfaceTTYRuntimeProofIfNeeded(from: detached) if let cleanupConfiguration = detached.remoteCleanupConfiguration { if didAdoptWorkspaceRemoteTracking { @@ -12512,6 +12513,8 @@ extension Workspace: BonsplitDelegate { directoryDisplayLabel: panelDirectoryDisplayLabels[panelId], ttyName: surfaceTTYNames[panelId], ttyNameWasReportedByCurrentRuntime: surfaceRegistry.runtimeReportedTTYSurfaceIDs.contains(panelId), + ttyReportRuntimeSurfaceGeneration: + surfaceRegistry.runtimeReportedTTYSurfaceGenerations[panelId], cachedTitle: cachedTitle, customTitle: panelCustomTitles[panelId], customTitleSource: panelCustomTitles[panelId] != nil diff --git a/cmuxTests/AgentDeliveryTTYBindingTests.swift b/cmuxTests/AgentDeliveryTTYBindingTests.swift index e7db90f12e25..33851a5e90cf 100644 --- a/cmuxTests/AgentDeliveryTTYBindingTests.swift +++ b/cmuxTests/AgentDeliveryTTYBindingTests.swift @@ -73,12 +73,22 @@ extension AgentNotificationRegressionTests { fixture.restore() } fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) #expect( TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.source.id, requestedSurfaceID: fixture.panelId, - ttyName: "pts/2" + ttyName: "pts/2", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID ) == .recorded(surfaceID: fixture.panelId) ) @@ -157,14 +167,24 @@ extension AgentNotificationRegressionTests { fixture.restore() } fixture.source.remoteConfiguration = deliveryTargetRemoteConfiguration() + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) try moveRemoteSurface(fixture, into: dock) #expect( TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.source.id, requestedSurfaceID: fixture.panelId, - ttyName: "pts/3" + ttyName: "pts/3", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID ) == .recorded(surfaceID: fixture.panelId) ) assertRelayTTYTarget( @@ -305,18 +325,22 @@ extension AgentNotificationRegressionTests { fixture.source.trackRemoteTerminalSurface(fixture.panelId) fixture.source.registerReportedSurfaceTTYName("pts/0", panelId: fixture.panelId) try moveRemoteSurface(fixture, into: dock) + let attemptID = UUID() #expect( dock.markRemoteTerminalSessionLaunching( panelId: fixture.panelId, terminalLifecycleID: terminal.surface.terminalLifecycleId, - attemptID: UUID() + attemptID: attemptID ) ) #expect( TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.source.id, requestedSurfaceID: fixture.panelId, - ttyName: "pts/0" + ttyName: "pts/0", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID ) == .recorded(surfaceID: fixture.panelId) ) assertRelayTTYTarget( diff --git a/cmuxTests/AgentNotificationLiveRetargetTests.swift b/cmuxTests/AgentNotificationLiveRetargetTests.swift index d58340a1d903..288d4b29460f 100644 --- a/cmuxTests/AgentNotificationLiveRetargetTests.swift +++ b/cmuxTests/AgentNotificationLiveRetargetTests.swift @@ -198,16 +198,8 @@ extension AgentNotificationRegressionTests { let siblingPanelID = try #require(fixture.claimedWorkspace.focusedPanelId) fixture.claimedWorkspace.trackRemoteTerminalSurface(siblingPanelID) fixture.owningWorkspace.trackRemoteTerminalSurface(fixture.panelId) - #expect(TerminalController.shared.controlSurfaceReportTTY( - workspaceID: fixture.claimedWorkspace.id, - requestedSurfaceID: siblingPanelID, - ttyName: "0" - ) == .recorded(surfaceID: siblingPanelID)) - #expect(TerminalController.shared.controlSurfaceReportTTY( - workspaceID: fixture.owningWorkspace.id, - requestedSurfaceID: fixture.panelId, - ttyName: "0" - ) == .recorded(surfaceID: fixture.panelId)) + fixture.claimedWorkspace.registerReportedSurfaceTTYName("0", panelId: siblingPanelID) + fixture.owningWorkspace.registerReportedSurfaceTTYName("0", panelId: fixture.panelId) let result = TerminalController.shared.v2AgentResolveDeliveryTarget(params: [ "tty_name": "0", diff --git a/cmuxTests/AgentRelayTTYOwnershipTests.swift b/cmuxTests/AgentRelayTTYOwnershipTests.swift index db22b64472d7..79d4484ab433 100644 --- a/cmuxTests/AgentRelayTTYOwnershipTests.swift +++ b/cmuxTests/AgentRelayTTYOwnershipTests.swift @@ -47,7 +47,14 @@ extension AgentNotificationRegressionTests { destination: "source.example.invalid", relayPort: 64_007 ) + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) fixture.source.registerReportedSurfaceTTYName("pts/21", panelId: fixture.panelId) let paneID = try #require(fixture.source.bonsplitController.allPaneIds.first) _ = try #require(fixture.source.newTerminalSurface(inPane: paneID, focus: false)) @@ -58,7 +65,10 @@ extension AgentNotificationRegressionTests { TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.source.id, requestedSurfaceID: fixture.panelId, - ttyName: "pts/22" + ttyName: "pts/22", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID ) == .recorded(surfaceID: fixture.panelId) ) assertRelayTTYTarget( @@ -81,7 +91,14 @@ extension AgentNotificationRegressionTests { destination: "source.example.invalid", relayPort: 64_007 ) + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) fixture.source.registerReportedSurfaceTTYName("pts/23", panelId: fixture.panelId) fixture.source.disconnectRemoteConnection() @@ -94,7 +111,10 @@ extension AgentNotificationRegressionTests { TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.source.id, requestedSurfaceID: fixture.panelId, - ttyName: "pts/24" + ttyName: "pts/24", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID ) == .surfaceNotFound ) assertNoRelayTTYTarget( @@ -111,7 +131,14 @@ extension AgentNotificationRegressionTests { destination: "source.example.invalid", relayPort: 64_007 ) + let terminal = try #require(fixture.source.panels[fixture.panelId] as? TerminalPanel) + let attemptID = UUID() fixture.source.trackRemoteTerminalSurface(fixture.panelId) + #expect(fixture.source.markRemoteTerminalSessionLaunching( + surfaceId: fixture.panelId, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID + )) fixture.source.registerReportedSurfaceTTYName("pts/25", panelId: fixture.panelId) #expect( fixture.source.markRemoteTerminalSessionEnded( @@ -124,7 +151,10 @@ extension AgentNotificationRegressionTests { TerminalController.shared.controlSurfaceReportTTY( workspaceID: fixture.source.id, requestedSurfaceID: fixture.panelId, - ttyName: "pts/26" + ttyName: "pts/26", + authenticatedRemoteWorkspaceID: fixture.source.id, + terminalLifecycleID: terminal.surface.terminalLifecycleId, + attemptID: attemptID ) == .surfaceNotFound ) assertNoRelayTTYTarget( diff --git a/cmuxTests/GhosttyConfigTests.swift b/cmuxTests/GhosttyConfigTests.swift index fc229a5fe0b6..8b7891310a25 100644 --- a/cmuxTests/GhosttyConfigTests.swift +++ b/cmuxTests/GhosttyConfigTests.swift @@ -5070,11 +5070,13 @@ final class ZshShellIntegrationHandoffTests: XCTestCase { "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", "CMUX_TAB_ID": "22222222-2222-2222-2222-222222222222", "CMUX_PANEL_ID": "22222222-2222-2222-2222-222222222222", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", ] ) XCTAssertTrue( - output.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys777","surface_id":"22222222-2222-2222-2222-222222222222"}"#), + output.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys777","terminal_lifecycle_id":"33333333-3333-3333-3333-333333333333","attempt_id":"44444444-4444-4444-4444-444444444444","surface_id":"22222222-2222-2222-2222-222222222222"}"#), output ) } @@ -5207,11 +5209,13 @@ final class ZshShellIntegrationHandoffTests: XCTestCase { "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", "CMUX_TAB_ID": "22222222-2222-2222-2222-222222222222", "CMUX_PANEL_ID": "22222222-2222-2222-2222-222222222222", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", ] ) XCTAssertTrue( - result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys888","surface_id":"22222222-2222-2222-2222-222222222222"}"#), + result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys888","terminal_lifecycle_id":"33333333-3333-3333-3333-333333333333","attempt_id":"44444444-4444-4444-4444-444444444444","surface_id":"22222222-2222-2222-2222-222222222222"}"#), result.stdout ) } @@ -5254,11 +5258,13 @@ final class ZshShellIntegrationHandoffTests: XCTestCase { "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", "CMUX_TAB_ID": "22222222-2222-2222-2222-222222222222", "CMUX_PANEL_ID": "", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", ] ) XCTAssertTrue( - result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys889"}"#), + result.stdout.contains(#"rpc surface.report_tty {"workspace_id":"11111111-1111-1111-1111-111111111111","tty_name":"ttys889","terminal_lifecycle_id":"33333333-3333-3333-3333-333333333333","attempt_id":"44444444-4444-4444-4444-444444444444"}"#), result.stdout ) XCTAssertTrue( From 1dd6ab0944a078b4fd96e3c84b0e5fbebd30281d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 13:02:47 -0700 Subject: [PATCH 33/35] test: cover Grok restore routing --- cmuxTests/CMUXCLIErrorOutputRegressionTests.swift | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift index b03587e78797..990013bbd8ec 100644 --- a/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift +++ b/cmuxTests/CMUXCLIErrorOutputRegressionTests.swift @@ -636,9 +636,10 @@ import Testing XCTAssertEqual(requiredResponder.receivedRequests.count, 2) } - @Test func testRestorePrefersLiveProcessTargetOverStaleAmbientRouting() throws { + @Test(arguments: ["pi", "grok"]) + func testRestorePrefersLiveProcessTargetOverStaleAmbientRouting(kind: String) throws { let cliPath = try bundledCLIPath() - let checkpointID = "pi-\(UUID().uuidString.lowercased())" + let checkpointID = "\(kind)-\(UUID().uuidString.lowercased())" let staleSurfaceID = UUID().uuidString let staleTTYSurfaceID = UUID().uuidString let currentSurfaceID = UUID().uuidString @@ -657,7 +658,7 @@ import Testing let restoreResponse = try restoreResponse(result: [ "restore_record": [ "mode": "direct", - "kind": "pi", + "kind": kind, "checkpoint_id": checkpointID, "environment": [:], "launch_command": [ @@ -684,7 +685,7 @@ import Testing let result = runProcess( executablePath: cliPath, - arguments: ["restore", "pi", checkpointID], + arguments: ["restore", kind, checkpointID], environment: environment, timeout: 5 ) From 48157de9f111813a93c50732e765bd7768a1a847 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 13:20:44 -0700 Subject: [PATCH 34/35] test: cover relay TTY readiness gaps --- ...RemoteTmuxSessionCommandBuilderTests.swift | 6 ++ cmuxTests/FishShellIntegrationTests.swift | 12 ++- .../RemoteInitialCommandBootstrapTests.swift | 67 ++++++++++++++++ cmuxTests/RemoteShellPromptRelayTests.swift | 80 +++++++++++++++++++ .../ShellIntegrationSendTransportTests.swift | 11 ++- 5 files changed, 169 insertions(+), 7 deletions(-) diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift index 3591cdf7cc44..cedcb695dbaf 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift @@ -148,14 +148,18 @@ struct RemoteTmuxSessionCommandBuilderTests { ) let currentWorkspace = "11111111-1111-1111-1111-111111111111" let currentSocket = "127.0.0.1:55272" + let currentLifecycle = "33333333-3333-3333-3333-333333333333" + let currentAttempt = "44444444-4444-4444-4444-444444444444" let result = try run(builder.remoteShellCommand, environment: environment.merging([ "CMUX_BUNDLED_CLI_PATH": "/home/dev/.cmux/bin/cmux", "CMUX_PERSISTENT_PTY_EXEC_HELPER": "/home/dev/.cmux/bin/cmux", "CMUX_PANEL_ID": "22222222-2222-2222-2222-222222222222", "CMUX_SHELL_INTEGRATION_DIR": "/home/dev/.cmux/relay/55272.shell", "CMUX_SOCKET_PATH": currentSocket, + "CMUX_SSH_ATTEMPT_ID": currentAttempt, "CMUX_SURFACE_ID": "22222222-2222-2222-2222-222222222222", "CMUX_TAB_ID": currentWorkspace, + "CMUX_TERMINAL_LIFECYCLE_ID": currentLifecycle, "CMUX_WORKSPACE_ID": currentWorkspace, ]) { _, current in current }) @@ -168,7 +172,9 @@ struct RemoteTmuxSessionCommandBuilderTests { ["set-environment", "-t", "=existing", "CMUX_PERSISTENT_PTY_EXEC_HELPER", "/home/dev/.cmux/bin/cmux"], ["set-environment", "-t", "=existing", "CMUX_SHELL_INTEGRATION_DIR", "/home/dev/.cmux/relay/55272.shell"], ["set-environment", "-t", "=existing", "CMUX_SOCKET_PATH", currentSocket], + ["set-environment", "-t", "=existing", "CMUX_SSH_ATTEMPT_ID", currentAttempt], ["set-environment", "-t", "=existing", "CMUX_TAB_ID", currentWorkspace], + ["set-environment", "-t", "=existing", "CMUX_TERMINAL_LIFECYCLE_ID", currentLifecycle], ["set-environment", "-t", "=existing", "CMUX_WORKSPACE_ID", currentWorkspace], ["set-environment", "-t", "=existing", "-u", "CMUX_PANEL_ID"], ["set-environment", "-t", "=existing", "-u", "CMUX_SURFACE_ID"], diff --git a/cmuxTests/FishShellIntegrationTests.swift b/cmuxTests/FishShellIntegrationTests.swift index 6251be2f1b53..ff891ae1282c 100644 --- a/cmuxTests/FishShellIntegrationTests.swift +++ b/cmuxTests/FishShellIntegrationTests.swift @@ -222,15 +222,15 @@ struct FishShellIntegrationTests { function tmux if test "$argv[1]" = show-environment if test "$argv[2]" = -g - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_TAB_ID=stale-workspace' 'CMUX_WORKSPACE_ID=stale-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_SSH_ATTEMPT_ID=stale-attempt' 'CMUX_TAB_ID=stale-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=stale-lifecycle' 'CMUX_WORKSPACE_ID=stale-workspace' else - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_TAB_ID=current-workspace' 'CMUX_WORKSPACE_ID=current-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_SSH_ATTEMPT_ID=current-attempt' 'CMUX_TAB_ID=current-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=current-lifecycle' 'CMUX_WORKSPACE_ID=current-workspace' end end end _cmux_tmux_sync_cmux_environment - printf 'workspace=%s\\nsocket=%s\\nsurface=%s\\npanel=%s\\n' \ - "$CMUX_WORKSPACE_ID" "$CMUX_SOCKET_PATH" \ + printf 'workspace=%s\\nsocket=%s\\nlifecycle=%s\\nattempt=%s\\nsurface=%s\\npanel=%s\\n' \ + "$CMUX_WORKSPACE_ID" "$CMUX_SOCKET_PATH" "$CMUX_TERMINAL_LIFECYCLE_ID" "$CMUX_SSH_ATTEMPT_ID" \ (set -q CMUX_SURFACE_ID; and printf %s "$CMUX_SURFACE_ID"; or printf %s '') \ (set -q CMUX_PANEL_ID; and printf %s "$CMUX_PANEL_ID"; or printf %s '') """, @@ -239,6 +239,8 @@ struct FishShellIntegrationTests { "CMUX_SOCKET_PATH": "127.0.0.1:63135", "CMUX_SURFACE_ID": "stale-surface", "CMUX_TAB_ID": "stale-workspace", + "CMUX_TERMINAL_LIFECYCLE_ID": "stale-lifecycle", + "CMUX_SSH_ATTEMPT_ID": "stale-attempt", "CMUX_WORKSPACE_ID": "stale-workspace", "TMUX": "/tmp/tmux-test,1,0", ] @@ -246,6 +248,8 @@ struct FishShellIntegrationTests { expectTrue(result.stdout.contains("workspace=current-workspace"), result.stdout) expectTrue(result.stdout.contains("socket=127.0.0.1:55272"), result.stdout) + expectTrue(result.stdout.contains("lifecycle=current-lifecycle"), result.stdout) + expectTrue(result.stdout.contains("attempt=current-attempt"), result.stdout) expectTrue(result.stdout.contains("surface="), result.stdout) expectTrue(result.stdout.contains("panel="), result.stdout) } diff --git a/cmuxTests/RemoteInitialCommandBootstrapTests.swift b/cmuxTests/RemoteInitialCommandBootstrapTests.swift index 690aa0e3ad3b..1010f116f986 100644 --- a/cmuxTests/RemoteInitialCommandBootstrapTests.swift +++ b/cmuxTests/RemoteInitialCommandBootstrapTests.swift @@ -334,6 +334,73 @@ struct RemoteInitialCommandBootstrapTests { #expect(recordedInvocations == "execute|\(home.path)|remote-only\ninteractive\ninteractive\n") } + @Test("relay TTY registration completes before the interactive shell starts") + func relayTTYRegistrationCompletesBeforeInteractiveShellStarts() throws { + let fileManager = FileManager.default + let root = fileManager.temporaryDirectory + .appendingPathComponent("cmux-relay-ready-bootstrap-\(UUID().uuidString)") + let home = root.appendingPathComponent("home") + let bin = root.appendingPathComponent("bin") + let cmuxBin = home.appendingPathComponent(".cmux/bin") + let fakeCmux = cmuxBin.appendingPathComponent("cmux") + let fakeShell = bin.appendingPathComponent("test-shell") + let reportStatus = root.appendingPathComponent("report-status") + let shellStarted = root.appendingPathComponent("shell-started") + try fileManager.createDirectory(at: cmuxBin, withIntermediateDirectories: true) + try fileManager.createDirectory(at: bin, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: root) } + + let persistentPTYExecHelper = try writePersistentPTYExecHelper(to: bin) + try """ + #!/bin/sh + if [ "${1:-}" = rpc ] && [ "${2:-}" = surface.report_tty ]; then + cmux_wait_count=0 + while [ "$cmux_wait_count" -lt 100 ] && [ ! -e "$CMUX_TEST_SHELL_STARTED" ]; do + cmux_wait_count=$((cmux_wait_count + 1)) + sleep 0.01 + done + if [ -e "$CMUX_TEST_SHELL_STARTED" ]; then + printf raced > "$CMUX_TEST_REPORT_STATUS" + else + printf ready > "$CMUX_TEST_REPORT_STATUS" + fi + fi + printf '{"ok":true}\\n' + """.write(to: fakeCmux, atomically: true, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: fakeCmux.path) + try """ + #!/bin/sh + : > "$CMUX_TEST_SHELL_STARTED" + cmux_wait_count=0 + while [ "$cmux_wait_count" -lt 100 ] && [ ! -s "$CMUX_TEST_REPORT_STATUS" ]; do + cmux_wait_count=$((cmux_wait_count + 1)) + sleep 0.01 + done + cat "$CMUX_TEST_REPORT_STATUS" + """.write(to: fakeShell, atomically: true, encoding: .utf8) + try fileManager.setAttributes([.posixPermissions: 0o700], ofItemAtPath: fakeShell.path) + + let script = RemoteInteractiveShellBootstrapBuilder.script( + remoteRelayPort: 64011, + shellFeatures: "ssh-env,ssh-terminfo" + ) + let result = try runShell(script, environment: [ + "CMUX_BOOTSTRAP_TTY": "ttys990", + "CMUX_PERSISTENT_PTY_EXEC_HELPER": persistentPTYExecHelper.path, + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_TEST_REPORT_STATUS": reportStatus.path, + "CMUX_TEST_SHELL_STARTED": shellStarted.path, + "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", + "HOME": home.path, + "PATH": "\(bin.path):/usr/bin:/bin", + "SHELL": fakeShell.path, + ]) + + #expect(result.status == 0, "stdout: \(result.stdout)\nstderr: \(result.stderr)") + #expect(result.stdout == "ready") + } + @Test func whitespaceOnlyCommandDoesNotAddBootstrapWork() { let bootstrap = RemoteInitialCommandBootstrap(command: " \n\t ") diff --git a/cmuxTests/RemoteShellPromptRelayTests.swift b/cmuxTests/RemoteShellPromptRelayTests.swift index 0c5e950c6ada..2165ed6b7825 100644 --- a/cmuxTests/RemoteShellPromptRelayTests.swift +++ b/cmuxTests/RemoteShellPromptRelayTests.swift @@ -8,6 +8,13 @@ import Testing @testable import cmux #endif +private let remoteShellPromptFishExecutablePath = [ + "/opt/homebrew/bin/fish", + "/usr/local/bin/fish", + "/usr/bin/fish", + "/bin/fish", +].first { FileManager.default.isExecutableFile(atPath: $0) } + struct RemoteShellPromptRelayTests { @Test("remote zsh prompt reports Git metadata through the relay") func remoteZshPromptReportsGitMetadataThroughRelay() throws { @@ -73,6 +80,79 @@ struct RemoteShellPromptRelayTests { ), Comment(rawValue: output)) } + @Test( + "remote fish retries TTY registration until the relay acknowledges it", + .enabled(if: remoteShellPromptFishExecutablePath != nil) + ) + func remoteFishRetriesTTYRegistrationUntilAcknowledged() throws { + let fish = try #require(remoteShellPromptFishExecutablePath) + let integration = try #require( + RemoteInteractiveShellBootstrapBuilder.bundledShellIntegrationScript(named: "fish/config.fish") + ) + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-fish-relay-tty-\(UUID().uuidString)", isDirectory: true) + let binDirectory = directory.appendingPathComponent("bin", isDirectory: true) + let integrationFile = directory.appendingPathComponent("config.fish") + let cmuxFile = binDirectory.appendingPathComponent("cmux") + let logFile = directory.appendingPathComponent("relay.log") + try FileManager.default.createDirectory(at: binDirectory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + + try integration.write(to: integrationFile, atomically: true, encoding: .utf8) + try Data().write(to: logFile) + try """ + #!/bin/sh + if [ "${1:-}" = rpc ] && [ "${2:-}" = surface.report_tty ]; then + printf 'call\\n' >> "$CMUX_TEST_LOG" + [ "$(/usr/bin/wc -l < "$CMUX_TEST_LOG")" -gt 1 ] || exit 1 + fi + printf '{"ok":true}\\n' + """.write(to: cmuxFile, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: cmuxFile.path) + + let process = Process() + let standardOutput = Pipe() + let standardError = Pipe() + process.executableURL = URL(fileURLWithPath: fish) + process.arguments = [ + "-c", + """ + source '\(integrationFile.path)' + set -g _CMUX_TTY_NAME ttys990 + set -g _CMUX_TTY_REPORTED 0 + _cmux_report_tty_once + _cmux_report_tty_once + for _cmux_i in (seq 1 20) + test -s "$CMUX_TEST_LOG"; and break + sleep 0.05 + end + printf 'calls=%s\\nreported=%s\\n' (count (cat "$CMUX_TEST_LOG")) "$_CMUX_TTY_REPORTED" + """, + ] + process.environment = [ + "CMUX_BUNDLED_CLI_PATH": cmuxFile.path, + "CMUX_SOCKET_PATH": "127.0.0.1:64011", + "CMUX_SSH_ATTEMPT_ID": "44444444-4444-4444-4444-444444444444", + "CMUX_TAB_ID": "11111111-1111-1111-1111-111111111111", + "CMUX_TERMINAL_LIFECYCLE_ID": "33333333-3333-3333-3333-333333333333", + "CMUX_TEST_LOG": logFile.path, + "CMUX_WORKSPACE_ID": "11111111-1111-1111-1111-111111111111", + "HOME": directory.path, + "PATH": "\(binDirectory.path):/usr/bin:/bin", + "TERM": "xterm-256color", + ] + process.standardOutput = standardOutput + process.standardError = standardError + try process.run() + process.waitUntilExit() + let output = String(decoding: standardOutput.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + let error = String(decoding: standardError.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + + #expect(process.terminationStatus == 0, "\(error)\n\(output)") + #expect(output.contains("calls=2"), Comment(rawValue: output)) + #expect(output.contains("reported=1"), Comment(rawValue: output)) + } + private func runPrompt( shell: String, integrationName: String, diff --git a/cmuxTests/ShellIntegrationSendTransportTests.swift b/cmuxTests/ShellIntegrationSendTransportTests.swift index 2c569e38aae6..6a6448a296c0 100644 --- a/cmuxTests/ShellIntegrationSendTransportTests.swift +++ b/cmuxTests/ShellIntegrationSendTransportTests.swift @@ -161,6 +161,8 @@ struct ShellIntegrationSendTransportTests { "CMUX_SOCKET_PATH": "127.0.0.1:63135", "CMUX_SURFACE_ID": "stale-surface", "CMUX_TAB_ID": "stale-workspace", + "CMUX_TERMINAL_LIFECYCLE_ID": "stale-lifecycle", + "CMUX_SSH_ATTEMPT_ID": "stale-attempt", "CMUX_WORKSPACE_ID": "stale-workspace", "HOME": directory.path, "PATH": "/usr/bin:/bin", @@ -177,6 +179,8 @@ struct ShellIntegrationSendTransportTests { #expect(process.terminationStatus == 0, "\(error)\n\(output)") #expect(output.contains("workspace=current-workspace"), Comment(rawValue: output)) #expect(output.contains("socket=127.0.0.1:55272"), Comment(rawValue: output)) + #expect(output.contains("lifecycle=current-lifecycle"), Comment(rawValue: output)) + #expect(output.contains("attempt=current-attempt"), Comment(rawValue: output)) #expect(output.contains("surface="), Comment(rawValue: output)) #expect(output.contains("panel="), Comment(rawValue: output)) } @@ -361,15 +365,16 @@ struct ShellIntegrationSendTransportTests { tmux() { if [ "$1" = show-environment ]; then if [ "${2:-}" = -g ]; then - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_TAB_ID=stale-workspace' 'CMUX_WORKSPACE_ID=stale-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:63135' 'CMUX_SSH_ATTEMPT_ID=stale-attempt' 'CMUX_TAB_ID=stale-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=stale-lifecycle' 'CMUX_WORKSPACE_ID=stale-workspace' else - printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_TAB_ID=current-workspace' 'CMUX_WORKSPACE_ID=current-workspace' + printf '%s\\n' 'CMUX_SOCKET_PATH=127.0.0.1:55272' 'CMUX_SSH_ATTEMPT_ID=current-attempt' 'CMUX_TAB_ID=current-workspace' 'CMUX_TERMINAL_LIFECYCLE_ID=current-lifecycle' 'CMUX_WORKSPACE_ID=current-workspace' fi fi } _cmux_tmux_sync_cmux_environment - printf 'workspace=%s\\nsocket=%s\\nsurface=%s\\npanel=%s\\n' \ + printf 'workspace=%s\\nsocket=%s\\nlifecycle=%s\\nattempt=%s\\nsurface=%s\\npanel=%s\\n' \ "${CMUX_WORKSPACE_ID:-}" "${CMUX_SOCKET_PATH:-}" \ + "${CMUX_TERMINAL_LIFECYCLE_ID:-}" "${CMUX_SSH_ATTEMPT_ID:-}" \ "${CMUX_SURFACE_ID:-}" "${CMUX_PANEL_ID:-}" """ } From e693ac2cfae88db1bce918e23bbcfd44c4479222 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Sat, 1 Aug 2026 13:26:29 -0700 Subject: [PATCH 35/35] fix: wait for relay TTY readiness --- .../RemoteTmuxSessionCommandBuilder.swift | 2 ++ ...RemoteTmuxSessionCommandBuilderTests.swift | 6 ++++++ .../cmux-bash-integration.bash | 2 ++ .../cmux-zsh-integration.zsh | 2 ++ Resources/shell-integration/fish/config.fish | 19 +++++++++++++++++-- ...moteInteractiveShellBootstrapBuilder.swift | 18 ++++++++---------- 6 files changed, 37 insertions(+), 12 deletions(-) diff --git a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift index a934b9d5a6d5..c6a974c595ea 100644 --- a/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift +++ b/Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/RemoteTmuxSessionCommandBuilder.swift @@ -64,7 +64,9 @@ public struct RemoteTmuxSessionCommandBuilder: Sendable { "CMUX_SHELL_INTEGRATION", "CMUX_SHELL_INTEGRATION_DIR", "CMUX_SOCKET_PATH", + "CMUX_SSH_ATTEMPT_ID", "CMUX_TAB_ID", + "CMUX_TERMINAL_LIFECYCLE_ID", "CMUX_WORKSPACE_ID", ] diff --git a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift index cedcb695dbaf..01723cd96b95 100644 --- a/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift +++ b/Packages/macOS/CmuxFoundation/Tests/CmuxFoundationTests/RemoteTmuxSessionCommandBuilderTests.swift @@ -25,7 +25,9 @@ struct RemoteTmuxSessionCommandBuilderTests { "-e", "CMUX_SHELL_INTEGRATION=", "-e", "CMUX_SHELL_INTEGRATION_DIR=", "-e", "CMUX_SOCKET_PATH=", + "-e", "CMUX_SSH_ATTEMPT_ID=", "-e", "CMUX_TAB_ID=", + "-e", "CMUX_TERMINAL_LIFECYCLE_ID=", "-e", "CMUX_WORKSPACE_ID=", "-e", "CMUX_INITIAL_COMMAND_FILE=", "-e", "CMUX_PANEL_ID=", @@ -37,7 +39,9 @@ struct RemoteTmuxSessionCommandBuilderTests { ["set-environment", "-t", "=agent main", "-u", "CMUX_SHELL_INTEGRATION"], ["set-environment", "-t", "=agent main", "-u", "CMUX_SHELL_INTEGRATION_DIR"], ["set-environment", "-t", "=agent main", "-u", "CMUX_SOCKET_PATH"], + ["set-environment", "-t", "=agent main", "-u", "CMUX_SSH_ATTEMPT_ID"], ["set-environment", "-t", "=agent main", "-u", "CMUX_TAB_ID"], + ["set-environment", "-t", "=agent main", "-u", "CMUX_TERMINAL_LIFECYCLE_ID"], ["set-environment", "-t", "=agent main", "-u", "CMUX_WORKSPACE_ID"], ["set-environment", "-t", "=agent main", "-u", "CMUX_INITIAL_COMMAND_FILE"], ["set-environment", "-t", "=agent main", "-u", "CMUX_PANEL_ID"], @@ -86,7 +90,9 @@ struct RemoteTmuxSessionCommandBuilderTests { "-e", "CMUX_SHELL_INTEGRATION=1", "-e", "CMUX_SHELL_INTEGRATION_DIR=/home/dev/.cmux/relay/55272.shell", "-e", "CMUX_SOCKET_PATH=\(currentSocket)", + "-e", "CMUX_SSH_ATTEMPT_ID=", "-e", "CMUX_TAB_ID=\(currentWorkspace)", + "-e", "CMUX_TERMINAL_LIFECYCLE_ID=", "-e", "CMUX_WORKSPACE_ID=\(currentWorkspace)", "-e", "CMUX_INITIAL_COMMAND_FILE=", "-e", "CMUX_PANEL_ID=", diff --git a/Resources/shell-integration/cmux-bash-integration.bash b/Resources/shell-integration/cmux-bash-integration.bash index 0485aaf821b6..8626bb5dce03 100644 --- a/Resources/shell-integration/cmux-bash-integration.bash +++ b/Resources/shell-integration/cmux-bash-integration.bash @@ -467,8 +467,10 @@ _CMUX_TMUX_SYNC_KEYS=( CMUX_SOCKET_ENABLE CMUX_SOCKET_MODE CMUX_SOCKET_PATH + CMUX_SSH_ATTEMPT_ID CMUX_TAB_ID CMUX_TAG + CMUX_TERMINAL_LIFECYCLE_ID CMUX_WORKSPACE_ID ) _CMUX_TMUX_SURFACE_SCOPED_KEYS=( diff --git a/Resources/shell-integration/cmux-zsh-integration.zsh b/Resources/shell-integration/cmux-zsh-integration.zsh index c3fbdb105263..574ee3660cf2 100644 --- a/Resources/shell-integration/cmux-zsh-integration.zsh +++ b/Resources/shell-integration/cmux-zsh-integration.zsh @@ -504,8 +504,10 @@ typeset -ga _CMUX_TMUX_SYNC_KEYS=( CMUX_SOCKET_ENABLE CMUX_SOCKET_MODE CMUX_SOCKET_PATH + CMUX_SSH_ATTEMPT_ID CMUX_TAB_ID CMUX_TAG + CMUX_TERMINAL_LIFECYCLE_ID CMUX_WORKSPACE_ID ) typeset -ga _CMUX_TMUX_SURFACE_SCOPED_KEYS=( diff --git a/Resources/shell-integration/fish/config.fish b/Resources/shell-integration/fish/config.fish index c4665d6edb9f..d44476321d24 100644 --- a/Resources/shell-integration/fish/config.fish +++ b/Resources/shell-integration/fish/config.fish @@ -41,8 +41,10 @@ if test "$_cmux_integration_enabled" != 0 CMUX_SOCKET_ENABLE \ CMUX_SOCKET_MODE \ CMUX_SOCKET_PATH \ + CMUX_SSH_ATTEMPT_ID \ CMUX_TAB_ID \ CMUX_TAG \ + CMUX_TERMINAL_LIFECYCLE_ID \ CMUX_WORKSPACE_ID set -g _CMUX_TMUX_SURFACE_SCOPED_KEYS CMUX_PANEL_ID CMUX_SURFACE_ID @@ -240,6 +242,17 @@ if test "$_cmux_integration_enabled" != 0 "$relay_cli" rpc "$method" "$params" >/dev/null 2>&1 & end + function _cmux_relay_rpc --argument-names method params + _cmux_socket_uses_remote_relay; or return 1 + set -l relay_cli (_cmux_relay_cli_path) + test -n "$relay_cli"; or return 1 + set -l response ("$relay_cli" rpc "$method" "$params" 2>/dev/null); or return 1 + set response (string join '' -- $response) + string match -q '*"ok":false*' -- "$response"; and return 1 + string match -q '*"ok": false*' -- "$response"; and return 1 + return 0 + end + function _cmux_report_tty_via_relay _cmux_socket_uses_remote_relay; or return 1 test -n "$_CMUX_TTY_NAME"; or return 1 @@ -252,7 +265,7 @@ if test "$_cmux_integration_enabled" != 0 set params "$params,\"surface_id\":\"$CMUX_PANEL_ID\"" end set params "$params}" - _cmux_relay_rpc_bg surface.report_tty "$params" + _cmux_relay_rpc surface.report_tty "$params" end function _cmux_report_pwd_via_relay --argument-names pwd @@ -418,8 +431,10 @@ if test "$_cmux_integration_enabled" != 0 set -g _CMUX_TTY_REPORTED 1 _cmux_send_bg "report_tty $_CMUX_TTY_NAME --tab=$CMUX_TAB_ID --panel=$CMUX_PANEL_ID" else if _cmux_socket_uses_remote_relay + # Treat the first relay report as a readiness barrier. Latch only + # after acknowledgement so later prompts retry transient failures. + _cmux_report_tty_via_relay; or return 0 set -g _CMUX_TTY_REPORTED 1 - _cmux_report_tty_via_relay end end diff --git a/Sources/RemoteInteractiveShellBootstrapBuilder.swift b/Sources/RemoteInteractiveShellBootstrapBuilder.swift index 468a999b6056..fd50b6af960a 100644 --- a/Sources/RemoteInteractiveShellBootstrapBuilder.swift +++ b/Sources/RemoteInteractiveShellBootstrapBuilder.swift @@ -376,16 +376,14 @@ enum RemoteInteractiveShellBootstrapBuilder { " printf '%s' \"$cmux_relay_tty\" > \"$HOME/.cmux/relay/\(remoteRelayPort).tty\" 2>/dev/null || true", "fi", "if [ -n \"$cmux_relay_cli\" ] && [ -n \"$CMUX_WORKSPACE_ID\" ] && [ -n \"$CMUX_TERMINAL_LIFECYCLE_ID\" ] && [ -n \"$CMUX_SSH_ATTEMPT_ID\" ] && [ -n \"$cmux_relay_tty\" ] && [ \"$cmux_relay_tty\" != \"not a tty\" ]; then", - " (", - " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", - " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", - " if [ -n \"$CMUX_SURFACE_ID\" ]; then", - " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", - " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", - " fi", - " \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", - " \"$cmux_relay_cli\" rpc surface.ports_kick \"$cmux_relay_ports_kick\" >/dev/null 2>&1 || true", - " ) /dev/null 2>&1 &", + " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", + " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", + " if [ -n \"$CMUX_SURFACE_ID\" ]; then", + " cmux_relay_report_tty=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"tty_name\\\":\\\"$cmux_relay_tty\\\",\\\"terminal_lifecycle_id\\\":\\\"$CMUX_TERMINAL_LIFECYCLE_ID\\\",\\\"attempt_id\\\":\\\"$CMUX_SSH_ATTEMPT_ID\\\"}\"", + " cmux_relay_ports_kick=\"{\\\"workspace_id\\\":\\\"$CMUX_WORKSPACE_ID\\\",\\\"surface_id\\\":\\\"$CMUX_SURFACE_ID\\\",\\\"reason\\\":\\\"command\\\"}\"", + " fi", + " \"$cmux_relay_cli\" rpc surface.report_tty \"$cmux_relay_report_tty\" >/dev/null 2>&1 || true", + " ( \"$cmux_relay_cli\" rpc surface.ports_kick \"$cmux_relay_ports_kick\" >/dev/null 2>&1 || true ) /dev/null 2>&1 &", "fi", "unset CMUX_BOOTSTRAP_TTY cmux_relay_cli cmux_relay_tty cmux_relay_report_tty cmux_relay_ports_kick", ]