Repository navigation
Route blocking v2 socket methods off main #3340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 3 commits
2597d88
f58aacd
af2de20
05e8fd6
eae86ef
16aa5f9
ff5280c
7c282c4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1383,88 +1383,121 @@ class TerminalController { | |
| return nil | ||
| } | ||
|
|
||
| private nonisolated func socketWorkerAuthResponseIfNeeded(for command: String) -> String? { | ||
| guard command.hasPrefix("{"), | ||
| let data = command.data(using: .utf8), | ||
| private enum SocketCommandExecutionPolicy: Equatable { | ||
| case mainActor | ||
| case socketWorker | ||
| } | ||
|
|
||
| private struct V2SocketRequest { | ||
| let id: Any? | ||
| let method: String | ||
| let params: [String: Any] | ||
| } | ||
|
|
||
| private nonisolated static let socketWorkerV2Methods: Set<String> = [ | ||
| "auth.status", | ||
| "auth.begin_sign_in", | ||
| "auth.sign_out", | ||
| "feedback.submit", | ||
| "feed.push", | ||
| "feed.permission.reply", | ||
| "feed.question.reply", | ||
| "feed.exit_plan.reply", | ||
| ] | ||
|
|
||
| private nonisolated static func executionPolicy(forV2Method method: String) -> SocketCommandExecutionPolicy { | ||
| if method.hasPrefix("vm.") || socketWorkerV2Methods.contains(method) { | ||
| return .socketWorker | ||
| } | ||
| return .mainActor | ||
| } | ||
|
|
||
| private nonisolated func parseV2SocketRequest(_ command: String) -> V2SocketRequest? { | ||
| let trimmedCommand = command.trimmingCharacters(in: .whitespacesAndNewlines) | ||
| guard trimmedCommand.hasPrefix("{"), | ||
| let data = trimmedCommand.data(using: .utf8), | ||
| let dict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else { | ||
| return nil | ||
| } | ||
|
|
||
| let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" | ||
| guard method == "auth.status" || method == "auth.begin_sign_in" || method == "auth.sign_out" else { | ||
| guard !method.isEmpty else { | ||
| return nil | ||
| } | ||
|
|
||
| let id: Any? = dict["id"] | ||
| let params = dict["params"] as? [String: Any] ?? [:] | ||
|
|
||
| return withSocketCommandPolicy(commandKey: method, isV2: true) { | ||
| switch method { | ||
| case "auth.status": | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| Task { @MainActor in | ||
| await AuthManager.shared.awaitBootstrapped() | ||
| semaphore.signal() | ||
| } | ||
| semaphore.wait() | ||
| return v2Ok(id: id, result: v2AuthStatusPayload(timedOut: false)) | ||
| case "auth.begin_sign_in": | ||
| let timeoutSeconds = (params["timeout_seconds"] as? Double) ?? 300 | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| nonisolated(unsafe) var signedIn = false | ||
| Task { @MainActor in | ||
| signedIn = await AuthManager.shared.beginSignInAndAwait( | ||
| timeout: timeoutSeconds | ||
| ) | ||
| semaphore.signal() | ||
| } | ||
| semaphore.wait() | ||
| return v2Ok(id: id, result: v2AuthStatusPayload(timedOut: !signedIn)) | ||
| case "auth.sign_out": | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| Task { @MainActor in | ||
| _ = await AuthManager.shared.signOutAndAwait(timeout: 5) | ||
| semaphore.signal() | ||
| } | ||
| semaphore.wait() | ||
| return v2Ok(id: id, result: v2AuthStatusPayload(timedOut: false)) | ||
| default: | ||
| return nil | ||
| } | ||
| } | ||
| return V2SocketRequest( | ||
| id: dict["id"], | ||
| method: method, | ||
| params: dict["params"] as? [String: Any] ?? [:] | ||
| ) | ||
| } | ||
|
|
||
| private nonisolated func socketWorkerFeedbackResponseIfNeeded(for command: String) -> String? { | ||
| guard command.hasPrefix("{"), | ||
| let data = command.data(using: .utf8), | ||
| let dict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else { | ||
| private nonisolated func socketWorkerV2ResponseIfNeeded(for command: String) -> String? { | ||
| guard let request = parseV2SocketRequest(command), | ||
| Self.executionPolicy(forV2Method: request.method) == .socketWorker else { | ||
| return nil | ||
| } | ||
|
|
||
| let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" | ||
| guard method == "feedback.submit" else { return nil } | ||
| return withSocketCommandPolicy(commandKey: request.method, isV2: true) { | ||
| socketWorkerV2Response(request) | ||
| } | ||
| } | ||
|
|
||
| let id: Any? = dict["id"] | ||
| let params = dict["params"] as? [String: Any] ?? [:] | ||
| return withSocketCommandPolicy(commandKey: method, isV2: true) { | ||
| v2Result(id: id, v2FeedbackSubmit(params: params)) | ||
| private nonisolated func socketWorkerV2Response(_ request: V2SocketRequest) -> String { | ||
| switch request.method { | ||
| case "auth.status": | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| Task { @MainActor in | ||
| await AuthManager.shared.awaitBootstrapped() | ||
| semaphore.signal() | ||
| } | ||
| semaphore.wait() | ||
| return v2Ok(id: request.id, result: v2AuthStatusPayload(timedOut: false)) | ||
| case "auth.begin_sign_in": | ||
| let timeoutSeconds = (request.params["timeout_seconds"] as? Double) ?? 300 | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| nonisolated(unsafe) var signedIn = false | ||
| Task { @MainActor in | ||
| signedIn = await AuthManager.shared.beginSignInAndAwait( | ||
| timeout: timeoutSeconds | ||
| ) | ||
|
Comment on lines
+1464
to
+1470
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject non-positive A missing timeout falls back to Suggested fix- let timeoutSeconds = (request.params["timeout_seconds"] as? Double) ?? 300
+ let timeoutSeconds: TimeInterval
+ if let rawTimeout = request.params["timeout_seconds"] {
+ guard let seconds = rawTimeout as? NSNumber, seconds.doubleValue > 0 else {
+ return v2Error(
+ id: request.id,
+ code: "invalid_params",
+ message: "auth.begin_sign_in requires `timeout_seconds` > 0"
+ )
+ }
+ timeoutSeconds = seconds.doubleValue
+ } else {
+ timeoutSeconds = 300
+ }Based on learnings: In Swift request/JSON handlers in 🤖 Prompt for AI Agents |
||
| semaphore.signal() | ||
| } | ||
| semaphore.wait() | ||
| return v2Ok(id: request.id, result: v2AuthStatusPayload(timedOut: !signedIn)) | ||
| case "auth.sign_out": | ||
| let semaphore = DispatchSemaphore(value: 0) | ||
| Task { @MainActor in | ||
| _ = await AuthManager.shared.signOutAndAwait(timeout: 5) | ||
| semaphore.signal() | ||
| } | ||
| semaphore.wait() | ||
| return v2Ok(id: request.id, result: v2AuthStatusPayload(timedOut: false)) | ||
| case "feedback.submit": | ||
| return v2Result(id: request.id, v2FeedbackSubmit(params: request.params)) | ||
| case "feed.push": | ||
| return v2Result(id: request.id, v2FeedPush(params: request.params)) | ||
| case "feed.permission.reply": | ||
| return v2Result(id: request.id, v2FeedPermissionReply(params: request.params)) | ||
| case "feed.question.reply": | ||
| return v2Result(id: request.id, v2FeedQuestionReply(params: request.params)) | ||
| case "feed.exit_plan.reply": | ||
| return v2Result(id: request.id, v2FeedExitPlanReply(params: request.params)) | ||
| case let method where method.hasPrefix("vm."): | ||
| return socketWorkerCloudVMResponse(method: method, id: request.id, params: request.params) | ||
| default: | ||
| return v2Error(id: request.id, code: "method_not_found", message: "Unknown method") | ||
| } | ||
| } | ||
|
|
||
| private nonisolated func socketWorkerSystemTopResponseIfNeeded(for command: String) -> String? { | ||
| guard command.hasPrefix("{"), | ||
| let data = command.data(using: .utf8), | ||
| let dict = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else { | ||
| guard let request = parseV2SocketRequest(command), | ||
| request.method == "system.top" else { | ||
| return nil | ||
| } | ||
|
|
||
| let method = (dict["method"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" | ||
| guard method == "system.top" else { return nil } | ||
|
|
||
| let id: Any? = dict["id"] | ||
| let params = dict["params"] as? [String: Any] ?? [:] | ||
| return withSocketCommandPolicy(commandKey: method, isV2: true) { | ||
| v2Result(id: id, v2SystemTop(params: params)) | ||
| return withSocketCommandPolicy(commandKey: request.method, isV2: true) { | ||
| v2Result(id: request.id, v2SystemTop(params: request.params)) | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -1812,31 +1845,40 @@ class TerminalController { | |
| if let response = authResponseIfNeeded(for: command, authenticated: &nextAuthenticated) { | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
| } | ||
| if let response = socketWorkerAuthResponseIfNeeded(for: command) { | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
| } | ||
| if let response = socketWorkerFeedbackResponseIfNeeded(for: command) { | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
|
|
||
| let response = processCommandUsingSocketExecutionPolicy(command) | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
| } | ||
|
|
||
| private nonisolated func processCommandUsingSocketExecutionPolicy(_ command: String) -> String { | ||
| if Thread.isMainThread, | ||
| let request = parseV2SocketRequest(command), | ||
| Self.executionPolicy(forV2Method: request.method) == .socketWorker { | ||
| return v2Error( | ||
| id: request.id, | ||
| code: "invalid_dispatch", | ||
| message: "\(request.method) must run off the main thread" | ||
| ) | ||
| } | ||
| if let response = socketWorkerCloudVMResponseIfNeeded(for: command) { | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
|
|
||
| if let response = socketWorkerV2ResponseIfNeeded(for: command) { | ||
| return response | ||
| } | ||
| if let response = socketWorkerSystemTopResponseIfNeeded(for: command) { | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
| return response | ||
| } | ||
|
|
||
| let response = v2MainSync { | ||
| return v2MainSync { | ||
| self.processCommand(command) | ||
| } | ||
| return SocketLineProcessingResult(response: response, authenticated: nextAuthenticated) | ||
| } | ||
|
|
||
| /// Public entry point mirroring the socket's `processCommand` path so | ||
| /// in-process callers (e.g. the Feed coordinator's `feed.jump` focus | ||
| /// request) can reuse the full V1/V2 dispatcher without duplicating | ||
| /// its auth/policy wrappers. | ||
| func handleSocketLine(_ line: String) -> String { | ||
| return processCommand(line) | ||
| nonisolated func handleSocketLine(_ line: String) -> String { | ||
| return processCommandUsingSocketExecutionPolicy(line) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| private func processCommand(_ command: String) -> String { | ||
|
|
@@ -2228,6 +2270,14 @@ class TerminalController { | |
| return v2Error(id: id, code: "invalid_request", message: "Missing method") | ||
| } | ||
|
|
||
| guard Self.executionPolicy(forV2Method: method) == .mainActor else { | ||
| return v2Error( | ||
| id: id, | ||
| code: "invalid_dispatch", | ||
| message: "\(method) must run on the socket worker" | ||
| ) | ||
| } | ||
|
|
||
| v2MainSync { self.v2RefreshKnownRefs() } | ||
|
|
||
|
|
||
|
|
@@ -7987,7 +8037,7 @@ class TerminalController { | |
|
|
||
| // MARK: - V2 Feed (workstream) handlers | ||
|
|
||
| private func v2FeedPush(params: [String: Any]) -> V2CallResult { | ||
| private nonisolated func v2FeedPush(params: [String: Any]) -> V2CallResult { | ||
| let waitTimeout: TimeInterval | ||
| if let rawTimeout = params["wait_timeout_seconds"] { | ||
| let seconds: Double? | ||
|
|
@@ -8052,7 +8102,7 @@ class TerminalController { | |
| return .ok(FeedSocketEncoding.payload(for: result)) | ||
| } | ||
|
|
||
| private func v2FeedPermissionReply(params: [String: Any]) -> V2CallResult { | ||
| private nonisolated func v2FeedPermissionReply(params: [String: Any]) -> V2CallResult { | ||
| guard let requestId = params["request_id"] as? String else { | ||
| return .err( | ||
| code: "invalid_params", | ||
|
|
@@ -8076,7 +8126,7 @@ class TerminalController { | |
| return .ok(["delivered": true]) | ||
| } | ||
|
|
||
| private func v2FeedQuestionReply(params: [String: Any]) -> V2CallResult { | ||
| private nonisolated func v2FeedQuestionReply(params: [String: Any]) -> V2CallResult { | ||
| guard let requestId = params["request_id"] as? String else { | ||
| return .err( | ||
| code: "invalid_params", | ||
|
|
@@ -8098,7 +8148,7 @@ class TerminalController { | |
| return .ok(["delivered": true]) | ||
| } | ||
|
|
||
| private func v2FeedExitPlanReply(params: [String: Any]) -> V2CallResult { | ||
| private nonisolated func v2FeedExitPlanReply(params: [String: Any]) -> V2CallResult { | ||
| guard let requestId = params["request_id"] as? String else { | ||
| return .err( | ||
| code: "invalid_params", | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.