-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathAssistViewModel.kt
More file actions
529 lines (469 loc) · 20.1 KB
/
Copy pathAssistViewModel.kt
File metadata and controls
529 lines (469 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package io.homeassistant.companion.android.assist
import android.app.Application
import android.content.Intent
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import dagger.hilt.android.lifecycle.HiltViewModel
import io.homeassistant.companion.android.assist.ui.AssistMessage
import io.homeassistant.companion.android.assist.ui.AssistUiPipeline
import io.homeassistant.companion.android.common.R as commonR
import io.homeassistant.companion.android.common.assist.AssistAudioStrategy
import io.homeassistant.companion.android.common.assist.AssistEvent
import io.homeassistant.companion.android.common.assist.AssistViewModelBase
import io.homeassistant.companion.android.common.data.servers.ServerManager
import io.homeassistant.companion.android.common.data.websocket.impl.entities.AssistPipelineResponse
import io.homeassistant.companion.android.common.util.AudioUrlPlayer
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber
@VisibleForTesting
internal val CLOSE_INACTIVE = 30.seconds
@HiltViewModel(assistedFactory = AssistViewModel.Factory::class)
class AssistViewModel @AssistedInject constructor(
serverManager: ServerManager,
@Assisted initialAudioStrategy: AssistAudioStrategy,
audioUrlPlayer: AudioUrlPlayer,
application: Application,
) : AssistViewModelBase(serverManager, initialAudioStrategy, audioUrlPlayer, application) {
@AssistedFactory
interface Factory {
fun create(audioStrategy: AssistAudioStrategy): AssistViewModel
}
init {
viewModelScope.launch {
audioStrategy.wakeWordDetected.collect { detectedPhrase ->
if (inputMode != AssistInputMode.VOICE_ACTIVE) {
wakeWordPhrase = detectedPhrase
onMicrophoneInput()
}
}
}
}
private var filteredServerId: Int? = null
private val allPipelines = mutableMapOf<Int, List<AssistPipelineResponse>>()
private var selectedPipeline: AssistPipelineResponse? = null
private var wakeWordPhrase: String? = null
private var recorderAutoStart = true
private var requestPermission: (() -> Unit)? = null
private var requestSilently = true
private val startMessage =
AssistMessage(application.getString(commonR.string.assist_how_can_i_assist), isInput = false)
private val _conversation = mutableStateListOf(startMessage)
/**
* Conversation messages to display. The input placeholder marking an active voice recording is
* hidden: listening is already conveyed by the microphone button animation.
*/
val conversation: List<AssistMessage> by derivedStateOf {
_conversation.filterNot { it.isInput && it.isPlaceholder }
}
private val _pipelines = mutableStateListOf<AssistUiPipeline>()
val pipelines: List<AssistUiPipeline> = _pipelines
var currentPipeline by mutableStateOf<AssistUiPipeline?>(null)
private set
var inputMode by mutableStateOf<AssistInputMode?>(null)
private set
var userCanManagePipelines by mutableStateOf(false)
private set
var shouldFinish by mutableStateOf(false)
private set
/** When true, the UI should not be shown yet (waiting to confirm the pipeline is not a duplicate wake-up). The activity should finish if a duplicate is detected. */
var pendingWakeWordConfirmation by mutableStateOf(false)
private set
private var startedFromWakeWord = false
private var inactivityTimerJob: Job? = null
fun onCreate(
hasPermission: Boolean,
serverId: Int?,
pipelineId: String?,
startListening: Boolean?,
wakeWordPhrase: String?,
) {
viewModelScope.launch {
this@AssistViewModel.hasPermission = hasPermission
this@AssistViewModel.wakeWordPhrase = wakeWordPhrase
this@AssistViewModel.startedFromWakeWord = wakeWordPhrase != null
serverId?.let {
filteredServerId = serverId
selectedServerId = serverId
}
startListening?.let { recorderAutoStart = it }
if (!serverManager.isRegistered()) {
inputMode = AssistInputMode.BLOCKED
_conversation.clear()
_conversation.add(
AssistMessage(app.getString(commonR.string.not_registered), isInput = false),
)
return@launch
}
if (
pipelineId == PIPELINE_LAST_USED &&
recorderAutoStart &&
hasPermission &&
hasMicrophone &&
serverManager.getServer(selectedServerId) != null &&
serverManager.integrationRepository(selectedServerId).getLastUsedPipelineSttSupport()
) {
// Start microphone recording to prevent missing voice input while doing network checks
pendingWakeWordConfirmation = wakeWordPhrase != null
onMicrophoneInput(proactive = true)
}
val supported = checkSupport()
if (supported != true) stopRecording()
if (supported == null) { // Couldn't get config
inputMode = AssistInputMode.BLOCKED
_conversation.clear()
_conversation.add(
AssistMessage(app.getString(commonR.string.assist_connnect), isInput = false),
)
} else if (!supported) { // Core too old or doesn't include assist pipeline
inputMode = AssistInputMode.BLOCKED
_conversation.clear()
_conversation.add(
AssistMessage(
app.getString(
commonR.string.no_assist_support,
"2023.5",
app.getString(commonR.string.no_assist_support_assist_pipeline),
),
isInput = false,
),
)
} else {
setPipeline(
when {
pipelineId == PIPELINE_LAST_USED -> serverManager.integrationRepository(
selectedServerId,
).getLastUsedPipelineId()
pipelineId == PIPELINE_PREFERRED -> null
pipelineId?.isNotBlank() == true -> pipelineId
else -> null
},
)
}
if (serverManager.isRegistered()) {
loadPipelines()
}
userCanManagePipelines = serverManager.getServer()?.user?.isAdmin == true
}
}
/**
* Update the state of the Assist dialog for a new 'assistant triggered' action
* @param intent the updated intent
* @param lockedMatches whether the locked state changed and contents should be cleared
*/
fun onNewIntent(intent: Intent, lockedMatches: Boolean) {
if (
(intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) ||
intent.action in
listOf(Intent.ACTION_ASSIST, "android.intent.action.VOICE_ASSIST", Intent.ACTION_VOICE_COMMAND)
) {
if (!lockedMatches && inputMode != AssistInputMode.BLOCKED) {
_conversation.clear()
_conversation.add(startMessage)
}
if (inputMode == AssistInputMode.VOICE_ACTIVE || inputMode == AssistInputMode.VOICE_INACTIVE) {
onMicrophoneInput()
}
}
}
override fun getInput(): AssistInputMode? = inputMode
override fun setInput(inputMode: AssistInputMode) {
this.inputMode = inputMode
restartInactivityTimer()
}
/**
* Restarts the inactivity timer that closes the Assist dialog after [CLOSE_INACTIVE].
*
* The timer only runs when the input mode is [AssistInputMode.VOICE_INACTIVE],
* TTS audio is not currently playing, and the last conversation message is not a
* placeholder (assistant finished processing).
*
* Disabled for non wake word sessions to avoid auto-closing the dialog while the user
* is interacting with hands.
*/
private fun restartInactivityTimer() {
inactivityTimerJob?.cancel()
if (!startedFromWakeWord) return
fun isInactive(): Boolean {
val shouldRun = when (inputMode) {
AssistInputMode.VOICE_INACTIVE -> true
AssistInputMode.TEXT,
AssistInputMode.TEXT_ONLY,
AssistInputMode.VOICE_ACTIVE,
AssistInputMode.BLOCKED,
null,
-> false
}
if (!shouldRun || isPlayingAudio) return false
val lastMessage = _conversation.lastOrNull()
return !(lastMessage == null || lastMessage.isPlaceholder)
}
if (!isInactive()) return
inactivityTimerJob = viewModelScope.launch {
delay(CLOSE_INACTIVE)
if (isInactive()) {
shouldFinish = true
} else {
Timber.d("Inactivity timer expired but Assist is no longer inactive, not finishing")
}
}
}
private suspend fun checkSupport(): Boolean? {
if (!serverManager.isRegistered()) return false
return try {
if (!serverManager.integrationRepository(
selectedServerId,
).isHomeAssistantVersionAtLeast(2023, 5, 0)
) {
false
} else {
serverManager.webSocketRepository(selectedServerId).getConfig()?.components?.contains("assist_pipeline")
}
} catch (e: IllegalStateException) {
Timber.e(e, "Failed to check support")
false
}
}
private suspend fun loadPipelines() {
val serverIds = filteredServerId?.let { listOf(it) } ?: serverManager.servers().map { it.id }
serverIds.forEach { serverId ->
viewModelScope.launch {
val server = serverManager.getServer(serverId)
val serverPipelines = try {
serverManager.webSocketRepository(serverId).getAssistPipelines()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Timber.e(e, "Failed to load assist pipelines")
null
}
allPipelines[serverId] = serverPipelines?.pipelines ?: emptyList()
_pipelines.addAll(
serverPipelines?.pipelines.orEmpty().map {
AssistUiPipeline(
serverId = serverId,
serverName = server?.friendlyName ?: "",
id = it.id,
name = it.name,
)
},
)
}
}
}
fun changePipeline(serverId: Int, id: String) = viewModelScope.launch {
if (serverId == selectedServerId && id == selectedPipeline?.id) return@launch
stopRecording(sendRecorded = false)
stopPlayback()
selectedServerId = serverId
setPipeline(id)
}
private suspend fun setPipeline(id: String?) {
selectedPipeline =
allPipelines[selectedServerId]?.firstOrNull { it.id == id }
?: try {
serverManager.webSocketRepository(selectedServerId).getAssistPipeline(id)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Timber.e(e, "Failed to get assist pipeline")
null
}
selectedPipeline?.let {
currentPipeline = AssistUiPipeline(
serverId = selectedServerId,
serverName = serverManager.getServer(selectedServerId)?.friendlyName ?: "",
id = it.id,
name = it.name,
)
try {
serverManager.integrationRepository(selectedServerId).setLastUsedPipeline(it.id, it.sttEngine != null)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Timber.e(e, "Failed to set last used pipeline")
}
_conversation.clear()
_conversation.add(startMessage)
clearPipelineData()
if (hasMicrophone && it.sttEngine != null) {
if (recorderAutoStart && (hasPermission || requestSilently)) {
inputMode = AssistInputMode.VOICE_INACTIVE
onMicrophoneInput(proactive = null)
} else { // already requested permission once and was denied
inputMode = AssistInputMode.TEXT
}
} else {
inputMode = AssistInputMode.TEXT_ONLY
}
restartInactivityTimer()
} ?: run {
if (!id.isNullOrBlank()) {
setPipeline(null) // Try falling back to default pipeline
} else {
Timber.w("Server $selectedServerId does not have any pipelines")
inputMode = AssistInputMode.BLOCKED
_conversation.clear()
_conversation.add(
AssistMessage(app.getString(commonR.string.assist_error), isInput = false),
)
}
}
}
fun onChangeInput() {
when (inputMode) {
null, AssistInputMode.BLOCKED, AssistInputMode.TEXT_ONLY -> { /* Do nothing */ }
AssistInputMode.TEXT -> {
inputMode = AssistInputMode.VOICE_INACTIVE
if (hasPermission || requestSilently) {
onMicrophoneInput()
}
}
AssistInputMode.VOICE_INACTIVE -> {
inputMode = AssistInputMode.TEXT
}
AssistInputMode.VOICE_ACTIVE -> {
stopRecording(sendRecorded = false)
// Remove placeholder message if present from proactive recording
if (_conversation.lastOrNull()?.let { it.isPlaceholder && it.isInput } == true) {
_conversation.removeAt(_conversation.size - 1)
}
inputMode = AssistInputMode.TEXT
}
}
restartInactivityTimer()
}
fun onTextInput(input: String) = runAssistPipeline(input)
/**
* Start/stop microphone input for Assist, depending on the current state.
* @param proactive true if proactive, null if not important, false if not
*/
fun onMicrophoneInput(proactive: Boolean? = false) {
if (!hasPermission) {
requestPermission?.let { it() }
return
}
if (inputMode == AssistInputMode.VOICE_ACTIVE && proactive == false) {
stopRecording()
return
}
stopPlayback()
if (!recorderProactive) {
audioStrategy.requestFocus()
setupRecorder(
onError = {
stopRecording()
_conversation.add(
AssistMessage(app.getString(commonR.string.assist_error), isInput = false, isError = true),
)
},
)
}
inputMode = AssistInputMode.VOICE_ACTIVE
if (proactive == true) _conversation.add(AssistMessage.placeholder(isInput = true))
if (proactive != true) runAssistPipeline(null)
restartInactivityTimer()
recorderProactive = proactive == true
}
private fun runAssistPipeline(text: String?) {
val isVoice = text == null
stopPlayback()
val userMessage = text?.let { AssistMessage(it, isInput = true) } ?: AssistMessage.placeholder(isInput = true)
_conversation.add(userMessage)
val haMessage = AssistMessage.placeholder(isInput = false)
if (!isVoice) _conversation.add(haMessage)
var message = if (isVoice) userMessage else haMessage
// Capture and clear wake word phrase - it should only be sent once for the initial command
val wakeWord = wakeWordPhrase.also { wakeWordPhrase = null }
runAssistPipelineInternal(
text = text,
pipeline = selectedPipeline,
wakeWordPhrase = wakeWord,
) { event ->
when (event) {
is AssistEvent.Message -> {
_conversation.indexOf(message).takeIf { pos -> pos >= 0 }?.let { index ->
val isInput = event is AssistEvent.Message.Input
val isError = event is AssistEvent.Message.Error
_conversation[index] = message.copy(
message = event.message.trim(),
isInput = isInput,
isError = isError,
)
if (isInput) {
_conversation.add(haMessage)
message = haMessage
}
if (isError && inputMode == AssistInputMode.VOICE_ACTIVE) {
stopRecording()
}
}
restartInactivityTimer()
}
is AssistEvent.MessageChunk -> {
val lastMessage = _conversation.last()
if (lastMessage == haMessage) {
// Remove '...' message and add the chunk received
_conversation.removeAt(_conversation.lastIndex)
_conversation.add(lastMessage.copy(message = event.chunk))
} else {
// Replace last message with the updated message with the new chunk append
_conversation[_conversation.lastIndex] =
lastMessage.copy(message = lastMessage.message + event.chunk)
}
}
is AssistEvent.PipelineStarted -> { /* handled below */ }
is AssistEvent.PipelineEnded,
is AssistEvent.PlaybackFinished,
-> restartInactivityTimer()
is AssistEvent.ContinueConversation -> onMicrophoneInput()
is AssistEvent.Dismiss -> shouldFinish = true
}
if (!shouldFinish && pendingWakeWordConfirmation) {
// Any event confirms this is not a duplicate wake-up, so the UI can be shown.
// Skipped when finishing to avoid a brief UI flash before dismissal.
pendingWakeWordConfirmation = false
}
}
}
fun setPermissionInfo(hasPermission: Boolean, callback: () -> Unit) {
this.hasPermission = hasPermission
requestPermission = callback
}
fun onPermissionResult(granted: Boolean) {
hasPermission = granted
val proactive = currentPipeline == null
if (granted) {
inputMode = AssistInputMode.VOICE_INACTIVE
onMicrophoneInput(proactive = proactive)
} else if (requestSilently && !proactive) { // Don't notify the user if they haven't explicitly requested
inputMode = AssistInputMode.TEXT
} else if (!requestSilently) {
_conversation.add(AssistMessage(app.getString(commonR.string.assist_permission), isInput = false))
}
restartInactivityTimer()
if (!proactive) requestSilently = false
}
fun onPause() {
requestPermission = null
inactivityTimerJob?.cancel()
stopRecording()
}
fun onDestroy() {
requestPermission = null
inactivityTimerJob?.cancel()
stopRecording()
stopPlayback()
}
}