Skip to content

Commit 9413a5a

Browse files
committed
fix(android): defer runtime startup after first draw
1 parent b7cafb5 commit 9413a5a

3 files changed

Lines changed: 140 additions & 45 deletions

File tree

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

Lines changed: 108 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,117 @@ package ai.openclaw.app
22

33
import ai.openclaw.app.ui.OpenClawTheme
44
import ai.openclaw.app.ui.RootScreen
5+
import android.content.Intent
56
import android.os.Bundle
67
import android.view.WindowManager
78
import androidx.activity.ComponentActivity
89
import androidx.activity.compose.setContent
910
import androidx.activity.viewModels
11+
import androidx.compose.foundation.layout.Box
12+
import androidx.compose.foundation.layout.fillMaxSize
1013
import androidx.compose.material3.Surface
14+
import androidx.compose.material3.Text
15+
import androidx.compose.runtime.Composable
16+
import androidx.compose.runtime.LaunchedEffect
17+
import androidx.compose.runtime.getValue
18+
import androidx.compose.runtime.mutableStateOf
19+
import androidx.compose.runtime.remember
20+
import androidx.compose.runtime.setValue
21+
import androidx.compose.runtime.withFrameNanos
22+
import androidx.compose.ui.Alignment
1123
import androidx.compose.ui.Modifier
24+
import androidx.compose.ui.graphics.Color
25+
import androidx.compose.ui.text.font.FontWeight
26+
import androidx.compose.ui.unit.sp
1227
import androidx.core.view.WindowCompat
1328
import androidx.lifecycle.Lifecycle
1429
import androidx.lifecycle.lifecycleScope
1530
import androidx.lifecycle.repeatOnLifecycle
31+
import kotlinx.coroutines.Dispatchers
1632
import kotlinx.coroutines.launch
33+
import kotlinx.coroutines.withContext
1734

