Skip to content

Commit 000db97

Browse files
feat(talk): add macOS realtime Gateway relay (#128204)
* feat(talk): add macOS realtime relay transport Co-authored-by: Zhilong Zheng <[email protected]> * feat(talk): integrate realtime relay with macOS Talk Co-authored-by: Zhilong Zheng <[email protected]> * fix(talk): keep realtime bootstrap config redacted Co-authored-by: Zhilong Zheng <[email protected]> * fix(talk): surface failed native fallback Co-authored-by: Zhilong Zheng <[email protected]> * test(talk): inject deterministic relay capture Co-authored-by: Zhilong Zheng <[email protected]> --------- Co-authored-by: Zhilong Zheng <[email protected]>
1 parent 5283334 commit 000db97

18 files changed

Lines changed: 4636 additions & 327 deletions

‎apps/.i18n/native-source.json‎

Lines changed: 110 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/macos/Sources/OpenClaw/AppState+Preview.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ extension AppState {
2020
state.voiceWakeAdditionalLocaleIDs = ["en-US", "de-DE"]
2121
state.voicePushToTalkEnabled = false
2222
state.talkEnabled = false
23+
state.talkRealtimeRelayEnabled = false
2324
state.talkPhaseSoundsEnabled = true
2425
state.talkShiftToStopEnabled = true
2526
state.iconOverride = .system
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import Foundation
2+
3+
extension AppState {
4+
func persistTalkRealtimeRelayPreference(previousValue: Bool) {
5+
guard !self.isPreview else { return }
6+
AppDefaults.standard.set(self.talkRealtimeRelayEnabled, forKey: talkRealtimeRelayEnabledKey)
7+
guard self.talkEnabled, self.talkRealtimeRelayEnabled != previousValue else { return }
8+
Task { await TalkModeRuntime.shared.realtimeRelayPreferenceDidChange() }
9+
}
10+
}

‎apps/macos/Sources/OpenClaw/AppState.swift‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ final class AppState {
8181
private static let logger = Logger(subsystem: "ai.openclaw", category: "app-state")
8282
private static let execApprovalsReadRetryAttempts = 5
8383

84-
private let isPreview: Bool
84+
let isPreview: Bool
8585
@ObservationIgnored private let execApprovalsDefaultsAsyncResolver:
8686
@MainActor () async -> Result<ExecApprovalsResolvedDefaults, ExecApprovalsReadError>
8787
@ObservationIgnored private let execApprovalsReadRetryDelay: Duration
@@ -260,6 +260,10 @@ final class AppState {
260260
}
261261
}
262262

263+
var talkRealtimeRelayEnabled = isTalkRealtimeRelayEnabled() {
264+
didSet { self.persistTalkRealtimeRelayPreference(previousValue: oldValue) }
265+
}
266+
263267
var talkPhaseSoundsEnabled: Bool {
264268
didSet {
265269
self.ifNotPreview {

‎apps/macos/Sources/OpenClaw/Constants.swift‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ let voiceWakeAdditionalLocalesKey = "openclaw.voiceWakeAdditionalLocaleIDs"
3131
let voicePushToTalkEnabledKey = "openclaw.voicePushToTalkEnabled"
3232
let voiceWakeTriggersTalkModeKey = "openclaw.voiceWakeTriggersTalkMode"
3333
let talkEnabledKey = "openclaw.talkEnabled"
34+
let talkRealtimeRelayEnabledKey = "openclaw.talkRealtimeRelayEnabled"
3435
let talkPhaseSoundsEnabledKey = "openclaw.talkPhaseSoundsEnabled"
3536
let talkShiftToStopEnabledKey = "openclaw.talkShiftToStopEnabled"
3637
let iconOverrideKey = "openclaw.iconOverride"
@@ -48,6 +49,10 @@ let cookieSyncEnabledKey = "openclaw.cookieSyncEnabled"
4849
let cookieSyncIntoProfileKey = "openclaw.cookieSyncIntoProfile"
4950
let cookieSyncDomainsKey = "openclaw.cookieSyncDomains"
5051

52+
func isTalkRealtimeRelayEnabled(defaults: UserDefaults = AppDefaults.standard) -> Bool {
53+
defaults.object(forKey: talkRealtimeRelayEnabledKey) as? Bool ?? false
54+
}
55+
5156
func isComputerControlEnabled(
5257
defaults: UserDefaults = AppDefaults.standard,
5358
launchPlan: AppLaunchRuntimePlan = .current) -> Bool
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import Foundation
2+
import OpenClawChatUI
3+
import OpenClawKit
4+
import OpenClawProtocol
5+
6+
extension GatewayConnection {
7+
struct RealtimeTalkBootstrap: @unchecked Sendable {
8+
let transport: RealtimeTalkRelayTransport
9+
let configSnapshot: ConfigSnapshot
10+
let sessionKey: String
11+
}
12+
13+
/// Freezes config and relay traffic to one physical Gateway socket.
14+
///
15+
/// A route replacement between config resolution and session creation must
16+
/// fail this attempt instead of silently moving the relay to a new owner.
17+
func acquireRealtimeTalkBootstrap() async throws -> RealtimeTalkBootstrap {
18+
let lease = try await self.acquireServerLease()
19+
let data = try await self.request(
20+
method: Method.talkConfig.rawValue,
21+
params: [:],
22+
timeoutMs: 8000,
23+
ifCurrentServerLease: lease)
24+
let snapshot = try JSONDecoder().decode(ConfigSnapshot.self, from: data)
25+
guard await self.isCurrentServerLease(lease) else {
26+
throw OpenClawChatTransportSendError.notDispatched
27+
}
28+
let configuredSessionKey = snapshot.config?["session"]?.dictionaryValue?["mainKey"]?
29+
.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines)
30+
return RealtimeTalkBootstrap(
31+
transport: self.realtimeTalkTransport(ifCurrentServerLease: lease),
32+
configSnapshot: snapshot,
33+
sessionKey: configuredSessionKey?.isEmpty == false ? configuredSessionKey! : "main")
34+
}
35+
36+
/// Creates a realtime Talk transport bound to one physical Gateway socket.
37+
///
38+
/// Gateway relay sessions are owned by the connection that created them. A
39+
/// route-only transport could silently move follow-up audio or close calls to
40+
/// a replacement socket after reconnecting, where that session does not exist.
41+
func acquireRealtimeTalkTransport() async throws -> RealtimeTalkRelayTransport {
42+
let lease = try await self.acquireServerLease()
43+
return self.realtimeTalkTransport(ifCurrentServerLease: lease)
44+
}
45+
46+
private func realtimeTalkTransport(
47+
ifCurrentServerLease lease: ServerLease) -> RealtimeTalkRelayTransport
48+
{
49+
RealtimeTalkRelayTransport(
50+
subscribeServerEvents: { bufferingNewest in
51+
let pushes = await self.subscribe(
52+
bufferingNewest: bufferingNewest,
53+
ifCurrentServerLease: lease)
54+
return AsyncStream(bufferingPolicy: .bufferingNewest(bufferingNewest)) { continuation in
55+
let task = Task {
56+
for await push in pushes {
57+
guard case let .event(event) = push else { continue }
58+
switch continuation.yield(event) {
59+
case .enqueued:
60+
continue
61+
case .dropped, .terminated:
62+
continuation.finish()
63+
return
64+
@unknown default:
65+
continuation.finish()
66+
return
67+
}
68+
}
69+
continuation.finish()
70+
}
71+
continuation.onTermination = { @Sendable _ in
72+
task.cancel()
73+
}
74+
}
75+
},
76+
request: { method, params, timeoutMs in
77+
try await self.request(
78+
method: method,
79+
params: params,
80+
timeoutMs: timeoutMs,
81+
ifCurrentServerLease: lease)
82+
},
83+
isCurrent: {
84+
await self.isCurrentServerLease(lease)
85+
})
86+
}
87+
88+
func subscribe(
89+
bufferingNewest: Int,
90+
ifCurrentServerLease lease: ServerLease) -> AsyncStream<GatewayPush>
91+
{
92+
let id = UUID()
93+
let connection = self
94+
return AsyncStream(bufferingPolicy: .bufferingNewest(bufferingNewest)) { continuation in
95+
guard self.serverLeaseMatchesCurrentState(lease) else {
96+
continuation.finish()
97+
return
98+
}
99+
if let snapshot = self.lastSnapshot {
100+
switch continuation.yield(.snapshot(snapshot)) {
101+
case .enqueued:
102+
break
103+
case .dropped, .terminated:
104+
continuation.finish()
105+
return
106+
@unknown default:
107+
continuation.finish()
108+
return
109+
}
110+
}
111+
self.realtimeTalkSubscribers[lease.socketGeneration, default: [:]][id] = continuation
112+
continuation.onTermination = { @Sendable _ in
113+
Task {
114+
await connection.removeRealtimeTalkSubscriber(
115+
id,
116+
socketGeneration: lease.socketGeneration)
117+
}
118+
}
119+
}
120+
}
121+
122+
func removeRealtimeTalkSubscriber(_ id: UUID, socketGeneration: UInt64) {
123+
self.realtimeTalkSubscribers[socketGeneration]?[id] = nil
124+
if self.realtimeTalkSubscribers[socketGeneration]?.isEmpty == true {
125+
self.realtimeTalkSubscribers[socketGeneration] = nil
126+
}
127+
}
128+
129+
func finishRealtimeTalkSubscribers(socketGeneration: UInt64? = nil) {
130+
let subscribers: [AsyncStream<GatewayPush>.Continuation]
131+
if let socketGeneration {
132+
if let removed = self.realtimeTalkSubscribers.removeValue(forKey: socketGeneration) {
133+
subscribers = Array(removed.values)
134+
} else {
135+
subscribers = []
136+
}
137+
} else {
138+
subscribers = self.realtimeTalkSubscribers.values.flatMap(\.values)
139+
self.realtimeTalkSubscribers.removeAll()
140+
}
141+
subscribers.forEach { $0.finish() }
142+
}
143+
144+
#if DEBUG
145+
func _test_activeSocketGeneration() -> UInt64? {
146+
self.activeSocketGeneration
147+
}
148+
#endif
149+
}

0 commit comments

Comments
 (0)