@@ -10,34 +10,75 @@ import android.content.Context
1010import android.content.Intent
1111import android.content.pm.PackageManager
1212import android.content.pm.ServiceInfo
13+ import android.util.Log
1314import androidx.core.app.NotificationCompat
1415import androidx.core.app.ServiceCompat
1516import androidx.core.content.ContextCompat
17+ import kotlinx.coroutines.CancellationException
1618import kotlinx.coroutines.CoroutineScope
1719import kotlinx.coroutines.Dispatchers
1820import kotlinx.coroutines.Job
1921import kotlinx.coroutines.SupervisorJob
2022import kotlinx.coroutines.cancel
2123import kotlinx.coroutines.flow.combine
2224import 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. */
2528class 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+
236316internal fun foregroundServiceTypes (
237317 voiceMode : VoiceCaptureMode ,
238318 backgroundLocationActive : Boolean ,
0 commit comments