1835
/**
1936
* Main Android activity that owns Compose UI attachment and runtime UI wiring.
2037
*/
2138
class MainActivity : ComponentActivity() {
2239
private val viewModel: MainViewModel by viewModels()
2340
private lateinit var permissionRequester: PermissionRequester
41+
private var initializedViewModel: MainViewModel? = null
2442
private var didAttachRuntimeUi = false
2543
private var didStartNodeService = false
44+
private var didStartViewModelCollectors = false
45+
private var foreground = false
46+
private var pendingIntent: Intent? = null
2647

2748
override fun onCreate(savedInstanceState: Bundle?) {
2849
super.onCreate(savedInstanceState)
29-
handleAssistantIntent(intent)
50+
pendingIntent = intent
3051
WindowCompat.setDecorFitsSystemWindows(window, false)
3152
permissionRequester = PermissionRequester(this)
3253

54+
setContent {
55+
var activeViewModel by remember { mutableStateOf<MainViewModel?>(null) }
56+
57+
LaunchedEffect(Unit) {
58+
withFrameNanos { }
59+
withContext(Dispatchers.Default) {
60+
(application as NodeApp).prefs
61+
}
62+
val readyViewModel = viewModel
63+
activateViewModel(readyViewModel)
64+
activeViewModel = readyViewModel
65+
}
66+
67+
OpenClawTheme {
68+
activeViewModel?.let { RootScreen(viewModel = it) } ?: StartupSurface()
69+
}
70+
}
71+
}
72+
73+
override fun onStart() {
74+
super.onStart()
75+
foreground = true
76+
initializedViewModel?.setForeground(true)
77+
}
78+
79+
override fun onStop() {
80+
foreground = false
81+
initializedViewModel?.setForeground(false)
82+
super.onStop()
83+
}
84+
85+
override fun onNewIntent(intent: android.content.Intent) {
86+
super.onNewIntent(intent)
87+
setIntent(intent)
88+
pendingIntent = intent
89+
initializedViewModel?.let { handleAssistantIntent(viewModel = it, intent = intent) }
90+
}
91+
92+
/**
93+
* Wires MainViewModel only after Activity first draw and background prefs warm-up.
94+
*/
95+
private fun activateViewModel(readyViewModel: MainViewModel) {
96+
if (initializedViewModel != null) return
97+
initializedViewModel = readyViewModel
98+
readyViewModel.setForeground(foreground)
99+
startViewModelCollectors(readyViewModel)
100+
pendingIntent?.let { initialIntent ->
101+
handleAssistantIntent(viewModel = readyViewModel, intent = initialIntent)
102+
pendingIntent = null
103+
}
104+
}
105+
106+
/**
107+
* Starts lifecycle collectors after ViewModel construction so they cannot force early startup.
108+
*/
109+
private fun startViewModelCollectors(readyViewModel: MainViewModel) {
110+
if (didStartViewModelCollectors) return
111+
didStartViewModelCollectors = true
112+
33113
lifecycleScope.launch {
34114
repeatOnLifecycle(Lifecycle.State.STARTED) {
35-
viewModel.preventSleep.collect { enabled ->
115+
readyViewModel.preventSleep.collect { enabled ->
36116
if (enabled) {
37117
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
38118
} else {
@@ -44,10 +124,10 @@ class MainActivity : ComponentActivity() {
44124

45125
lifecycleScope.launch {
46126
repeatOnLifecycle(Lifecycle.State.STARTED) {
47-
viewModel.runtimeInitialized.collect { ready ->
127+
readyViewModel.runtimeInitialized.collect { ready ->
48128
if (!ready || didAttachRuntimeUi) return@collect
49129
// Runtime UI helpers need an Activity owner, so attach once after NodeRuntime is ready.
50-
viewModel.attachRuntimeUi(owner = this@MainActivity, permissionRequester = permissionRequester)
130+
readyViewModel.attachRuntimeUi(owner = this@MainActivity, permissionRequester = permissionRequester)
51131
didAttachRuntimeUi = true
52132
if (!didStartNodeService) {
53133
NodeForegroundService.start(this@MainActivity)
@@ -56,36 +136,15 @@ class MainActivity : ComponentActivity() {
56136
}
57137
}
58138
}
59-
60-
setContent {
61-
OpenClawTheme {
62-
Surface(modifier = Modifier) {
63-
RootScreen(viewModel = viewModel)
64-
}
65-
}
66-
}
67-
}
68-
69-
override fun onStart() {
70-
super.onStart()
71-
viewModel.setForeground(true)
72-
}
73-
74-
override fun onStop() {
75-
viewModel.setForeground(false)
76-
super.onStop()
77-
}
78-
79-
override fun onNewIntent(intent: android.content.Intent) {
80-
super.onNewIntent(intent)
81-
setIntent(intent)
82-
handleAssistantIntent(intent)
83139
}
84140

85141
/**
86142
* Routes assistant/app-action intents into ViewModel state without recreating the activity.
87143
*/
88-
private fun handleAssistantIntent(intent: android.content.Intent?) {
144+
private fun handleAssistantIntent(
145+
viewModel: MainViewModel,
146+
intent: Intent?,
147+
) {
89148
parseHomeDestinationIntent(intent)?.let { destination ->
90149
viewModel.requestHomeDestination(destination)
91150
return
@@ -94,3 +153,23 @@ class MainActivity : ComponentActivity() {
94153
viewModel.handleAssistantLaunch(request)
95154
}
96155
}
156+
157+
@Composable
158+
private fun StartupSurface() {
159+
Surface(
160+
modifier = Modifier.fillMaxSize(),
161+
color = Color.Black,
162+
contentColor = Color.White,
163+
) {
164+
Box(
165+
modifier = Modifier.fillMaxSize(),
166+
contentAlignment = Alignment.Center,
167+
) {
168+
Text(
169+
text = "OPENCLAW",
170+
fontSize = 22.sp,
171+
fontWeight = FontWeight.Medium,
172+
)
173+
}
174+
}
175+
}

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

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@ import android.app.Application
1414
import androidx.lifecycle.AndroidViewModel
1515
import androidx.lifecycle.LifecycleOwner
1616
import androidx.lifecycle.viewModelScope
17+
import kotlinx.coroutines.Dispatchers
1718
import kotlinx.coroutines.ExperimentalCoroutinesApi
1819
import kotlinx.coroutines.flow.MutableStateFlow
1920
import kotlinx.coroutines.flow.SharingStarted
2021
import kotlinx.coroutines.flow.StateFlow
2122
import kotlinx.coroutines.flow.flatMapLatest
2223
import kotlinx.coroutines.flow.flowOf
2324
import kotlinx.coroutines.flow.stateIn
25+
import kotlinx.coroutines.launch
2426

2527
/**
2628
* UI-facing bridge that exposes NodeRuntime and preference state as Compose-friendly StateFlows.
@@ -32,7 +34,11 @@ class MainViewModel(
3234
private val nodeApp = app as NodeApp
3335
private val prefs = nodeApp.prefs
3436
private val runtimeRef = MutableStateFlow<NodeRuntime?>(null)
35-
private var foreground = true
37+
38+
@Volatile private var foreground = false
39+
40+
@Volatile private var runtimeStartupQueued = false
41+
3642
private val _requestedHomeDestination = MutableStateFlow<HomeDestination?>(null)
3743
val requestedHomeDestination: StateFlow<HomeDestination?> = _requestedHomeDestination
3844
private val _startOnboardingAtGatewaySetup = MutableStateFlow(false)
@@ -53,6 +59,19 @@ class MainViewModel(
5359
return runtime
5460
}
5561

62+
/**
63+
* Starts the node runtime off the main thread so fresh installs can render
64+
* the shell before encrypted prefs, device identity, and gateway setup warm up.
65+
*/
66+
private fun queueRuntimeStartup() {
67+
if (runtimeRef.value != null || runtimeStartupQueued) return
68+
runtimeStartupQueued = true
69+
viewModelScope.launch(Dispatchers.Default) {
70+
runCatching { ensureRuntime() }
71+
runtimeStartupQueued = false
72+
}
73+
}
74+
5675
/**
5776
* Adapts a runtime StateFlow to a stable ViewModel StateFlow before runtime startup.
5877
*/
@@ -180,12 +199,6 @@ class MainViewModel(
180199
val chatSessions: StateFlow<List<ChatSessionEntry>> = runtimeState(initial = emptyList()) { it.chatSessions }
181200
val pendingRunCount: StateFlow<Int> = runtimeState(initial = 0) { it.pendingRunCount }
182201

183-
init {
184-
if (prefs.onboardingCompleted.value) {
185-
ensureRuntime()
186-
}
187-
}
188-
189202
val canvas: CanvasController
190203
get() = ensureRuntime().canvas
191204

@@ -213,13 +226,10 @@ class MainViewModel(
213226
*/
214227
fun setForeground(value: Boolean) {
215228
foreground = value
216-
val runtime =
217-
if (value && prefs.onboardingCompleted.value) {
218-
ensureRuntime()
219-
} else {
220-
runtimeRef.value
221-
}
222-
runtime?.setForeground(value)
229+
if (value && prefs.onboardingCompleted.value) {
230+
queueRuntimeStartup()
231+
}
232+
runtimeRef.value?.setForeground(value)
223233
}
224234

225235
fun setDisplayName(value: String) {

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,10 @@ fun ShellScreen(
119119
var settingsRoute by rememberSaveable { mutableStateOf(SettingsRoute.Home) }
120120
var returnToOverviewFromSettings by rememberSaveable { mutableStateOf(false) }
121121
var commandOpen by rememberSaveable { mutableStateOf(false) }
122+
var voiceScreenWasActive by rememberSaveable { mutableStateOf(false) }
122123
val requestedHomeDestination by viewModel.requestedHomeDestination.collectAsState()
123124
val pendingTrust by viewModel.pendingGatewayTrust.collectAsState()
125+
val runtimeInitialized by viewModel.runtimeInitialized.collectAsState()
124126

125127
LaunchedEffect(requestedHomeDestination) {
126128
val destination = requestedHomeDestination ?: return@LaunchedEffect
@@ -141,8 +143,12 @@ fun ShellScreen(
141143
viewModel.clearRequestedHomeDestination()
142144
}
143145

144-
LaunchedEffect(activeTab) {
145-
viewModel.setVoiceScreenActive(activeTab == Tab.Voice)
146+
LaunchedEffect(activeTab, runtimeInitialized) {
147+
val voiceScreenActive = activeTab == Tab.Voice
148+
if (voiceScreenActive || voiceScreenWasActive || runtimeInitialized) {
149+
viewModel.setVoiceScreenActive(voiceScreenActive)
150+
}
151+
voiceScreenWasActive = voiceScreenActive
146152
}
147153

148154
BackHandler(enabled = activeTab != Tab.Overview) {

0 commit comments

Comments
 (0)