Skip to content

Commit d85e8a5

Browse files
authored
fix(android): restore sticky node service (#104226)
Co-authored-by: NianJiuZst <[email protected]>
1 parent 26dc42a commit d85e8a5

5 files changed

Lines changed: 278 additions & 21 deletions

File tree

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

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -179,95 +179,95 @@
179179
},
180180
{
181181
"kind": "conditional-branch",
182-
"line": 116,
182+
"line": 163,
183183
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeForegroundService.kt",
184184
"source": "Connected",
185185
"surface": "android",
186186
"id": "native.android.012c8499137972ad"
187187
},
188188
{
189189
"kind": "conditional-branch",
190-
"line": 116,
190+
"line": 163,
191191
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeForegroundService.kt",
192192
"source": "Talk mode active",
193193
"surface": "android",
194194
"id": "native.android.3e0889d921c92cab"
195195
},
196196
{
197197
"kind": "conditional-branch",
198-
"line": 278,
198+
"line": 358,
199199
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeForegroundService.kt",
200200
"source": " · Mic: Listening",
201201
"surface": "android",
202202
"id": "native.android.ae88801e6a1b3343"
203203
},
204204
{
205205
"kind": "conditional-branch",
206-
"line": 278,
206+
"line": 358,
207207
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeForegroundService.kt",
208208
"source": " · Mic: Pending",
209209
"surface": "android",
210210
"id": "native.android.7521acb4a7bc9a75"
211211
},
212212
{
213213
"kind": "ui-state-text",
214-
"line": 649,
214+
"line": 666,
215215
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
216216
"source": "Offline",
217217
"surface": "android",
218218
"id": "native.android.c65b61de70a063e7"
219219
},
220220
{
221221
"kind": "conditional-branch",
222-
"line": 1512,
222+
"line": 1529,
223223
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
224224
"source": "Cron job started.",
225225
"surface": "android",
226226
"id": "native.android.fef5049bc20826c7"
227227
},
228228
{
229229
"kind": "conditional-branch",
230-
"line": 1512,
230+
"line": 1529,
231231
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
232232
"source": "Cron run queued.",
233233
"surface": "android",
234234
"id": "native.android.c39fb6f80dbf6820"
235235
},
236236
{
237237
"kind": "conditional-branch",
238-
"line": 1556,
238+
"line": 1573,
239239
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
240240
"source": "Cron job disabled.",
241241
"surface": "android",
242242
"id": "native.android.b878b2913410055a"
243243
},
244244
{
245245
"kind": "conditional-branch",
246-
"line": 1556,
246+
"line": 1573,
247247
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
248248
"source": "Cron job enabled.",
249249
"surface": "android",
250250
"id": "native.android.a45ec59239fbfff0"
251251
},
252252
{
253253
"kind": "conditional-branch",
254-
"line": 3149,
254+
"line": 3169,
255255
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
256256
"source": "Failed: no secure gateway endpoint was detected. Enable gateway TLS or Tailscale Serve, or use a trusted private LAN address with Unencrypted selected.",
257257
"surface": "android",
258258
"id": "native.android.4b07456682e725d9"
259259
},
260260
{
261261
"kind": "conditional-branch",
262-
"line": 3151,
262+
"line": 3171,
263263
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
264264
"source": "Failed: secure endpoint reached, but TLS fingerprint verification timed out. Check Tailscale Serve or gateway TLS and retry.",
265265
"surface": "android",
266266
"id": "native.android.467899bb510b8e34"
267267
},
268268
{
269269
"kind": "conditional-branch",
270-
"line": 3153,
270+
"line": 3173,
271271
"path": "apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt",
272272
"source": "Failed: couldn't reach the secure gateway endpoint for this host.",
273273
"surface": "android",

‎apps/android/app/src/main/java/ai/openclaw/app/NodeApp.kt‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import ai.openclaw.app.gateway.DeviceIdentityStore
77
import android.app.Application
88
import android.os.StrictMode
99
import androidx.room.withTransaction
10+
import kotlinx.coroutines.CoroutineScope
11+
import kotlinx.coroutines.Dispatchers
12+
import kotlinx.coroutines.SupervisorJob
13+
import kotlinx.coroutines.launch
1014
import kotlinx.coroutines.runBlocking
1115

1216
/**
@@ -15,6 +19,7 @@ import kotlinx.coroutines.runBlocking
1519
class NodeApp : Application() {
1620
val prefs: SecurePrefs by lazy { SecurePrefs(this) }
1721

22+
private val runtimeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
1823
private val runtimeLock = Any()
1924
private var runtimeInstance: NodeRuntime? = null
2025

@@ -26,6 +31,13 @@ class NodeApp : Application() {
2631
runtimeInstance ?: NodeRuntime(this, prefs).also { runtimeInstance = it }
2732
}
2833

34+
/** Creates a cold-process runtime with foreground-only capabilities disabled before publication. */
35+
internal fun ensureBackgroundRuntime(): NodeRuntime =
36+
synchronized(runtimeLock) {
37+
runtimeInstance
38+
?: NodeRuntime(this, prefs, initialForeground = false).also { runtimeInstance = it }
39+
}
40+
2941
internal fun ensureScreenshotFixtureRuntime(): NodeRuntime =
3042
synchronized(runtimeLock) {
3143
check(BuildConfig.DEBUG) { "Android screenshot fixtures require a debug build" }
@@ -41,6 +53,13 @@ class NodeApp : Application() {
4153
*/
4254
fun peekRuntime(): NodeRuntime? = synchronized(runtimeLock) { runtimeInstance }
4355

56+
/** Disconnects the current or concurrently constructing runtime without blocking the caller. */
57+
internal fun disconnectRuntimeAsync() {
58+
// The process-owned scope outlives a stopping service, so cancellation cannot
59+
// strand an Activity-created runtime that the service has not observed yet.
60+
runtimeScope.launch { peekRuntime()?.disconnect() }
61+
}
62+
4463
/** Clears pairing auth without racing lazy process-runtime construction. */
4564
suspend fun resetGatewaySetupAuth(stableId: String): Boolean {
4665
val runtime =

‎apps/android/app/src/main/java/ai/openclaw/app/NodeForegroundService.kt‎

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,34 +10,75 @@ import android.content.Context
1010
import android.content.Intent
1111
import android.content.pm.PackageManager
1212
import android.content.pm.ServiceInfo
13+
import android.util.Log
1314
import androidx.core.app.NotificationCompat
1415
import androidx.core.app.ServiceCompat
1516
import androidx.core.content.ContextCompat
17+
import kotlinx.coroutines.CancellationException
1618
import kotlinx.coroutines.CoroutineScope
1719
import kotlinx.coroutines.Dispatchers
1820
import kotlinx.coroutines.Job
1921
import kotlinx.coroutines.SupervisorJob
2022
import kotlinx.coroutines.cancel
2123
import kotlinx.coroutines.flow.combine
2224
import kotlinx.coroutines.launch
25+
import kotlinx.coroutines.withContext
2326

2427
/** Foreground service that keeps the Android node connection and voice capture visible to the OS. */
2528
class NodeForegroundService : Service() {
2629
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
2730
private var notificationJob: Job? = null
31+
private var runtimeRestoreJob: Job? = null
32+
private var activeRuntime: NodeRuntime? = null
33+
private var latestStartId = 0
2834
private var voiceCaptureMode = VoiceCaptureMode.Off
2935

36+
@Volatile private var disconnectRequested = false
37+
3038
override fun onCreate() {
3139
super.onCreate()
3240
ensureChannel()
3341
val initial = buildNotification(title = "OpenClaw Node", text = "Starting…")
3442
startForegroundWithTypes(notification = initial)
43+
}
3544

36-
val runtime = (application as NodeApp).peekRuntime()
37-
if (runtime == null) {
38-
stopSelf()
39-
return
40-
}
45+
private fun startRuntimeIfNeeded(startId: Int) {
46+
if (activeRuntime != null || runtimeRestoreJob?.isActive == true || disconnectRequested) return
47+
val app = application as NodeApp
48+
runtimeRestoreJob =
49+
scope.launch(Dispatchers.Default) {
50+
try {
51+
restoreStickyRuntime(
52+
createRuntime = app::ensureBackgroundRuntime,
53+
disconnectRequested = { disconnectRequested },
54+
disconnectRuntime = NodeRuntime::disconnect,
55+
) { restoredRuntime ->
56+
withContext(Dispatchers.Main) {
57+
runtimeRestoreJob = null
58+
if (disconnectRequested) {
59+
false
60+
} else {
61+
activeRuntime = restoredRuntime
62+
observeRuntime(restoredRuntime)
63+
true
64+
}
65+
}
66+
}
67+
} catch (err: CancellationException) {
68+
throw err
69+
} catch (err: Throwable) {
70+
Log.e("OpenClawNodeService", "Failed to restore node runtime", err)
71+
withContext(Dispatchers.Main) {
72+
runtimeRestoreJob = null
73+
if (!disconnectRequested && !stopSelfResult(startId)) {
74+
startRuntimeIfNeeded(latestStartId)
75+
}
76+
}
77+
}
78+
}
79+
}
80+
81+
private fun observeRuntime(runtime: NodeRuntime) {
4182
// Keep the connection tuple atomic, then split connection and capture work so notification text
4283
// can update without restarting runtime-owned connection work.
4384
notificationJob =
@@ -101,10 +142,16 @@ class NodeForegroundService : Service() {
101142
flags: Int,
102143
startId: Int,
103144
): Int {
145+
latestStartId = maxOf(latestStartId, startId)
104146
when (intent?.action) {
105147
ACTION_STOP -> {
106-
(application as NodeApp).peekRuntime()?.disconnect()
107-
stopSelf()
148+
disconnectRequested = true
149+
runtimeRestoreJob?.cancel()
150+
runtimeRestoreJob = null
151+
activeRuntime?.disconnect()
152+
activeRuntime = null
153+
(application as NodeApp).disconnectRuntimeAsync()
154+
stopSelfResult(startId)
108155
return START_NOT_STICKY
109156
}
110157
ACTION_SET_VOICE_CAPTURE_MODE -> {
@@ -118,6 +165,14 @@ class NodeForegroundService : Service() {
118165
)
119166
}
120167
}
168+
if (disconnectRequested) {
169+
// A STOP can lose stopSelfResult to a newer queued start. Let the newest
170+
// start id close the service instead of leaving a disconnected FGS alive.
171+
stopSelfResult(startId)
172+
return START_NOT_STICKY
173+
}
174+
// START_STICKY recreates the service in a fresh process and calls this with a null intent.
175+
startRuntimeIfNeeded(startId)
121176
// Keep running; connection is managed by NodeRuntime (auto-reconnect + manual).
122177
return START_STICKY
123178
}
@@ -233,6 +288,31 @@ class NodeForegroundService : Service() {
233288
}
234289
}
235290

291+
/** Restores process-local state after Android recreates a sticky service in a fresh process. */
292+
internal suspend fun <T> restoreStickyRuntime(
293+
createRuntime: () -> T,
294+
disconnectRequested: () -> Boolean,
295+
disconnectRuntime: (T) -> Unit,
296+
activateRuntime: suspend (T) -> Boolean,
297+
) {
298+
// A queued recovery may begin after STOP; do not construct process state once
299+
// disconnect has already won. The post-create check still closes the race during construction.
300+
if (disconnectRequested()) return
301+
val runtime = createRuntime()
302+
var activated = false
303+
try {
304+
if (!disconnectRequested()) {
305+
activated = activateRuntime(runtime)
306+
}
307+
} finally {
308+
// Ownership transfers only after activation. Stop/cancellation during the
309+
// dispatcher hop must disconnect the recovered runtime instead of leaking it.
310+
if (!activated) {
311+
disconnectRuntime(runtime)
312+
}
313+
}
314+
}
315+
236316
internal fun foregroundServiceTypes(
237317
voiceMode: VoiceCaptureMode,
238318
backgroundLocationActive: Boolean,

‎apps/android/app/src/main/java/ai/openclaw/app/NodeRuntime.kt‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,7 @@ class NodeRuntime private constructor(
357357
private val tlsFingerprintProbe: suspend (String, Int) -> GatewayTlsProbeResult,
358358
chatStores: AndroidChatStores,
359359
internal val mode: NodeRuntimeMode,
360+
initialForeground: Boolean,
360361
) {
361362
private val chatTranscriptCache = chatStores.transcriptCache
362363
private val chatCommandOutbox = chatStores.commandOutbox
@@ -394,6 +395,20 @@ class NodeRuntime private constructor(
394395
tlsFingerprintProbe = tlsFingerprintProbe,
395396
chatStores = openAndroidChatStores(context),
396397
mode = NodeRuntimeMode.Live,
398+
initialForeground = true,
399+
)
400+
401+
internal constructor(
402+
context: Context,
403+
prefs: SecurePrefs,
404+
initialForeground: Boolean,
405+
) : this(
406+
context = context,
407+
prefs = prefs,
408+
tlsFingerprintProbe = ::probeGatewayTlsFingerprint,
409+
chatStores = openAndroidChatStores(context),
410+
mode = NodeRuntimeMode.Live,
411+
initialForeground = initialForeground,
397412
)
398413

399414
internal constructor(
@@ -406,6 +421,7 @@ class NodeRuntime private constructor(
406421
tlsFingerprintProbe = ::probeGatewayTlsFingerprint,
407422
chatStores = openAndroidChatStores(context),
408423
mode = mode,
424+
initialForeground = true,
409425
)
410426

411427
internal constructor(
@@ -422,6 +438,7 @@ class NodeRuntime private constructor(
422438
commandOutbox = RoomChatCommandOutbox(ChatCacheDatabase.open(context.applicationContext)),
423439
),
424440
mode = NodeRuntimeMode.Live,
441+
initialForeground = true,
425442
)
426443

427444
/**
@@ -805,7 +822,7 @@ class NodeRuntime private constructor(
805822
private val _healthLogsErrorText = MutableStateFlow<String?>(null)
806823
val healthLogsErrorText: StateFlow<String?> = _healthLogsErrorText.asStateFlow()
807824

808-
private val _isForeground = MutableStateFlow(true)
825+
private val _isForeground = MutableStateFlow(initialForeground)
809826
val isForeground: StateFlow<Boolean> = _isForeground.asStateFlow()
810827

811828
private data class TalkPttOwnership(
@@ -1978,8 +1995,11 @@ class NodeRuntime private constructor(
19781995
prefs.setVoiceWakeMode(VoiceWakeMode.Off)
19791996
}
19801997

1981-
if (prefs.voiceMicEnabled.value) {
1998+
if (initialForeground && prefs.voiceMicEnabled.value) {
19821999
setVoiceCaptureMode(VoiceCaptureMode.ManualMic, persistManualMic = false)
2000+
} else if (!initialForeground && prefs.voiceMicEnabled.value) {
2001+
// Process recovery without an Activity must not revive microphone capture.
2002+
prefs.setVoiceMicEnabled(false)
19832003
}
19842004

19852005
scope.launch(Dispatchers.Default) {

0 commit comments

Comments
 (0)