diff --git a/.gitignore b/.gitignore
index 94af20a..559bf7b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,4 +10,5 @@ captures/
keystore.properties
*.jks
*.keystore
+keystore/
.git-commit-helper.sh
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 02298f0..bd4cf9b 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -11,8 +11,8 @@ android {
applicationId = "dev.vibex.companion"
minSdk = 26
targetSdk = 35
- versionCode = 18
- versionName = "0.4.5"
+ versionCode = 23
+ versionName = "0.5.0"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
@@ -24,7 +24,10 @@ android {
isMinifyEnabled = false
}
}
- buildFeatures { compose = true }
+ buildFeatures {
+ compose = true
+ buildConfig = true
+ }
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index b51c42a..bd35061 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -4,12 +4,14 @@
+
+
+ android:windowSoftInputMode="stateHidden|adjustResize">
@@ -41,5 +43,14 @@
android:name=".monitor.CompanionMonitorService"
android:exported="false"
android:foregroundServiceType="dataSync" />
+
+
+
diff --git a/app/src/main/java/dev/vibex/companion/app/CompanionModel.kt b/app/src/main/java/dev/vibex/companion/app/CompanionModel.kt
index 3a4153d..17f3136 100644
--- a/app/src/main/java/dev/vibex/companion/app/CompanionModel.kt
+++ b/app/src/main/java/dev/vibex/companion/app/CompanionModel.kt
@@ -36,6 +36,16 @@ import dev.vibex.companion.DiscoveredLanHost
import dev.vibex.companion.EventFold
import dev.vibex.companion.ExtensionCatalogItem
import dev.vibex.companion.HostApi
+import dev.vibex.companion.ProviderInstanceItem
+import dev.vibex.companion.EngineHandoffPreview
+import dev.vibex.companion.SideChatMessage
+import dev.vibex.companion.TimelineItem
+import dev.vibex.companion.buildSideChatContext
+import dev.vibex.companion.providerInstances
+import dev.vibex.companion.previewEngineHandoff
+import dev.vibex.companion.confirmEngineHandoff
+import dev.vibex.companion.sideChatSend
+import dev.vibex.companion.sideChatAbort
import dev.vibex.companion.HostOrigin
import dev.vibex.companion.KanbanSessionStatus
import dev.vibex.companion.KanbanSessionSummary
@@ -82,6 +92,7 @@ import dev.vibex.companion.setKanbanSessionPinned
import dev.vibex.companion.updateKanbanSessionStatus
import dev.vibex.companion.app.data.CredentialStore
import dev.vibex.companion.app.data.HostProfile
+import dev.vibex.companion.app.data.ModelPreferencesStore
import dev.vibex.companion.app.data.OfflineStore
import dev.vibex.companion.app.data.ProfileStore
import dev.vibex.companion.app.data.StoredReachability
@@ -111,6 +122,7 @@ import dev.vibex.companion.app.monitor.SystemNotificationAction
import dev.vibex.companion.app.monitor.SystemNotifier
import dev.vibex.companion.app.monitor.TaskLiveActivityState
import dev.vibex.companion.app.monitor.VibeXActivityPhase
+import dev.vibex.companion.app.ui.theme.AppLanguage
import dev.vibex.companion.app.ui.theme.Appearance
import dev.vibex.companion.app.ui.theme.AccentChoice
import dev.vibex.companion.app.net.EventSocket
@@ -123,8 +135,16 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
+enum class CloudNodePreference {
+ Auto,
+ OfficialCloud,
+ CustomNode,
+}
+
data class UiState(
val profiles: List = emptyList(),
val selectedHostId: String? = null,
@@ -151,6 +171,11 @@ data class UiState(
val monitor: Boolean = true,
val appearance: Appearance = Appearance.System,
val accent: AccentChoice = AccentChoice.Blue,
+ val language: AppLanguage = AppLanguage.ZhHans,
+ val confirmHighRiskApproval: Boolean = true,
+ val muteForegroundNotifications: Boolean = true,
+ val customRelayOrigin: String = "",
+ val pendingQrNodeChoiceRaw: String? = null,
val streamDisplay: StreamDisplayPrefs = StreamDisplayPrefs(),
val hostVersion: String = "",
val hostProtocol: String = "",
@@ -191,6 +216,12 @@ data class UiState(
val accountError: String? = null,
val accountLoginRequested: Boolean = false,
val desktopConnect: DesktopConnectSheet? = null,
+ val connectedSasNotice: ConnectedSasNotice? = null,
+ val isAutoConnectingInBackground: Boolean = false,
+ val autoConnectingHostName: String? = null,
+ val lanSasState: LanSasInlineState? = null,
+ val collabUnreadCount: Int = 0,
+ val manuallyCompletedSessionIds: Set = emptySet(),
val route: Route = Route.Conversations,
) {
/** Signed out with nothing paired, or right after an explicit sign-out. */
@@ -204,6 +235,7 @@ sealed class Route {
data object ManualPair : Route()
data object Folders : Route()
data object Conversations : Route()
+ data object NewThread : Route()
data object Status : Route()
data object Collaboration : Route()
data class Settings(val section: SettingsSection? = null) : Route()
@@ -219,9 +251,15 @@ data class CollabDetailBundle(
)
private const val PREF_ACCOUNT_LOGIN_REQUESTED = "account_login_requested"
+private const val PREF_MANUALLY_COMPLETED_SESSIONS = "vibex.manuallyCompletedSessionIDs"
+
+/** The desktop revokes a phone when another phone connects, it signs out, or the user removes it. */
+private const val REVOKED_FAILURE_REASON = "连接授权已失效"
+private const val REVOKED_NOTICE = "电脑已收回本机的连接授权,请重新连接"
class CompanionModel(application: Application) : AndroidViewModel(application) {
private val prefs = application.getSharedPreferences("vibex_companion_prefs", Context.MODE_PRIVATE)
+ val modelPrefs = ModelPreferencesStore(application)
private val profiles = ProfileStore(application)
private val credentials = CredentialStore(application)
private val offline = OfflineStore(application)
@@ -234,11 +272,166 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
private val socket = EventSocket()
private val sessions = java.util.concurrent.ConcurrentHashMap()
private val subscriptions = java.util.concurrent.ConcurrentHashMap()
+ private val connectMutex = Mutex()
+ @Volatile
+ private var lastConnectSuccessMs: Long = 0L
+ @Volatile
+ private var lastPushedSavedHostsSignature: String? = null
+ @Volatile
+ private var rawAccountDesktops: List = emptyList()
+ private val removedAccountHostIds = java.util.concurrent.ConcurrentHashMap.newKeySet()
private var pingJob: Job? = null
+ private var reconnectJob: Job? = null
+ private var recoveringJob: Job? = null
+ private var reconnectAttempt = 0
+ private var socketDownSinceMs: Long? = null
+ private var networkCallback: android.net.ConnectivityManager.NetworkCallback? = null
+ private val connLog = dev.vibex.companion.ConnectionLog()
+
+ private fun connLog(msg: String, warn: Boolean = false) {
+ val line = "${_state.value.connection} $msg"
+ connLog.add("${System.currentTimeMillis()} $line")
+ if (warn) android.util.Log.w("VxConn", line) else android.util.Log.i("VxConn", line)
+ }
+
+ private fun isEmulator(): Boolean =
+ Build.FINGERPRINT.contains("generic", ignoreCase = true)
+
+ private fun isLanTransportAvailable(): Boolean {
+ if (isEmulator()) return true
+ val cm = getApplication()
+ .getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager
+ ?: return false
+ val active = cm.activeNetwork ?: return false
+ val caps = cm.getNetworkCapabilities(active) ?: return false
+ return caps.hasTransport(android.net.NetworkCapabilities.TRANSPORT_WIFI) ||
+ caps.hasTransport(android.net.NetworkCapabilities.TRANSPORT_ETHERNET) ||
+ (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
+ caps.hasTransport(android.net.NetworkCapabilities.TRANSPORT_USB))
+ }
+
+ private fun migrateProfileOrigins(profile: HostProfile): HostProfile {
+ val migratedLast = profile.lastSuccessOrigin?.let { PairingClient.migrateLegacyRelayOrigin(it) }
+ val migratedReach = profile.reachability
+ .map { it.copy(origin = PairingClient.migrateLegacyRelayOrigin(it.origin)) }
+ .distinctBy { it.origin }
+ val migratedName = when {
+ profile.name.startsWith("VibeX (") -> profile.name.replaceFirst("VibeX (", "Dimo (")
+ profile.name == "VibeX 电脑" -> "Dimo 电脑"
+ profile.name == "VibeX 桌面端" || profile.name == "VibeX Desktop" ||
+ profile.name.equals("Local Host", ignoreCase = true) -> "Dimo 桌面端"
+ else -> profile.name
+ }
+ return if (migratedLast != profile.lastSuccessOrigin || migratedReach != profile.reachability || migratedName != profile.name) {
+ profile.copy(
+ name = migratedName,
+ lastSuccessOrigin = migratedLast,
+ reachability = migratedReach,
+ )
+ } else {
+ profile
+ }
+ }
+
+ private fun currentAccountRelayBase(overview: VibeXAccountOverview? = _state.value.accountOverview): String =
+ AccountDesktops.relayBase(
+ overview?.assignedRelayServer,
+ VibeXAccountRepository.DEFAULT_OFFICIAL_RELAY_BASE,
+ )
+
+ private fun currentOnlineLanHostIds(hosts: List = _state.value.discoveredHosts): Set =
+ hosts.asSequence()
+ .filter { !it.isCloudService }
+ .mapNotNull { host ->
+ AccountDesktops.rawHostId(host.hostId.orEmpty())
+ .lowercase(java.util.Locale.ROOT)
+ .takeIf { it.isNotEmpty() }
+ }
+ .toSet()
+
+ private fun currentPairedHostIds(list: List = _state.value.profiles): Set =
+ list.asSequence()
+ .map { AccountDesktops.rawHostId(it.hostId).lowercase(java.util.Locale.ROOT) }
+ .filter { it.isNotEmpty() && !AccountDesktops.isPlaceholderHostId(it) }
+ .toSet()
+
+ private fun filterAndDeduplicateAccountDesktops(
+ source: List,
+ hosts: List,
+ profileList: List,
+ ): List {
+ val lanIds = currentOnlineLanHostIds(hosts)
+ val filtered = source.filter { desktop ->
+ val key = AccountDesktops.rawHostId(desktop.hostId).lowercase(java.util.Locale.ROOT)
+ if (desktop.cloudOnline || key in lanIds) {
+ removedAccountHostIds.remove(key)
+ true
+ } else {
+ key !in removedAccountHostIds
+ }
+ }
+ return AccountDesktops.deduplicate(
+ desktops = filtered,
+ onlineLanHostIds = lanIds,
+ pairedHostIds = currentPairedHostIds(profileList),
+ )
+ }
+
+ /** Schedule one (and only one) backoff reconnect; resets via [markConnected]. */
+ private fun scheduleReconnect(reason: String, immediate: Boolean = false) {
+ if (selectedProfile() == null) return
+ if (reconnectJob?.isActive == true) {
+ if (!immediate || connectMutex.isLocked) return
+ reconnectJob?.cancel()
+ }
+ val delayMs = if (immediate) 0L else dev.vibex.companion.ConnectionPolicy.backoffMs(reconnectAttempt, Math.random())
+ connLog("reconnect scheduled in ${delayMs}ms attempt=$reconnectAttempt reason=$reason")
+ reconnectJob = viewModelScope.launch {
+ delay(delayMs)
+ val profile = selectedProfile() ?: return@launch
+ reconnectAttempt += 1
+ connect(profile, force = true)
+ }
+ }
+
+ private fun markConnected() {
+ reconnectJob?.cancel()
+ recoveringJob?.cancel()
+ reconnectAttempt = 0
+ socketDownSinceMs = null
+ connLog("connected")
+ }
+
+ private fun registerNetworkCallback() {
+ val cm = getApplication().getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager ?: return
+ val cb = object : android.net.ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: android.net.Network) {
+ viewModelScope.launch {
+ if (_state.value.connection != ConnectionState.Online || socketDownSinceMs != null) {
+ connLog("network available -> immediate reconnect")
+ scheduleReconnect("network-change", immediate = true)
+ }
+ }
+ }
+ }
+ runCatching { cm.registerDefaultNetworkCallback(cb); networkCallback = cb }
+ }
+
+ override fun onCleared() {
+ networkCallback?.let { cb ->
+ runCatching {
+ (getApplication().getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager)
+ .unregisterNetworkCallback(cb)
+ }
+ }
+ super.onCleared()
+ }
private var timelinePollJob: Job? = null
private var connectPollJob: Job? = null
+ private var lanSasPollJob: Job? = null
private var autoReconnectJob: Job? = null
private var noticeDismissJob: Job? = null
+ private var sasNoticeDismissJob: Job? = null
private var pendingConflictRetryAction: (() -> Unit)? = null
private val declinedCloudFallbackHostIds = java.util.concurrent.ConcurrentHashMap.newKeySet()
private val notifiedEventKeys = java.util.concurrent.ConcurrentHashMap.newKeySet()
@@ -254,9 +447,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
@Volatile
private var didSeedKnownConversations: Boolean = false
@Volatile
- private var hasAutoOpenedInitialConversation: Boolean = false
- @Volatile
- private var userRequestedNewChatLanding: Boolean = false
+ private var didAttemptInitialAccountAutoConnect: Boolean = false
@Volatile
private var boostPollingUntil: Long = 0L
@@ -268,12 +459,47 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
+ fun presentConnectedSasNotice(hostName: String, sasCode: String) {
+ val code = sasCode.trim()
+ if (code.isEmpty()) return
+ val notice = ConnectedSasNotice(
+ id = java.util.UUID.randomUUID().toString(),
+ hostName = hostName.ifBlank { "电脑" },
+ sasCode = code,
+ )
+ sasNoticeDismissJob?.cancel()
+ _state.update { it.copy(connectedSasNotice = notice) }
+ sasNoticeDismissJob = viewModelScope.launch {
+ delay(4_500L)
+ _state.update { current ->
+ if (current.connectedSasNotice?.id == notice.id) current.copy(connectedSasNotice = null) else current
+ }
+ }
+ }
+
+ fun dismissConnectedSasNotice() {
+ sasNoticeDismissJob?.cancel()
+ sasNoticeDismissJob = null
+ _state.update { it.copy(connectedSasNotice = null) }
+ }
+
private val _state = MutableStateFlow(UiState())
val state: StateFlow = _state
init {
- val stored = profiles.load()
+ registerNetworkCallback()
+ val rawStored = profiles.load()
+ val migratedProfiles = rawStored.profiles.map(::migrateProfileOrigins)
+ val stored = if (migratedProfiles != rawStored.profiles) {
+ rawStored.copy(profiles = migratedProfiles).also { profiles.save(it) }
+ } else {
+ rawStored
+ }
val savedAutoConnect = prefs.getBoolean("auto_connect", true)
+ val savedManualDone = prefs.getStringSet(PREF_MANUALLY_COMPLETED_SESSIONS, emptySet())
+ .orEmpty()
+ .filter { it.isNotBlank() }
+ .toSet()
val selectedHostId = stored.selectedHostId ?: stored.profiles.firstOrNull()?.hostId
val selected = stored.profiles.find { it.hostId == selectedHostId }
val hasAccountToken = accountRepo.getToken() != null
@@ -283,10 +509,15 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
selectedProjectId = selected?.selectedProjectId,
appearance = stored.appearance,
accent = if (stored.accent == AccentChoice.Ink) AccentChoice.Blue else stored.accent,
+ language = stored.language,
+ confirmHighRiskApproval = stored.confirmHighRiskApproval,
+ muteForegroundNotifications = stored.muteForegroundNotifications,
+ customRelayOrigin = stored.customRelayOrigin,
streamDisplay = stored.streamDisplay,
autoConnect = savedAutoConnect,
accountSignedIn = hasAccountToken,
accountLoginRequested = prefs.getBoolean(PREF_ACCOUNT_LOGIN_REQUESTED, false),
+ manuallyCompletedSessionIds = savedManualDone,
route = Route.Conversations,
connection = if (stored.profiles.isEmpty() || !savedAutoConnect) ConnectionState.Offline else ConnectionState.Connecting,
connectionFailureReason = if (!savedAutoConnect && stored.profiles.isNotEmpty()) "自动连接已关闭" else null,
@@ -324,8 +555,18 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
)
}
+ private var isAppInForeground: Boolean = true
+
fun onAppForegroundChanged(inForeground: Boolean) {
+ isAppInForeground = inForeground
if (inForeground) {
+ if (_state.value.profiles.isNotEmpty() &&
+ (_state.value.connection != ConnectionState.Online || socketDownSinceMs != null) &&
+ _state.value.connection != ConnectionState.AuthRequired
+ ) {
+ connLog("foreground -> immediate reconnect")
+ scheduleReconnect("foreground", immediate = true)
+ }
// If the live activity was only a temporary background standby pill, clear it on return
val currentLive = _state.value.liveActivity
if (currentLive != null && currentLive.stageTitle == "后台守护中") {
@@ -355,7 +596,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
conversationTitle = title,
phase = VibeXActivityPhase.Thinking,
stageTitle = "后台守护中",
- stageSubtitle = "VibeX 正在后台实时监听任务进展,点按返回会话",
+ stageSubtitle = "Dimo 正在后台实时监听任务进展,点按返回会话",
progress = 0.18f,
completed = 0,
total = 0,
@@ -432,23 +673,25 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
val current = _state.value
val sheetStage = current.desktopConnect?.stage
val accountConnectInFlight = sheetStage is DesktopConnectStage.Connecting ||
- sheetStage is DesktopConnectStage.AwaitingApproval
- if (current.profiles.isNotEmpty() && current.autoConnect && !accountConnectInFlight) {
- if (
- current.connection == ConnectionState.Offline ||
- current.connection == ConnectionState.Recovering ||
- current.connection == ConnectionState.HostSleeping
- ) {
- val profile = selectedProfile()
- if (profile != null) {
- connect(profile)
- }
- }
+ sheetStage is DesktopConnectStage.AwaitingApproval
+ if (
+ current.profiles.isNotEmpty() &&
+ current.autoConnect &&
+ !accountConnectInFlight &&
+ reconnectJob?.isActive != true &&
+ !connectMutex.isLocked &&
+ (current.connection == ConnectionState.Offline ||
+ current.connection == ConnectionState.HostSleeping) &&
+ current.connectionFailureReason != REVOKED_FAILURE_REASON &&
+ current.pendingCloudFallbackOrigin == null
+ ) {
+ scheduleReconnect("watchdog")
}
if (
sheetStage == DesktopConnectStage.Choosing &&
current.discoveredHosts.isEmpty() &&
- !current.discoveringHosts
+ !current.discoveringHosts &&
+ isLanTransportAvailable()
) {
discoverHosts()
}
@@ -457,29 +700,92 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
fun discoverHosts() {
+ if (!isLanTransportAvailable()) {
+ _state.update { current ->
+ val deduped = if (rawAccountDesktops.isNotEmpty() || current.accountDesktops.isNotEmpty()) {
+ filterAndDeduplicateAccountDesktops(
+ source = rawAccountDesktops.ifEmpty { current.accountDesktops },
+ hosts = emptyList(),
+ profileList = current.profiles,
+ )
+ } else {
+ current.accountDesktops
+ }
+ current.copy(
+ discoveredHosts = emptyList(),
+ discoveringHosts = false,
+ accountDesktops = deduped,
+ )
+ }
+ return
+ }
if (_state.value.discoveringHosts) return
+ val emulator = isEmulator()
viewModelScope.launch {
_state.update { it.copy(discoveringHosts = true) }
val found = withContext(Dispatchers.IO) {
- runCatching { PairingClient.discoverLanHosts() }.getOrDefault(emptyList())
+ runCatching { PairingClient.discoverLanHosts(includeEmulatorLoopback = emulator) }.getOrDefault(emptyList())
+ }
+ _state.update { current ->
+ val deduped = if (rawAccountDesktops.isNotEmpty() || current.accountDesktops.isNotEmpty()) {
+ filterAndDeduplicateAccountDesktops(
+ source = rawAccountDesktops.ifEmpty { current.accountDesktops },
+ hosts = found,
+ profileList = current.profiles,
+ )
+ } else {
+ current.accountDesktops
+ }
+ val nextSheet = current.desktopConnect?.let { sheet ->
+ if (sheet.selectedHostId != null && deduped.none { it.hostId == sheet.selectedHostId }) {
+ sheet.copy(selectedHostId = deduped.firstOrNull()?.hostId)
+ } else {
+ sheet
+ }
+ }
+ current.copy(
+ discoveredHosts = found,
+ discoveringHosts = false,
+ accountDesktops = deduped,
+ desktopConnect = nextSheet,
+ )
}
- _state.update { it.copy(discoveredHosts = found, discoveringHosts = false) }
}
}
- /** Opens the「发现你的电脑」popup and refreshes the account's desktops and the LAN scan. */
+ /** Opens the「连接你的电脑」popup and refreshes the account's desktops and the LAN scan. */
fun openDesktopConnect() {
- if (!_state.value.accountSignedIn) return
connectPollJob?.cancel()
- _state.update { it.copy(desktopConnect = DesktopConnectSheet()) }
- refreshAccount()
+ val signedIn = _state.value.accountSignedIn
+ val initialStage = if (signedIn && _state.value.accountDesktops.isEmpty()) {
+ DesktopConnectStage.Syncing
+ } else {
+ DesktopConnectStage.Choosing
+ }
+ val initialSelected = _state.value.accountDesktops.firstOrNull()?.hostId
+ _state.update {
+ it.copy(
+ desktopConnect = DesktopConnectSheet(stage = initialStage, selectedHostId = initialSelected),
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
+ )
+ }
+ if (signedIn) {
+ refreshAccount()
+ }
discoverHosts()
}
fun dismissDesktopConnect() {
connectPollJob?.cancel()
connectPollJob = null
- _state.update { it.copy(desktopConnect = null) }
+ _state.update {
+ it.copy(
+ desktopConnect = null,
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
+ )
+ }
}
fun selectAccountDesktop(hostId: String) {
@@ -488,76 +794,389 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
+ fun removeAccountDesktop(desktop: AccountDesktop) {
+ val rawId = AccountDesktops.rawHostId(desktop.hostId)
+ val normalizedId = rawId.lowercase(java.util.Locale.ROOT)
+ removedAccountHostIds.add(normalizedId)
+ rawAccountDesktops = rawAccountDesktops.filterNot {
+ AccountDesktops.rawHostId(it.hostId).equals(rawId, ignoreCase = true)
+ }
+ _state.update { current ->
+ val remaining = current.accountDesktops.filterNot {
+ AccountDesktops.rawHostId(it.hostId).equals(rawId, ignoreCase = true)
+ }
+ val nextSheet = current.desktopConnect?.let { sheet ->
+ val nextSelected = if (sheet.selectedHostId == null || remaining.none { it.hostId == sheet.selectedHostId }) {
+ remaining.firstOrNull()?.hostId
+ } else {
+ sheet.selectedHostId
+ }
+ sheet.copy(selectedHostId = nextSelected)
+ }
+ current.copy(
+ accountDesktops = remaining,
+ desktopConnect = nextSheet,
+ )
+ }
+ viewModelScope.launch {
+ accountRepo.deleteHostConfig(rawId)
+ }
+ }
+
fun retryDesktopConnect() {
val stage = _state.value.desktopConnect?.stage as? DesktopConnectStage.Failed ?: return
- val route = stage.route
- if (route == null) openDesktopConnect() else connectAccountDesktop(route)
+ val target = stage.retryTarget
+ if (target == null) openDesktopConnect() else connectDesktopTarget(target)
}
/** LAN origin of an account desktop when the current Wi-Fi scan found it. */
fun lanOriginFor(desktop: AccountDesktop): String? =
- _state.value.discoveredHosts.firstOrNull { it.hostId == desktop.hostId }?.origin
+ _state.value.discoveredHosts.firstOrNull {
+ !it.isCloudService && AccountDesktops.rawHostId(it.hostId.orEmpty()).equals(desktop.hostId, ignoreCase = true)
+ }?.origin
- fun connectAccountDesktop(route: DesktopConnectRoute, replaceExistingMobile: Boolean = false) {
+ fun connectSelectedAccountDesktop() {
val current = _state.value
- val sheet = current.desktopConnect ?: return
- val desktop = current.accountDesktops.firstOrNull { it.hostId == sheet.selectedHostId } ?: return
- val originUrl = when (route) {
- DesktopConnectRoute.Lan -> lanOriginFor(desktop) ?: return
- DesktopConnectRoute.Cloud -> AccountDesktops.tenantOrigin(
- AccountDesktops.relayBase(current.accountOverview?.assignedRelayServer, PairingClient.DEFAULT_OFFICIAL_RELAY_BASE),
- desktop.hostId,
- )
+ val hostId = current.desktopConnect?.selectedHostId ?: current.accountDesktops.firstOrNull()?.hostId
+ val desktop = current.accountDesktops.firstOrNull { it.hostId == hostId } ?: current.accountDesktops.firstOrNull() ?: return
+ connectDesktopTarget(DesktopConnectTarget.Account(desktop))
+ }
+
+ fun connectLanHostInSheet(host: DiscoveredLanHost) {
+ connectDesktopTarget(DesktopConnectTarget.Lan(host))
+ }
+
+ fun connectDesktopTarget(
+ target: DesktopConnectTarget,
+ replaceExistingMobile: Boolean = false,
+ silentUntilNeeded: Boolean = false,
+ ) {
+ fun setStage(stage: DesktopConnectStage) {
+ _state.update { current ->
+ val baseSheet = current.desktopConnect ?: DesktopConnectSheet(
+ selectedHostId = (target as? DesktopConnectTarget.Account)?.desktop?.hostId
+ ?: current.accountDesktops.firstOrNull()?.hostId,
+ )
+ current.copy(
+ desktopConnect = baseSheet.copy(stage = stage),
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
+ )
+ }
}
- val origin = runCatching { HostOrigin.parse(originUrl) }.getOrNull() ?: return
- if (route == DesktopConnectRoute.Cloud) PairingClient.rememberRelayBase(origin.value)
- val reachabilityKind = if (route == DesktopConnectRoute.Lan) "lan" else "published"
- fun setStage(stage: DesktopConnectStage) =
- _state.update { it.copy(desktopConnect = it.desktopConnect?.copy(stage = stage)) }
connectPollJob?.cancel()
connectPollJob = viewModelScope.launch {
- setStage(DesktopConnectStage.Connecting(route))
- val saved = current.accountSavedHosts.firstOrNull {
- AccountDesktops.rawHostId(it.hostId) == desktop.hostId && it.accessToken.isNotBlank()
- }
- if (saved != null) {
- val existing = current.profiles.firstOrNull { AccountDesktops.rawHostId(it.hostId) == desktop.hostId }
- val hostId = existing?.hostId ?: desktop.hostId
- credentials.put(hostId, saved.accessToken)
- val base = existing ?: HostProfile(
- hostId = hostId,
- name = desktop.hostName,
- deviceId = saved.deviceId.ifBlank { saved.profileId },
- reachability = emptyList(),
- lastSuccessOrigin = null,
- lastSyncAt = System.currentTimeMillis(),
- )
- val profile = base.copy(
- reachability = (listOf(StoredReachability(origin.value, reachabilityKind)) + base.reachability)
- .distinctBy { it.origin },
+ if (silentUntilNeeded) {
+ _state.update {
+ it.copy(
+ isAutoConnectingInBackground = true,
+ autoConnectingHostName = target.displayName,
+ )
+ }
+ } else {
+ setStage(DesktopConnectStage.Connecting(target))
+ }
+
+ val candidates = mutableListOf>()
+ when (target) {
+ is DesktopConnectTarget.Account -> {
+ val desktop = target.desktop
+ if (isLanTransportAvailable()) {
+ var lanUrl = lanOriginFor(desktop)
+ if (lanUrl == null) {
+ val emulator = isEmulator()
+ val scanned = withContext(Dispatchers.IO) {
+ runCatching { PairingClient.discoverLanHosts(includeEmulatorLoopback = emulator) }
+ .getOrDefault(emptyList())
+ }
+ if (scanned.isNotEmpty()) {
+ _state.update { current ->
+ val deduped = if (rawAccountDesktops.isNotEmpty() || current.accountDesktops.isNotEmpty()) {
+ filterAndDeduplicateAccountDesktops(
+ source = rawAccountDesktops.ifEmpty { current.accountDesktops },
+ hosts = scanned,
+ profileList = current.profiles,
+ )
+ } else {
+ current.accountDesktops
+ }
+ current.copy(discoveredHosts = scanned, accountDesktops = deduped)
+ }
+ lanUrl = scanned.firstOrNull {
+ !it.isCloudService && AccountDesktops.rawHostId(it.hostId.orEmpty()).equals(desktop.hostId, ignoreCase = true)
+ }?.origin
+ }
+ }
+ lanUrl?.let { url ->
+ runCatching { HostOrigin.parse(url) }.getOrNull()?.let { candidates += it to "lan" }
+ }
+ }
+ val current = _state.value
+ val canUseCloud = current.accountOverview?.canUseCloudRelay ?: true
+ if (canUseCloud) {
+ val cloudUrl = AccountDesktops.tenantOrigin(
+ AccountDesktops.relayBase(
+ current.accountOverview?.assignedRelayServer,
+ PairingClient.DEFAULT_OFFICIAL_RELAY_BASE,
+ ),
+ desktop.hostId,
+ )
+ runCatching { HostOrigin.parse(cloudUrl) }.getOrNull()?.let { origin ->
+ PairingClient.rememberRelayBase(origin.value)
+ candidates += origin to "published"
+ }
+ }
+ }
+ is DesktopConnectTarget.Lan -> {
+ val kind = if (target.host.isCloudService) "published" else "lan"
+ runCatching { HostOrigin.parse(target.host.origin) }.getOrNull()?.let {
+ candidates += it to kind
+ }
+ }
+ }
+
+ if (candidates.isEmpty()) {
+ if (silentUntilNeeded) {
+ _state.update { it.copy(isAutoConnectingInBackground = false, autoConnectingHostName = null) }
+ } else {
+ setStage(DesktopConnectStage.Failed("当前不在同一 Wi-Fi,且账号未开通云服务", target))
+ }
+ return@launch
+ }
+
+ // 1. Try existing synced/local credential fast-path if available
+ if (target is DesktopConnectTarget.Account) {
+ val desktop = target.desktop
+ val current = _state.value
+ val saved = current.accountSavedHosts.firstOrNull {
+ AccountDesktops.rawHostId(it.hostId) == desktop.hostId && it.accessToken.isNotBlank()
+ }
+ if (saved != null) {
+ val existing = current.profiles.firstOrNull { AccountDesktops.rawHostId(it.hostId) == desktop.hostId }
+ val hostId = existing?.hostId ?: desktop.hostId
+ credentials.put(hostId, saved.accessToken)
+ val primary = candidates.first()
+ val base = existing ?: HostProfile(
+ hostId = hostId,
+ name = desktop.displayName,
+ deviceId = saved.deviceId.ifBlank { saved.profileId },
+ reachability = emptyList(),
+ lastSuccessOrigin = null,
+ lastSyncAt = System.currentTimeMillis(),
+ )
+ val mergedReach = (candidates.map { StoredReachability(it.first.value, it.second) } + base.reachability)
+ .distinctBy { it.origin }
+ val profile = base.copy(
+ reachability = mergedReach,
+ lastSuccessOrigin = primary.first.value,
+ )
+ upsertProfile(profile, selected = true)
+ connect(profile, allowCloudSwitch = candidates.any { it.second == "published" })
+ val revoked = _state.value.profiles.none { it.hostId == hostId }
+ if (!revoked) {
+ if (_state.value.connection == ConnectionState.Online) {
+ _state.update {
+ it.copy(
+ desktopConnect = null,
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
+ )
+ }
+ return@launch
+ }
+ if (silentUntilNeeded) {
+ _state.update { it.copy(isAutoConnectingInBackground = false, autoConnectingHostName = null) }
+ } else {
+ setStage(DesktopConnectStage.Failed(_state.value.connectionFailureReason ?: "电脑离线", target))
+ }
+ return@launch
+ }
+ _state.update {
+ it.copy(
+ error = null,
+ connectionFailureReason = null,
+ accountSavedHosts = it.accountSavedHosts - saved,
+ )
+ }
+ }
+ }
+
+ // 2. Request connect (with optional same-account JWT for zero-click auto-approval)
+ val accountToken = accountRepo.getToken()
+ var lastFailure: Throwable? = null
+ var chosenOrigin: HostOrigin? = null
+ var chosenKind = "lan"
+ var requestedResult: dev.vibex.companion.DeviceConnectRequestResult? = null
+
+ for ((origin, kind) in candidates) {
+ val attempt = withContext(Dispatchers.IO) {
+ runCatching {
+ pairingClient.requestConnect(
+ origin = origin,
+ deviceName = Build.MODEL.ifBlank { "Android Companion" },
+ replaceExistingMobile = replaceExistingMobile,
+ accountToken = accountToken,
+ )
+ }
+ }
+ val ok = attempt.getOrNull()
+ if (ok != null) {
+ chosenOrigin = origin
+ chosenKind = kind
+ requestedResult = ok
+ break
+ }
+ val err = attempt.exceptionOrNull()
+ if (err is MobileDeviceConflictException) {
+ _state.update { it.copy(isAutoConnectingInBackground = false, autoConnectingHostName = null) }
+ pendingConflictRetryAction = {
+ connectDesktopTarget(target, replaceExistingMobile = true, silentUntilNeeded = false)
+ }
+ _state.update { it.copy(pendingConflictDeviceName = err.existingDeviceName) }
+ return@launch
+ }
+ if (err is AccountLinkException && err.failure == AccountLinkFailure.AccountTokenInvalid) {
+ _state.update { it.copy(isAutoConnectingInBackground = false, autoConnectingHostName = null) }
+ signOutAccount()
+ return@launch
+ }
+ // If account verification mismatched/signed out on LAN, retry without accountToken so manual 4-digit SAS works
+ if (err is AccountLinkException && (
+ err.failure == AccountLinkFailure.AccountMismatch ||
+ err.failure == AccountLinkFailure.HostAccountSignedOut ||
+ err.failure == AccountLinkFailure.VerificationUnavailable
+ )
+ ) {
+ val unauthAttempt = withContext(Dispatchers.IO) {
+ runCatching {
+ pairingClient.requestConnect(
+ origin = origin,
+ deviceName = Build.MODEL.ifBlank { "Android Companion" },
+ replaceExistingMobile = replaceExistingMobile,
+ accountToken = null,
+ )
+ }
+ }
+ val unauthOk = unauthAttempt.getOrNull()
+ if (unauthOk != null) {
+ chosenOrigin = origin
+ chosenKind = kind
+ requestedResult = unauthOk
+ break
+ }
+ }
+ lastFailure = err
+ }
+
+ val origin = chosenOrigin
+ val requested = requestedResult
+ if (origin == null || requested == null) {
+ if (silentUntilNeeded) {
+ _state.update { it.copy(isAutoConnectingInBackground = false, autoConnectingHostName = null) }
+ } else {
+ val msg = lastFailure?.let(::desktopConnectErrorMessage) ?: "无法连接到电脑,请确认电脑端在线"
+ setStage(DesktopConnectStage.Failed(msg, target))
+ }
+ return@launch
+ }
+
+ suspend fun adoptApprovedConnection(
+ cred: dev.vibex.remote.v1.DeviceCredential,
+ rawHostId: String,
+ rawHostName: String?,
+ sasCode: String,
+ ) {
+ val resolvedHostId = rawHostId.ifBlank { target.hostId.orEmpty() }.ifBlank { "host:${origin.value.hashCode()}" }
+ credentials.put(resolvedHostId, cred.access_token)
+ val allReach = (
+ listOf(StoredReachability(origin.value, chosenKind)) +
+ candidates.map { StoredReachability(it.first.value, it.second) }
+ ).distinctBy { it.origin }
+ val profile = HostProfile(
+ hostId = resolvedHostId,
+ name = rawHostName?.takeUnless { AccountDesktops.isGenericHostName(it) } ?: target.displayName,
+ deviceId = cred.device_id,
+ reachability = allReach,
lastSuccessOrigin = origin.value,
+ lastSyncAt = System.currentTimeMillis(),
+ selectedProjectId = null,
)
upsertProfile(profile, selected = true)
- connect(profile, allowCloudSwitch = route == DesktopConnectRoute.Cloud)
- val revoked = _state.value.profiles.none { it.hostId == hostId }
- if (!revoked) {
- if (_state.value.connection != ConnectionState.Online) {
- setStage(DesktopConnectStage.Failed(_state.value.connectionFailureReason ?: "电脑离线", route))
+ setAccountLoginRequested(false)
+ _state.update {
+ it.copy(
+ desktopConnect = null,
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
+ lanSasState = null,
+ route = if (it.route == Route.ManualPair) Route.Conversations else it.route,
+ )
+ }
+ presentConnectedSasNotice(profile.name, sasCode)
+ SystemNotifier.notifyStatus(getApplication(), "已连接电脑", "${profile.name} · 连接码 $sasCode")
+ connect(profile, allowCloudSwitch = candidates.any { it.second == "published" })
+ if (_state.value.connection != ConnectionState.Online && !silentUntilNeeded) {
+ setStage(DesktopConnectStage.Failed(_state.value.connectionFailureReason ?: "电脑离线", target))
+ }
+ }
+
+ // Same-account auto-approved in 0ms!
+ if (requested.status == "approved" && requested.credential != null) {
+ adoptApprovedConnection(
+ cred = requested.credential!!,
+ rawHostId = requested.hostId,
+ rawHostName = requested.hostName,
+ sasCode = requested.sasCode,
+ )
+ return@launch
+ }
+
+ // Manual approval required on desktop: show 4-digit SAS code
+ val displayHost = requested.hostName?.takeUnless { AccountDesktops.isGenericHostName(it) } ?: target.displayName
+ setStage(DesktopConnectStage.AwaitingApproval(target, requested.sasCode, displayHost))
+
+ while (isActive) {
+ delay(1_200)
+ val poll = withContext(Dispatchers.IO) {
+ runCatching { pairingClient.pollConnect(origin, requested.requestId) }.getOrNull()
+ } ?: continue
+ when (poll.status) {
+ "approved" -> {
+ val cred = poll.credential ?: continue
+ adoptApprovedConnection(
+ cred = cred,
+ rawHostId = poll.hostId,
+ rawHostName = poll.hostName ?: requested.hostName,
+ sasCode = poll.sasCode.ifBlank { requested.sasCode },
+ )
+ return@launch
+ }
+ "rejected" -> {
+ setStage(DesktopConnectStage.Failed(DESKTOP_APPROVAL_REJECTED, target))
+ return@launch
+ }
+ "expired" -> {
+ setStage(DesktopConnectStage.Failed(DESKTOP_APPROVAL_EXPIRED, target))
+ return@launch
}
- return@launch
}
- // The synced credential was revoked on the desktop; ask it for a fresh one instead.
- _state.update { it.copy(error = null, connectionFailureReason = null, accountSavedHosts = it.accountSavedHosts - saved) }
}
+ }
+ }
- val accountToken = accountRepo.getToken()
- if (accountToken == null) {
- signOutAccount()
+ fun connectLanHostInline(host: DiscoveredLanHost, replaceExistingMobile: Boolean = false) {
+ lanSasPollJob?.cancel()
+ lanSasPollJob = viewModelScope.launch {
+ _state.update { it.copy(lanSasState = LanSasInlineState.Connecting(host), error = null) }
+ val origin = runCatching { HostOrigin.parse(host.origin) }.getOrNull()
+ if (origin == null) {
+ _state.update { it.copy(lanSasState = null, error = "无效的电脑地址") }
return@launch
}
+ val accountToken = accountRepo.getToken()
val requested = withContext(Dispatchers.IO) {
- runCatching {
+ val primary = runCatching {
pairingClient.requestConnect(
origin = origin,
deviceName = Build.MODEL.ifBlank { "Android Companion" },
@@ -565,53 +1184,95 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
accountToken = accountToken,
)
}
- }.getOrElse { err ->
- when {
- err is MobileDeviceConflictException -> {
- pendingConflictRetryAction = { connectAccountDesktop(route, replaceExistingMobile = true) }
- _state.update { it.copy(pendingConflictDeviceName = err.existingDeviceName) }
+ if (primary.isSuccess) {
+ primary
+ } else {
+ val err = primary.exceptionOrNull()
+ if (accountToken != null && err is AccountLinkException) {
+ runCatching {
+ pairingClient.requestConnect(
+ origin = origin,
+ deviceName = Build.MODEL.ifBlank { "Android Companion" },
+ replaceExistingMobile = replaceExistingMobile,
+ accountToken = null,
+ )
+ }
+ } else {
+ primary
}
- err is AccountLinkException && err.failure == AccountLinkFailure.AccountTokenInvalid -> signOutAccount()
- else -> setStage(DesktopConnectStage.Failed(desktopConnectErrorMessage(err), route))
}
+ }.getOrElse { err ->
+ _state.update { it.copy(lanSasState = null) }
+ if (err is MobileDeviceConflictException) {
+ pendingConflictRetryAction = { connectLanHostInline(host, replaceExistingMobile = true) }
+ _state.update { it.copy(pendingConflictDeviceName = err.existingDeviceName) }
+ } else {
+ fail(err)
+ }
+ return@launch
+ }
+
+ suspend fun finishInlineApproved(
+ cred: dev.vibex.remote.v1.DeviceCredential,
+ rawHostId: String,
+ rawHostName: String?,
+ sasCode: String,
+ ) {
+ val resolvedHostId = rawHostId.ifBlank { host.hostId.orEmpty() }.ifBlank { "host:${origin.value.hashCode()}" }
+ credentials.put(resolvedHostId, cred.access_token)
+ val kind = if (host.isCloudService) "published" else "lan"
+ val profile = HostProfile(
+ hostId = resolvedHostId,
+ name = rawHostName?.ifBlank { null } ?: host.displayName,
+ deviceId = cred.device_id,
+ reachability = listOf(StoredReachability(origin.value, kind)),
+ lastSuccessOrigin = origin.value,
+ lastSyncAt = System.currentTimeMillis(),
+ selectedProjectId = null,
+ )
+ upsertProfile(profile, selected = true)
+ setAccountLoginRequested(false)
+ _state.update { it.copy(lanSasState = null, route = Route.Conversations, error = null) }
+ presentConnectedSasNotice(profile.name, sasCode)
+ connect(profile, allowCloudSwitch = host.isCloudService)
+ }
+
+ if (requested.status == "approved" && requested.credential != null) {
+ finishInlineApproved(
+ cred = requested.credential!!,
+ rawHostId = requested.hostId,
+ rawHostName = requested.hostName,
+ sasCode = requested.sasCode,
+ )
return@launch
}
- setStage(DesktopConnectStage.AwaitingApproval(route, requested.sasCode))
+ val hostLabel = requested.hostName?.ifBlank { null } ?: host.displayName
+ _state.update {
+ it.copy(lanSasState = LanSasInlineState.AwaitingApproval(host, requested.sasCode, hostLabel))
+ }
while (isActive) {
- delay(1_500)
+ delay(1_200)
val poll = withContext(Dispatchers.IO) {
runCatching { pairingClient.pollConnect(origin, requested.requestId) }.getOrNull()
} ?: continue
when (poll.status) {
"approved" -> {
val cred = poll.credential ?: continue
- val hostId = poll.hostId.ifBlank { desktop.hostId }
- credentials.put(hostId, cred.access_token)
- val profile = HostProfile(
- hostId = hostId,
- name = (poll.hostName ?: requested.hostName)?.ifBlank { null } ?: desktop.hostName,
- deviceId = cred.device_id,
- reachability = listOf(StoredReachability(origin.value, reachabilityKind)),
- lastSuccessOrigin = origin.value,
- lastSyncAt = System.currentTimeMillis(),
- selectedProjectId = null,
+ finishInlineApproved(
+ cred = cred,
+ rawHostId = poll.hostId,
+ rawHostName = poll.hostName ?: requested.hostName,
+ sasCode = poll.sasCode.ifBlank { requested.sasCode },
)
- upsertProfile(profile, selected = true)
- _state.update { it.copy(route = Route.Conversations) }
- SystemNotifier.notifyStatus(getApplication(), "已连接电脑", profile.name)
- connect(profile, allowCloudSwitch = route == DesktopConnectRoute.Cloud)
- if (_state.value.connection != ConnectionState.Online) {
- setStage(DesktopConnectStage.Failed(_state.value.connectionFailureReason ?: "电脑离线", route))
- }
return@launch
}
"rejected" -> {
- setStage(DesktopConnectStage.Failed(DESKTOP_APPROVAL_REJECTED, route))
+ _state.update { it.copy(lanSasState = null, error = DESKTOP_APPROVAL_REJECTED) }
return@launch
}
"expired" -> {
- setStage(DesktopConnectStage.Failed(DESKTOP_APPROVAL_EXPIRED, route))
+ _state.update { it.copy(lanSasState = null, error = DESKTOP_APPROVAL_EXPIRED) }
return@launch
}
}
@@ -619,6 +1280,12 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
+ fun cancelLanHostInline() {
+ lanSasPollJob?.cancel()
+ lanSasPollJob = null
+ _state.update { it.copy(lanSasState = null) }
+ }
+
fun selectProject(projectId: String) {
val profile = selectedProfile()?.copy(selectedProjectId = projectId) ?: return
@@ -676,6 +1343,57 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
persist { it.copy(appearance = appearance) }
}
+ fun setLanguage(language: AppLanguage) {
+ _state.update { it.copy(language = language) }
+ persist { it.copy(language = language) }
+ }
+
+ fun setConfirmHighRiskApproval(enabled: Boolean) {
+ _state.update { it.copy(confirmHighRiskApproval = enabled) }
+ persist { it.copy(confirmHighRiskApproval = enabled) }
+ }
+
+ fun setMuteForegroundNotifications(enabled: Boolean) {
+ _state.update { it.copy(muteForegroundNotifications = enabled) }
+ persist { it.copy(muteForegroundNotifications = enabled) }
+ }
+
+ fun setCustomRelayOrigin(raw: String) {
+ val normalized = normalizeCustomRelayOrigin(raw)
+ _state.update { it.copy(customRelayOrigin = normalized) }
+ persist { it.copy(customRelayOrigin = normalized) }
+ }
+
+ private fun normalizeCustomRelayOrigin(raw: String): String {
+ val trimmed = raw.trim().trimEnd('/')
+ if (trimmed.isEmpty()) return ""
+ return if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
+ trimmed
+ } else {
+ "https://$trimmed"
+ }
+ }
+
+ private fun notifyAlertIfAllowed(
+ notificationKey: String,
+ title: String,
+ body: String,
+ conversationId: String? = null,
+ actions: List = emptyList(),
+ ) {
+ if (isAppInForeground && _state.value.muteForegroundNotifications) {
+ return
+ }
+ SystemNotifier.notifyAlert(
+ context = getApplication(),
+ notificationKey = notificationKey,
+ title = title,
+ body = body,
+ conversationId = conversationId,
+ actions = actions,
+ )
+ }
+
fun setAccent(accent: AccentChoice) {
_state.update { it.copy(accent = accent) }
persist { it.copy(accent = accent) }
@@ -709,16 +1427,28 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
- fun pairFromRaw(raw: String, replaceExistingMobile: Boolean = false) {
+ fun pairFromRaw(
+ raw: String,
+ replaceExistingMobile: Boolean = false,
+ nodePreference: CloudNodePreference? = null,
+ ) {
+ val hasCustomNode = _state.value.customRelayOrigin.isNotBlank()
+ val canChooseCloud = hasCustomNode && _state.value.accountSignedIn
+ if (nodePreference == null && canChooseCloud) {
+ _state.update { it.copy(pendingQrNodeChoiceRaw = raw) }
+ return
+ }
+ val effectivePreference = nodePreference ?: CloudNodePreference.Auto
viewModelScope.launch {
- _state.update { it.copy(pairing = true, error = null) }
+ _state.update { it.copy(pairing = true, error = null, pendingQrNodeChoiceRaw = null) }
runCatching {
- val invitation = PairingInvitationParser.parse(raw)
+ val parsed = PairingInvitationParser.parse(raw)
+ val invitation = applyNodePreference(parsed, effectivePreference)
redeemOrMerge(invitation, replaceExistingMobile = replaceExistingMobile)
}.onFailure { err ->
if (err is MobileDeviceConflictException) {
pendingConflictRetryAction = {
- pairFromRaw(raw, replaceExistingMobile = true)
+ pairFromRaw(raw, replaceExistingMobile = true, nodePreference = effectivePreference)
}
_state.update {
it.copy(
@@ -735,32 +1465,70 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
+ fun confirmPendingNodeChoice(preference: CloudNodePreference) {
+ val raw = _state.value.pendingQrNodeChoiceRaw ?: return
+ _state.update { it.copy(pendingQrNodeChoiceRaw = null) }
+ pairFromRaw(raw, replaceExistingMobile = false, nodePreference = preference)
+ }
+
+ fun cancelPendingNodeChoice() {
+ _state.update { it.copy(pendingQrNodeChoiceRaw = null) }
+ }
+
+ private fun applyNodePreference(
+ invitation: dev.vibex.companion.PairingInvitation,
+ preference: CloudNodePreference,
+ ): dev.vibex.companion.PairingInvitation {
+ val customBase = normalizeCustomRelayOrigin(_state.value.customRelayOrigin)
+ if (preference != CloudNodePreference.CustomNode || customBase.isEmpty()) {
+ return invitation
+ }
+ val customUrl = when {
+ customBase.contains("/t/") -> customBase
+ !invitation.hostId.isNullOrBlank() -> "$customBase/t/${invitation.hostId}"
+ else -> customBase
+ }
+ val customTarget = runCatching {
+ ReachabilityTarget(HostOrigin.parse(customUrl), "published")
+ }.getOrNull() ?: return invitation
+ val filtered = invitation.reachability.filterNot {
+ it.origin.value.contains("dimo-ai.com") || it.origin.value.contains("vibex.xforever.xin")
+ }
+ return invitation.copy(
+ reachability = listOf(customTarget) + filtered.filterNot { it.origin.value == customTarget.origin.value },
+ )
+ }
+
fun pairManual(origin: String, token: String, replaceExistingMobile: Boolean = false) {
viewModelScope.launch {
_state.update { it.copy(pairing = true, error = null) }
runCatching {
val rawToken = token.trim()
- if (rawToken.startsWith("vibex-pairing:") || rawToken.startsWith("{")) {
+ if (rawToken.startsWith("vibex-pairing:") || rawToken.startsWith("dimo-pairing:") || rawToken.startsWith("{")) {
redeemOrMerge(
PairingInvitationParser.parse(rawToken),
replaceExistingMobile = replaceExistingMobile,
)
} else {
val candidates = LinkedHashSet()
- origin.trim().takeIf { it.isNotEmpty() }?.let { candidates.add(it) }
- val knownOrigins = _state.value.profiles.mapNotNull { it.lastSuccessOrigin }
+ origin.trim().takeIf { it.isNotEmpty() }?.let { candidates.add(PairingClient.migrateLegacyRelayOrigin(it)) }
+ val knownOrigins = _state.value.profiles.mapNotNull { it.lastSuccessOrigin }.map(PairingClient::migrateLegacyRelayOrigin)
val codeRendezvous = withContext(Dispatchers.IO) {
runCatching {
PairingClient.resolvePairingCodeRendezvous(rawToken, knownOrigins = knownOrigins)
}.getOrDefault(emptyList())
}
- candidates.addAll(codeRendezvous)
- _state.value.discoveredHosts.forEach { candidates.add(it.origin) }
- _state.value.activeOrigin?.takeIf { it.isNotBlank() }?.let { candidates.add(it) }
+ candidates.addAll(codeRendezvous.map(PairingClient::migrateLegacyRelayOrigin))
+ val lanAvailable = isLanTransportAvailable()
+ if (lanAvailable) {
+ _state.value.discoveredHosts.forEach { candidates.add(it.origin) }
+ }
+ _state.value.activeOrigin?.takeIf { it.isNotBlank() }?.let { candidates.add(PairingClient.migrateLegacyRelayOrigin(it)) }
knownOrigins.forEach { candidates.add(it) }
- if (candidates.isEmpty()) {
+ if (candidates.isEmpty() && lanAvailable) {
+ val emulator = isEmulator()
val autoFound = withContext(Dispatchers.IO) {
- runCatching { PairingClient.discoverLanHosts() }.getOrDefault(emptyList())
+ runCatching { PairingClient.discoverLanHosts(includeEmulatorLoopback = emulator) }.getOrDefault(emptyList())
}
autoFound.forEach { candidates.add(it.origin) }
}
@@ -816,10 +1584,11 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
val remaining = _state.value.profiles.filterNot { it.hostId == profile.hostId }
persist { it.copy(selectedHostId = remaining.firstOrNull()?.hostId, profiles = remaining) }
if (_state.value.accountSignedIn) {
+ lastPushedSavedHostsSignature = null
runCatching {
accountRepo.deleteSavedHost(
profileId = profile.deviceId.ifBlank { profile.hostId },
- hostId = profile.hostId,
+ hostId = AccountDesktops.rawHostId(profile.hostId).ifBlank { profile.hostId },
origin = origin.orEmpty(),
)
}
@@ -841,9 +1610,8 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
fun openNewChatLanding() {
- userRequestedNewChatLanding = true
timelinePollJob?.cancel()
- _state.update { it.copy(route = Route.Conversations, timeline = null) }
+ _state.update { it.copy(route = Route.NewThread, timeline = null) }
}
private var activeInlineConversationId: String? = null
@@ -853,8 +1621,6 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
fun openConversation(id: String) {
activeInlineConversationId = null
- userRequestedNewChatLanding = false
- hasAutoOpenedInitialConversation = true
_state.update { it.copy(route = Route.Timeline(id), timeline = sessions[id]?.snapshot()) }
viewModelScope.launch { attachConversation(id) }
startTimelinePoller(id)
@@ -882,7 +1648,9 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
delay(800)
while (isActive && currentObservedConversationId() == id) {
val session = sessions[id]
- val fast = session?.inFlightTurnId != null || System.currentTimeMillis() < boostPollingUntil
+ val fast = session?.inFlightTurnId != null ||
+ (session?.optimisticThinkingUntilMs ?: 0L) > System.currentTimeMillis() ||
+ System.currentTimeMillis() < boostPollingUntil
runCatching { syncConversationTimeline(id, forceRows = fast) }
if (fast) {
delay(900)
@@ -929,23 +1697,13 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
resolvedWorkspaceId,
resolvedAgentId,
title.ifBlank { null },
- prompt.ifBlank { null },
+ null,
)
}
locallyCreatedConversationIds.add(created.id)
knownConversationIds.add(created.id)
+ unmarkManuallyCompleted(created.id)
val agent = _state.value.catalog?.agents?.find { it.id == resolvedAgentId }
- withContext(Dispatchers.IO) {
- runCatching { api.ensureSessionControls(origin, token, created.id) }
- if (!modeId.isNullOrBlank()) {
- runCatching { api.setSessionMode(origin, token, created.id, modeId) }
- }
- config.forEach { (key, value) ->
- if (key.isNotBlank() && value.isNotBlank()) {
- runCatching { api.setSessionConfigOption(origin, token, created.id, key, value) }
- }
- }
- }
val boundAgent = created.agentId.ifBlank { resolvedAgentId }
val boundWorkspace = created.workspaceId.ifBlank { resolvedWorkspaceId }
val session = sessions.getOrPut(created.id) {
@@ -968,10 +1726,17 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
options = bound?.sessionConfig.orEmpty(),
selected = config,
)
+ if (prompt.isNotBlank()) {
+ boostPollingUntil = System.currentTimeMillis() + 30_000L
+ synchronized(session) {
+ session.beginOptimisticSend(prompt)
+ }
+ }
val summary = created.copy(
workspaceId = boundWorkspace,
title = title.ifBlank { created.title },
agentId = boundAgent,
+ status = if (prompt.isNotBlank()) "inprogress" else created.status,
)
_state.update { state ->
state.copy(
@@ -979,10 +1744,33 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
)
}
openConversation(created.id)
- if (prompt.isNotBlank()) {
- send(created.id, prompt)
+
+ // Apply mode/config & initial prompt in background without blocking navigation
+ viewModelScope.launch {
+ runCatching {
+ withContext(Dispatchers.IO) {
+ if (!modeId.isNullOrBlank()) {
+ runCatching { api.setSessionMode(origin, token, created.id, modeId) }
+ }
+ config.forEach { (key, value) ->
+ if (key.isNotBlank() && value.isNotBlank()) {
+ runCatching { api.setSessionConfigOption(origin, token, created.id, key, value) }
+ }
+ }
+ if (prompt.isNotBlank()) {
+ api.submitInput(origin, token, created.id, boundAgent, boundWorkspace, prompt)
+ }
+ }
+ if (prompt.isNotBlank()) {
+ syncConversationTimeline(created.id, forceRows = true)
+ }
+ runCatching { loadConversations(silent = true) }
+ }.onFailure { err ->
+ synchronized(session) { session.clearOptimisticSend() }
+ publishTimeline(session)
+ fail(err)
+ }
}
- viewModelScope.launch { runCatching { loadConversations() } }
}.onFailure { fail(it) }
}
}
@@ -1043,8 +1831,20 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
fun setSessionConfig(conversationId: String, key: String, value: String) {
if (!_state.value.connection.allowsWrites || key.isBlank()) return
sessions[conversationId]?.let { session ->
- val index = session.sessionConfig.indexOfFirst { it.key == key }
- if (index >= 0) session.sessionConfig[index] = session.sessionConfig[index].copy(value = value)
+ synchronized(session) {
+ val index = session.sessionConfig.indexOfFirst { it.key == key }
+ if (index >= 0) {
+ val existing = session.sessionConfig[index]
+ val nextChoices = if (existing.choices.any { it.value == value }) {
+ existing.choices
+ } else {
+ existing.choices + CatalogAgent.makeCustomChoice(value)
+ }
+ session.sessionConfig[index] = existing.copy(value = value, choices = nextChoices)
+ } else {
+ session.sessionConfig += CatalogAgent.makeCustomModelOption(key = key, modelId = value)
+ }
+ }
publishTimeline(session)
}
viewModelScope.launch {
@@ -1104,6 +1904,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
fun send(conversationId: String, text: String) {
if (!_state.value.connection.allowsWrites || text.isBlank()) return
+ unmarkManuallyCompleted(conversationId)
val summary = selectedConversation(conversationId)
val session = sessions.getOrPut(conversationId) {
TimelineSession().also {
@@ -1113,42 +1914,75 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
it.workspaceId = summary?.workspaceId.orEmpty()
}
}
- if (session.agentId.isBlank()) session.agentId = summary?.agentId.orEmpty()
- if (session.workspaceId.isBlank()) session.workspaceId = summary?.workspaceId.orEmpty()
+ val agentId = synchronized(session) {
+ if (session.agentId.isBlank()) session.agentId = summary?.agentId.orEmpty()
+ if (session.workspaceId.isBlank()) session.workspaceId = summary?.workspaceId.orEmpty()
+ val resolvedAg = session.agentId.ifBlank { summary?.agentId.orEmpty() }
+ .ifBlank {
+ _state.value.catalog?.agents?.firstOrNull { it.usable }?.id
+ ?: _state.value.catalog?.agents?.firstOrNull()?.id
+ ?: "claude_code"
+ }
+ session.agentId = resolvedAg
+ session.beginOptimisticSend(text)
+ resolvedAg
+ }
+ boostPollingUntil = System.currentTimeMillis() + 30_000L
+ publishTimeline(session)
+
viewModelScope.launch {
runCatching {
- val agentId = session.agentId.ifBlank { summary?.agentId.orEmpty() }
- .ifBlank {
- _state.value.catalog?.agents?.firstOrNull { it.usable }?.id
- ?: _state.value.catalog?.agents?.firstOrNull()?.id
- ?: "claude_code"
- }
- session.agentId = agentId
- val workspaceId = session.workspaceId.ifBlank { summary?.workspaceId.orEmpty() }
+ val workspaceId = synchronized(session) { session.workspaceId }
+ .ifBlank { summary?.workspaceId.orEmpty() }
.ifBlank { currentCollaborationWorkspaceId() }
if (workspaceId.isBlank()) error("会话还没有工作区")
- session.workspaceId = workspaceId
- boostPollingUntil = System.currentTimeMillis() + 30_000L
+ synchronized(session) { session.workspaceId = workspaceId }
val (origin, token) = live()
- val localId = "local:${System.currentTimeMillis()}"
- if (session.inFlightTurnId == null) session.inFlightTurnId = "local"
- session.rows += dev.vibex.companion.TimelineRow(
- id = localId,
- kind = "user",
- title = "",
- body = text,
- tone = dev.vibex.companion.TimelineTone.Quiet,
- )
- publishTimeline(session)
withContext(Dispatchers.IO) {
api.submitInput(origin, token, conversationId, agentId, workspaceId, text)
}
- syncConversationTimeline(conversationId)
- if (session.rows.any { it.kind == "user" && it.id != localId && it.body == text }) {
- session.rows.removeAll { it.id == localId }
- }
+ syncConversationTimeline(conversationId, forceRows = true)
+ }.onFailure { err ->
+ synchronized(session) { session.clearOptimisticSend() }
publishTimeline(session)
- }.onFailure { fail(it) }
+ fail(err)
+ }
+ }
+ }
+
+ fun markSessionViewed(conversationId: String) {
+ if (!_state.value.connection.allowsWrites || conversationId.isBlank()) return
+ viewModelScope.launch {
+ runCatching {
+ mutateKanbanSessionViewed(conversationId)
+ loadConversations(silent = true)
+ }
+ }
+ }
+
+ fun setManualSessionStatus(sessionId: String, status: KanbanSessionStatus) {
+ if (!_state.value.connection.allowsWrites) return
+ val nextSet = _state.value.manuallyCompletedSessionIds.toMutableSet().apply {
+ if (status == KanbanSessionStatus.Done) add(sessionId) else remove(sessionId)
+ }
+ prefs.edit().putStringSet(PREF_MANUALLY_COMPLETED_SESSIONS, nextSet).apply()
+ _state.update { it.copy(manuallyCompletedSessionIds = nextSet) }
+ viewModelScope.launch {
+ runCatching { mutateKanbanSessionStatus(sessionId, status) }.onFailure { fail(it) }
+ }
+ }
+
+ private fun unmarkManuallyCompleted(sessionId: String) {
+ if (sessionId !in _state.value.manuallyCompletedSessionIds) return
+ val nextSet = _state.value.manuallyCompletedSessionIds - sessionId
+ prefs.edit().putStringSet(PREF_MANUALLY_COMPLETED_SESSIONS, nextSet).apply()
+ _state.update { it.copy(manuallyCompletedSessionIds = nextSet) }
+ }
+
+ fun updateCollabUnreadCount(count: Int) {
+ val safe = count.coerceAtLeast(0)
+ if (_state.value.collabUnreadCount != safe) {
+ _state.update { it.copy(collabUnreadCount = safe) }
}
}
@@ -1497,8 +2331,11 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
val (origin, token) = live()
val catalog = withContext(Dispatchers.IO) { api.catalog(origin, token) }
val selected = _state.value.selectedProjectId
- val stillValid = selected != null && catalog.projects.any { it.id == selected }
- val resolvedProject = if (stillValid) selected else catalog.projects.firstOrNull()?.id
+ val resolvedProject = if (selected == null || catalog.projects.any { it.id == selected }) {
+ selected
+ } else {
+ null
+ }
_state.update {
it.copy(
catalog = catalog,
@@ -1507,15 +2344,29 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
error = null,
)
}
- if (resolvedProject != null) {
- loadConversations()
- }
+ loadConversations()
} catch (error: Throwable) {
_state.update { it.copy(catalogLoading = false) }
throw error
}
}
+ /**
+ * The account relay URL of a desktop signed in to the same account. It lets the phone reach
+ * that desktop off-LAN even when the profile never learned a published origin.
+ */
+ private fun accountTenantOriginFor(hostId: String): String? {
+ val current = _state.value
+ if (!current.accountSignedIn || current.accountOverview?.canUseCloudRelay == false) return null
+ val rawHostId = AccountDesktops.rawHostId(hostId)
+ if (current.accountDesktops.none { it.hostId == rawHostId }) return null
+ val relayBase = AccountDesktops.relayBase(
+ current.accountOverview?.assignedRelayServer,
+ PairingClient.DEFAULT_OFFICIAL_RELAY_BASE,
+ )
+ return AccountDesktops.tenantOrigin(relayBase, rawHostId)
+ }
+
private fun handleForcedOfflineByRevocation(hostId: String? = _state.value.selectedHostId) {
val targetId = hostId ?: selectedProfile()?.hostId
if (!targetId.isNullOrBlank()) {
@@ -1532,12 +2383,12 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
activeOrigin = null,
connection = ConnectionState.Offline,
realtimeRttMs = null,
- connectionFailureReason = "已被其他手机接管下线",
+ connectionFailureReason = REVOKED_FAILURE_REASON,
conversations = emptyList(),
timeline = null,
inbox = emptyList(),
pairing = false,
- error = "当前电脑已切换至其他手机远程连接,本机已强制下线并清除凭据,下次需重新连接",
+ error = REVOKED_NOTICE,
)
}
}
@@ -1560,7 +2411,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
.substringBefore(":")
val profile = HostProfile(
hostId = result.hostId,
- name = "VibeX ($displayHost)",
+ name = "Dimo ($displayHost)",
deviceId = result.session.credential.device_id,
reachability = invitation.reachability.map { StoredReachability(it.origin.value, it.kind) }
.ifEmpty { listOf(StoredReachability(result.session.origin.value, "paired")) },
@@ -1582,238 +2433,301 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
val kind = profile.reachability.find { it.origin == originUrl }?.kind?.lowercase()
if (kind == "webrtc") return "WebRTC P2P"
- if (lower.contains("/t/")) return "VibeX 云服务 · Beta"
- if (kind == "published" || kind == "tunnel" || lower.startsWith("https://")) return "云服务 · Beta"
+ if (lower.contains("/t/") || lower.contains("dimo-ai.com") || lower.contains("vibex.xforever.xin")) return "Dimo 云中继"
+ if (kind == "published" || kind == "tunnel" || lower.startsWith("https://")) return "Dimo 云中继"
val isPrivateLan = Regex("""^http://(192\.168\.|10\.|172\.(1[6-9]|2\d|3[0-1])\.)""").containsMatchIn(lower)
- if (!isPrivateLan) return "云服务 · Beta"
+ if (!isPrivateLan) return "Dimo 云中继"
return "LAN 局域网直连"
}
-
- private suspend fun connect(profile: HostProfile, allowCloudSwitch: Boolean = false) {
- if (
- _state.value.connection == ConnectionState.Online &&
- _state.value.selectedHostId == profile.hostId &&
- !_state.value.activeOrigin.isNullOrBlank()
- ) {
- loadCatalogSilent()
- return
- }
- _state.update {
- it.copy(
- connection = if (it.connection == ConnectionState.Recovering) ConnectionState.Recovering else ConnectionState.Connecting,
- error = null,
- triedOrigins = emptyList(),
+
+ private suspend fun connect(profile: HostProfile, allowCloudSwitch: Boolean = false, force: Boolean = false) {
+ val requestedAtMs = System.currentTimeMillis()
+ connectMutex.withLock {
+ val currentProfile = migrateProfileOrigins(
+ _state.value.profiles.find { it.hostId == profile.hostId } ?: profile,
)
- }
- val token = credentials.get(profile.hostId)
- if (token.isNullOrBlank()) {
- handleForcedOfflineByRevocation(profile.hostId)
- return
- }
- val targets = profile.reachability.map {
- if (it.origin.contains("/t/")) {
- PairingClient.rememberRelayBase(it.origin)
- }
- ReachabilityTarget(HostOrigin.parse(it.origin), it.kind)
- }.toMutableList()
- val order = OriginOrder.probeOrder(targets, profile.lastSuccessOrigin).toMutableList()
- val tried = mutableListOf()
- var lastError: Exception? = null
- val connectStartMs = System.currentTimeMillis()
-
- fun isLanOriginUrl(url: String): Boolean {
- val lower = url.lowercase()
- if (lower.contains("/t/")) return false
- return lower.contains("://127.0.0.1") ||
- lower.contains("://10.0.2.2") ||
- lower.contains("://localhost") ||
- Regex("""^http://(192\.168\.|10\.|172\.(1[6-9]|2\d|3[0-1])\.)""").containsMatchIn(lower)
- }
-
- val wasLanMode = !allowCloudSwitch &&
- profile.lastSuccessOrigin != null &&
- isLanOriginUrl(profile.lastSuccessOrigin)
-
- suspend fun tryConnectOrigin(origin: HostOrigin): Boolean {
- tried += origin.value
- val VerifyHost = withContext(Dispatchers.IO) {
- PairingClient.probeHostHealth(
- originUrl = origin.value,
- timeoutMs = if (isLanOriginUrl(origin.value)) 350 else 3500,
- expectedHostId = profile.hostId.takeUnless { it.startsWith("host:") },
+ val alreadyConnected = _state.value.connection == ConnectionState.Online &&
+ _state.value.selectedHostId == currentProfile.hostId &&
+ !_state.value.activeOrigin.isNullOrBlank() &&
+ socketDownSinceMs == null
+ if (alreadyConnected && (!force || lastConnectSuccessMs >= requestedAtMs)) {
+ loadCatalogSilent()
+ return@withLock
+ }
+ _state.update {
+ it.copy(
+ connection = if (it.connection == ConnectionState.Recovering || (force && it.connection == ConnectionState.Online)) it.connection else ConnectionState.Connecting,
+ error = null,
+ triedOrigins = emptyList(),
)
}
- if (VerifyHost == null) {
- throw IllegalStateException("电脑端暂未响应")
+ val token = credentials.get(currentProfile.hostId)
+ if (token.isNullOrBlank()) {
+ handleForcedOfflineByRevocation(currentProfile.hostId)
+ return@withLock
}
- val (caps, serverReachability) = withContext(Dispatchers.IO) {
- api.capabilitiesWithReachability(origin, token)
+ val targets = currentProfile.reachability.mapNotNull {
+ val migratedOrigin = PairingClient.migrateLegacyRelayOrigin(it.origin)
+ if (migratedOrigin.contains("/t/")) {
+ PairingClient.rememberRelayBase(migratedOrigin)
+ }
+ runCatching { ReachabilityTarget(HostOrigin.parse(migratedOrigin), it.kind) }.getOrNull()
+ }.toMutableList()
+ val migratedLastSuccess = currentProfile.lastSuccessOrigin?.let(PairingClient::migrateLegacyRelayOrigin)
+ val order = OriginOrder.probeOrder(targets, migratedLastSuccess).toMutableList()
+ val tried = mutableListOf()
+ var lastError: Exception? = null
+ val connectStartMs = System.currentTimeMillis()
+
+ fun isLanOriginUrl(url: String): Boolean {
+ val lower = url.lowercase()
+ if (lower.contains("/t/")) return false
+ return lower.contains("://127.0.0.1") ||
+ lower.contains("://10.0.2.2") ||
+ lower.contains("://localhost") ||
+ lower.contains("://[fd") ||
+ lower.contains("://[fe80") ||
+ Regex("""^http://(192\.168\.|10\.|172\.(1[6-9]|2\d|3[0-1])\.)""").containsMatchIn(lower)
+ }
+
+ val customBase = normalizeCustomRelayOrigin(_state.value.customRelayOrigin)
+ if (customBase.isNotEmpty() && !currentProfile.hostId.startsWith("host:")) {
+ val customUrl = if (customBase.contains("/t/")) customBase else "$customBase/t/${currentProfile.hostId}"
+ val customOrigin = runCatching { HostOrigin.parse(customUrl) }.getOrNull()
+ if (customOrigin != null && order.none { it.value == customOrigin.value }) {
+ order.add(customOrigin)
+ }
}
- val totalDuration = (System.currentTimeMillis() - connectStartMs).coerceAtLeast(1L)
- if (caps.protocol_version.substringBefore('.') != "1") {
+ val canUseCloudRelay = (_state.value.accountSignedIn && (_state.value.accountOverview?.canUseCloudRelay == true)) || customBase.isNotEmpty()
+ val wasLanMode = !allowCloudSwitch &&
+ !canUseCloudRelay &&
+ migratedLastSuccess != null &&
+ isLanOriginUrl(migratedLastSuccess)
+
+ suspend fun tryConnectOrigin(origin: HostOrigin): Boolean {
+ tried += origin.value
+ val verifyHost = withContext(Dispatchers.IO) {
+ PairingClient.probeHostHealth(
+ originUrl = origin.value,
+ timeoutMs = if (isLanOriginUrl(origin.value)) 800 else 5_000,
+ expectedHostId = currentProfile.hostId.takeUnless { it.startsWith("host:") },
+ )
+ }
+ if (verifyHost == null) {
+ throw IllegalStateException("电脑端暂未响应")
+ }
+ val (caps, serverReachability) = withContext(Dispatchers.IO) {
+ api.capabilitiesWithReachability(origin, token)
+ }
+ val totalDuration = (System.currentTimeMillis() - connectStartMs).coerceAtLeast(1L)
+ if (caps.protocol_version.substringBefore('.') != "1") {
+ _state.update {
+ it.copy(
+ connection = ConnectionState.Incompatible,
+ triedOrigins = tried,
+ realtimeRttMs = null,
+ connectionFailureReason = "协议版本不兼容 (${caps.protocol_version})",
+ )
+ }
+ return true
+ }
+ val warmRttMs = withContext(Dispatchers.IO) {
+ val t0 = System.nanoTime()
+ val ok = runCatching { api.health(origin) }.isSuccess
+ if (ok) ((System.nanoTime() - t0) / 1_000_000L).coerceAtLeast(1L) else null
+ }
+ val syncedTargets = serverReachability.map {
+ val migrated = PairingClient.migrateLegacyRelayOrigin(it.origin.value)
+ if (migrated.contains("/t/")) {
+ PairingClient.rememberRelayBase(migrated)
+ }
+ StoredReachability(migrated, it.kind)
+ }
+ val selfOrigin = PairingClient.migrateLegacyRelayOrigin(origin.value)
+ val selfKind = if (selfOrigin.startsWith("https://") || selfOrigin.contains("/t/")) "published" else "lan"
+ if (selfKind == "lan") {
+ declinedCloudFallbackHostIds.remove(currentProfile.hostId)
+ }
+ val mergedReachability = (syncedTargets + currentProfile.reachability + StoredReachability(selfOrigin, selfKind))
+ .map { it.copy(origin = PairingClient.migrateLegacyRelayOrigin(it.origin)) }
+ .filterNot { it.origin.contains(":17890") }
+ .distinctBy { it.origin }
+ val updatedProfile = currentProfile.copy(
+ reachability = mergedReachability,
+ lastSuccessOrigin = selfOrigin,
+ lastSyncAt = System.currentTimeMillis(),
+ )
+ upsertProfile(updatedProfile, true)
+ lastConnectSuccessMs = System.currentTimeMillis()
_state.update {
it.copy(
- connection = ConnectionState.Incompatible,
+ connection = ConnectionState.Online,
+ activeOrigin = selfOrigin,
triedOrigins = tried,
- realtimeRttMs = null,
- connectionFailureReason = "协议版本不兼容 (${caps.protocol_version})",
+ hostVersion = caps.server_version,
+ hostProtocol = caps.protocol_version,
+ hostCapabilities = caps.capabilities,
+ lastConnectDurationMs = totalDuration,
+ realtimeRttMs = warmRttMs,
+ transportPath = inferTransportPath(selfOrigin, updatedProfile),
+ connectionFailureReason = null,
+ pendingCloudFallbackOrigin = null,
+ pendingCloudFallbackHostName = null,
+ desktopConnect = null,
+ error = null,
)
}
+ bindSocket(selfOrigin, token)
+ loadCatalogSilent()
return true
}
- val warmRttMs = withContext(Dispatchers.IO) {
- val t0 = System.nanoTime()
- val ok = runCatching { api.health(origin) }.isSuccess
- if (ok) ((System.nanoTime() - t0) / 1_000_000L).coerceAtLeast(1L) else null
- }
- val syncedTargets = serverReachability.map {
- if (it.origin.value.contains("/t/")) {
- PairingClient.rememberRelayBase(it.origin.value)
+
+ suspend fun tryDiscoverOnLan(): Boolean {
+ val emulator = isEmulator()
+ val discovered = withContext(Dispatchers.IO) {
+ runCatching { PairingClient.discoverLanHosts(includeEmulatorLoopback = emulator) }
+ .getOrDefault(emptyList())
}
- StoredReachability(it.origin.value, it.kind)
- }
- val selfKind = if (origin.value.startsWith("https://") || origin.value.contains("/t/")) "published" else "lan"
- if (selfKind == "lan") {
- declinedCloudFallbackHostIds.remove(profile.hostId)
- }
- val mergedReachability = (syncedTargets + profile.reachability + StoredReachability(origin.value, selfKind))
- .filterNot { it.origin.contains(":17890") }
- .distinctBy { it.origin }
- val updatedProfile = profile.copy(
- reachability = mergedReachability,
- lastSuccessOrigin = origin.value,
- lastSyncAt = System.currentTimeMillis(),
- )
- upsertProfile(updatedProfile, true)
- _state.update {
- it.copy(
- connection = ConnectionState.Online,
- activeOrigin = origin.value,
- triedOrigins = tried,
- hostVersion = caps.server_version,
- hostProtocol = caps.protocol_version,
- hostCapabilities = caps.capabilities,
- lastConnectDurationMs = totalDuration,
- realtimeRttMs = warmRttMs,
- transportPath = inferTransportPath(origin.value, updatedProfile),
- connectionFailureReason = null,
- pendingCloudFallbackOrigin = null,
- pendingCloudFallbackHostName = null,
- desktopConnect = null,
- error = null,
- )
+ val matchedHost = discovered.find { it.hostId == currentProfile.hostId } ?: discovered.firstOrNull {
+ currentProfile.hostId.startsWith("host:")
+ }
+ if (matchedHost != null && !tried.contains(matchedHost.origin) && isLanOriginUrl(matchedHost.origin)) {
+ val discoveredOrigin = runCatching { HostOrigin.parse(matchedHost.origin) }.getOrNull()
+ if (discoveredOrigin != null) {
+ if (tryConnectOrigin(discoveredOrigin)) return true
+ }
+ }
+ return false
}
- bindSocket(origin.value, token)
- loadCatalogSilent()
- return true
- }
- // Happy Eyeballs Step 1: Give LAN candidates a fast priority window (350ms probe)
- val (lanCandidates, remoteCandidates) = order.partition { isLanOriginUrl(it.value) }
- for (origin in lanCandidates) {
- try {
- if (tryConnectOrigin(origin)) return
- } catch (error: AuthRequiredException) {
- handleForcedOfflineByRevocation(profile.hostId)
- return
- } catch (error: Exception) {
- lastError = error
- }
- }
+ val lanAvailable = isLanTransportAvailable()
+ val (lanCandidates, remoteCandidates) = order.partition { isLanOriginUrl(it.value) }
+ val lastSuccessIsCloud = migratedLastSuccess?.contains("/t/") == true
+ var didRunLanScan = false
+
+ if (lanAvailable) {
+ for (origin in lanCandidates) {
+ try {
+ if (tryConnectOrigin(origin)) return@withLock
+ } catch (error: AuthRequiredException) {
+ handleForcedOfflineByRevocation(currentProfile.hostId)
+ return@withLock
+ } catch (error: Exception) {
+ lastError = error
+ }
+ }
- // Step 2: If LAN IP changed via DHCP on the same Wi-Fi, try LAN discovery before considering Cloud Service
- val knownOriginStrings = profile.reachability.map { it.origin }
- val discovered = withContext(Dispatchers.IO) {
- runCatching { PairingClient.discoverLanHosts() }
- .getOrDefault(emptyList())
- }
- val matchedHost = discovered.find { it.hostId == profile.hostId } ?: discovered.firstOrNull {
- profile.hostId.startsWith("host:")
- }
- if (matchedHost != null && !tried.contains(matchedHost.origin) && isLanOriginUrl(matchedHost.origin)) {
- runCatching { HostOrigin.parse(matchedHost.origin) }.getOrNull()?.let { discoveredOrigin ->
- try {
- if (tryConnectOrigin(discoveredOrigin)) return
- } catch (error: AuthRequiredException) {
- handleForcedOfflineByRevocation(profile.hostId)
- return
- } catch (error: Exception) {
- lastError = error
+ // Only run a full 254-IP subnet scan before Cloud Relay when we had LAN candidates
+ // that failed and the previous successful connection was not already on Cloud Relay.
+ if (lanCandidates.isNotEmpty() && !lastSuccessIsCloud) {
+ didRunLanScan = true
+ try {
+ if (tryDiscoverOnLan()) return@withLock
+ } catch (error: AuthRequiredException) {
+ handleForcedOfflineByRevocation(currentProfile.hostId)
+ return@withLock
+ } catch (error: Exception) {
+ lastError = error
+ }
}
}
- }
-
- // Step 3: Domestic Cloud Relay / Published origins
- val rendezvousOrigins = withContext(Dispatchers.IO) {
- runCatching { PairingClient.resolveHostRendezvous(profile.hostId, knownOrigins = knownOriginStrings) }
- .getOrDefault(emptyList())
- }
- val cleanRemoteCandidates = remoteCandidates.map { it.value }.filterNot { url ->
- val lower = url.lowercase()
- lower.contains("serveousercontent.com") ||
- lower.contains("serveo.net") ||
- lower.contains("lhr.life") ||
- lower.contains(":17890") ||
- lower.contains(":17891")
- }
- val combinedRemote = (rendezvousOrigins + cleanRemoteCandidates).distinct()
- // If previously connected via LAN direct, ask the user before switching to Cloud Service!
- if (wasLanMode) {
- for (rawOrigin in combinedRemote) {
- val reachable = withContext(Dispatchers.IO) {
- PairingClient.probeHostHealth(
- originUrl = rawOrigin,
- timeoutMs = 2200,
- expectedHostId = profile.hostId.takeUnless { it.startsWith("host:") },
- )
- }
- if (reachable != null) {
- val shouldPrompt = profile.hostId !in declinedCloudFallbackHostIds
- _state.update {
- it.copy(
- connection = ConnectionState.Offline,
- triedOrigins = tried,
- realtimeRttMs = null,
- connectionFailureReason = "局域网已断开",
- pendingCloudFallbackOrigin = if (shouldPrompt) reachable.origin else it.pendingCloudFallbackOrigin,
- pendingCloudFallbackHostName = if (shouldPrompt) profile.name else it.pendingCloudFallbackHostName,
- error = null,
+ // Cloud Relay / Published origins (0ms entry when on cellular or cloud-first)
+ val knownOriginStrings = currentProfile.reachability.map { it.origin }
+ val rendezvousOrigins = withContext(Dispatchers.IO) {
+ runCatching { PairingClient.resolveHostRendezvous(currentProfile.hostId, knownOrigins = knownOriginStrings) }
+ .getOrDefault(emptyList())
+ }
+ val cleanRemoteCandidates = remoteCandidates.map { it.value }.filterNot { url ->
+ val lower = url.lowercase()
+ lower.contains("serveousercontent.com") ||
+ lower.contains("serveo.net") ||
+ lower.contains("lhr.life") ||
+ lower.contains(":17890") ||
+ lower.contains(":17891")
+ }
+ val combinedRemote = (
+ listOfNotNull(migratedLastSuccess?.takeIf { !isLanOriginUrl(it) }) +
+ rendezvousOrigins +
+ cleanRemoteCandidates +
+ listOfNotNull(accountTenantOriginFor(currentProfile.hostId))
+ ).map(PairingClient::migrateLegacyRelayOrigin).distinct()
+
+ if (wasLanMode) {
+ for (rawOrigin in combinedRemote) {
+ val reachable = withContext(Dispatchers.IO) {
+ PairingClient.probeHostHealth(
+ originUrl = rawOrigin,
+ timeoutMs = 5_000,
+ expectedHostId = currentProfile.hostId.takeUnless { it.startsWith("host:") },
)
}
- return
+ if (reachable != null) {
+ val shouldPrompt = currentProfile.hostId !in declinedCloudFallbackHostIds
+ _state.update {
+ it.copy(
+ connection = ConnectionState.Offline,
+ triedOrigins = tried,
+ realtimeRttMs = null,
+ connectionFailureReason = "局域网已断开",
+ pendingCloudFallbackOrigin = if (shouldPrompt) reachable.origin else it.pendingCloudFallbackOrigin,
+ pendingCloudFallbackHostName = if (shouldPrompt) currentProfile.name else it.pendingCloudFallbackHostName,
+ error = null,
+ )
+ }
+ return@withLock
+ }
+ }
+ } else {
+ for (rawOrigin in combinedRemote) {
+ if (tried.contains(rawOrigin)) continue
+ val parsedOrigin = runCatching { HostOrigin.parse(rawOrigin) }.getOrNull() ?: continue
+ try {
+ if (tryConnectOrigin(parsedOrigin)) return@withLock
+ } catch (error: AuthRequiredException) {
+ handleForcedOfflineByRevocation(currentProfile.hostId)
+ return@withLock
+ } catch (error: Exception) {
+ lastError = error
+ }
}
}
- } else {
- for (rawOrigin in combinedRemote) {
- if (tried.contains(rawOrigin)) continue
- val parsedOrigin = runCatching { HostOrigin.parse(rawOrigin) }.getOrNull() ?: continue
+
+ // Last-chance Wi-Fi LAN scan if we prioritized Cloud Relay first and it failed
+ if (lanAvailable && !didRunLanScan) {
try {
- if (tryConnectOrigin(parsedOrigin)) return
+ if (tryDiscoverOnLan()) return@withLock
} catch (error: AuthRequiredException) {
- handleForcedOfflineByRevocation(profile.hostId)
- return
+ handleForcedOfflineByRevocation(currentProfile.hostId)
+ return@withLock
} catch (error: Exception) {
lastError = error
}
}
- }
- val errMsg = lastError?.message.orEmpty()
- val failureReason = when {
- errMsg.contains("sleep", ignoreCase = true) -> "电脑已休眠"
- errMsg.contains("Network is unreachable", ignoreCase = true) ||
- errMsg.contains("EHOSTUNREACH", ignoreCase = true) -> "网络受限"
- else -> "电脑离线"
- }
- _state.update {
- it.copy(
- connection = if (failureReason == "电脑已休眠") ConnectionState.HostSleeping else ConnectionState.Offline,
- triedOrigins = tried,
- realtimeRttMs = null,
- connectionFailureReason = failureReason,
- error = null,
- )
+ val errMsg = lastError?.message.orEmpty()
+ val failureReason = when {
+ errMsg.contains("sleep", ignoreCase = true) -> "电脑已休眠"
+ errMsg.contains("Network is unreachable", ignoreCase = true) ||
+ errMsg.contains("EHOSTUNREACH", ignoreCase = true) -> "网络受限"
+ else -> "电脑离线"
+ }
+ connLog("connect failed reason=$failureReason err=$errMsg attempt=$reconnectAttempt", warn = true)
+ val keepRecovering = force &&
+ !dev.vibex.companion.ConnectionPolicy.reconnectGivesOffline(reconnectAttempt) &&
+ failureReason != "电脑已休眠"
+ scheduleReconnect("connect-failed:$failureReason")
+ _state.update {
+ it.copy(
+ connection = if (failureReason == "电脑已休眠") ConnectionState.HostSleeping
+ else if (keepRecovering) (if (it.connection == ConnectionState.Online) it.connection else ConnectionState.Recovering)
+ else ConnectionState.Offline,
+ triedOrigins = tried,
+ realtimeRttMs = null,
+ connectionFailureReason = failureReason,
+ error = null,
+ )
+ }
}
}
@@ -1823,7 +2737,8 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
token = token,
onOpen = {
viewModelScope.launch {
- val openId = (_state.value.route as? Route.Timeline)?.conversationId
+ markConnected()
+ val openId = currentObservedConversationId()
if (!openId.isNullOrBlank()) {
attachConversation(openId)
}
@@ -1845,8 +2760,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
val project = resolveProjectName(session.workspaceId)
val titleText = session.title.ifBlank { "对话任务" }
if (event.kind == "turn_failed") {
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
key,
"$project · 会话执行出错",
titleText,
@@ -1866,8 +2780,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
)
finishLiveActivity(conversationId, failedMessage = titleText)
} else {
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
key,
"$project · 会话已完成",
titleText,
@@ -1904,22 +2817,40 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
handleForcedOfflineByRevocation()
}
- } else if (_state.value.connection == ConnectionState.Online) {
- _state.update { it.copy(connection = ConnectionState.Recovering) }
- viewModelScope.launch {
- delay(800)
- if (_state.value.connection == ConnectionState.Recovering) {
- connectSelected()
+ } else if (_state.value.connection == ConnectionState.Online ||
+ _state.value.connection == ConnectionState.Recovering
+ ) {
+ connLog("ws closed reason=$reason", warn = true)
+ if (socketDownSinceMs == null) socketDownSinceMs = System.currentTimeMillis()
+ // Debounce: only surface Recovering if the link stays down.
+ recoveringJob?.cancel()
+ recoveringJob = viewModelScope.launch {
+ delay(dev.vibex.companion.ConnectionPolicy.RECOVERING_DEBOUNCE_MS)
+ if (dev.vibex.companion.ConnectionPolicy.shouldShowRecovering(socketDownSinceMs, System.currentTimeMillis()) &&
+ _state.value.connection == ConnectionState.Online
+ ) {
+ connLog("down > debounce -> Recovering")
+ _state.update { it.copy(connection = ConnectionState.Recovering) }
}
}
+ scheduleReconnect("ws-closed")
}
},
)
pingJob?.cancel()
pingJob = viewModelScope.launch {
+ var lastHttpMs = System.currentTimeMillis()
+ var httpFailures = 0
while (isActive) {
- delay(2_500)
+ delay(dev.vibex.companion.ConnectionPolicy.WS_PING_INTERVAL_MS)
+ if (_state.value.connection != ConnectionState.Online) continue
socket.ping()
+ val now = System.currentTimeMillis()
+ if (!dev.vibex.companion.ConnectionPolicy.shouldRunHttpRefresh(
+ isAppInForeground, _state.value.connection, now - lastHttpMs,
+ )
+ ) continue
+ lastHttpMs = now
runCatching { loadConversations(silent = true) }
val refreshedResult = withContext(Dispatchers.IO) {
runCatching { api.capabilitiesWithReachability(HostOrigin.parse(origin), token) }
@@ -1930,13 +2861,27 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
break
}
val refreshed = refreshedResult.getOrNull()
- if (refreshed != null) {
- val synced = refreshed.second.map { StoredReachability(it.origin.value, it.kind) }
- selectedProfile()?.let { currentProfile ->
- val merged = (synced + currentProfile.reachability).distinctBy { it.origin }
- if (merged != currentProfile.reachability) {
- upsertProfile(currentProfile.copy(reachability = merged), true)
- }
+ if (refreshed == null) {
+ httpFailures += 1
+ connLog("http refresh failed x$httpFailures: ${failure?.message}", warn = true)
+ // Only a streak means trouble; the WS close path owns real recovery.
+ if (dev.vibex.companion.ConnectionPolicy.pollDegraded(httpFailures)) {
+ httpFailures = 0
+ socketDownSinceMs = socketDownSinceMs ?: System.currentTimeMillis()
+ scheduleReconnect("http-poll-streak", immediate = true)
+ }
+ continue
+ }
+ httpFailures = 0
+ val synced = refreshed.second.map {
+ StoredReachability(PairingClient.migrateLegacyRelayOrigin(it.origin.value), it.kind)
+ }
+ selectedProfile()?.let { currentProfile ->
+ val merged = (synced + currentProfile.reachability)
+ .map { it.copy(origin = PairingClient.migrateLegacyRelayOrigin(it.origin)) }
+ .distinctBy { it.origin }
+ if (merged != currentProfile.reachability) {
+ upsertProfile(currentProfile.copy(reachability = merged), true)
}
}
}
@@ -1975,27 +2920,31 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
runCatching {
val (origin, token) = live()
syncConversationTimeline(id, forceRows = true)
- val needControls = synchronized(session) {
- session.sessionModes.isEmpty() && session.sessionConfig.isEmpty()
- }
- if (needControls) {
- val controls = withContext(Dispatchers.IO) {
- api.ensureSessionControls(origin, token, id)
- }
- synchronized(session) {
- EventFold.applySessionControls(session, controls)
+ viewModelScope.launch {
+ runCatching {
+ val needControls = synchronized(session) {
+ session.sessionModes.isEmpty() && session.sessionConfig.isEmpty()
+ }
+ if (needControls) {
+ val controls = withContext(Dispatchers.IO) {
+ api.ensureSessionControls(origin, token, id)
+ }
+ synchronized(session) {
+ EventFold.applySessionControls(session, controls)
+ }
+ }
+ val skills = withContext(Dispatchers.IO) {
+ val agId = synchronized(session) { session.agentId }.ifBlank { summary?.agentId.orEmpty() }
+ val wsId = synchronized(session) { session.workspaceId }.ifBlank { summary?.workspaceId.orEmpty() }
+ api.listSlashCommands(origin, token, agId, wsId)
+ }
+ synchronized(session) {
+ session.skillCommands.clear()
+ session.skillCommands += skills
+ }
+ publishTimeline(session)
}
}
- val skills = withContext(Dispatchers.IO) {
- val agId = synchronized(session) { session.agentId }.ifBlank { summary?.agentId.orEmpty() }
- val wsId = synchronized(session) { session.workspaceId }.ifBlank { summary?.workspaceId.orEmpty() }
- api.listSlashCommands(origin, token, agId, wsId)
- }
- synchronized(session) {
- session.skillCommands.clear()
- session.skillCommands += skills
- }
- publishTimeline(session)
}
}
@@ -2040,6 +2989,60 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
if (forceRows || wasEmpty || events.isNotEmpty()) {
publishTimeline(session)
}
+ val needsSteeringProbe = synchronized(session) { session.inFlightTurnId != null && !session.steeringKnown }
+ if (needsSteeringProbe) refreshSteeringCapability(id)
+ }
+
+ /** Reads the binding's steering capability from `conversation_detail` (no guessing from agent identity). */
+ private suspend fun refreshSteeringCapability(conversationId: String) {
+ val session = sessions[conversationId] ?: return
+ val (origin, token) = live()
+ val detail = withContext(Dispatchers.IO) {
+ runCatching { api.conversationDetailLight(origin, token, conversationId) }.getOrNull()
+ } ?: return
+ synchronized(session) { EventFold.applyConversationDetail(session, detail) }
+ publishTimeline(session)
+ }
+
+ /** Native in-flight steering. Only call when the host reported steering support. */
+ fun steer(conversationId: String, text: String) {
+ if (!_state.value.connection.allowsWrites || text.isBlank()) return
+ val session = sessions[conversationId] ?: return send(conversationId, text)
+ val turnId = synchronized(session) { session.inFlightTurnId }
+ if (turnId == null || !synchronized(session) { session.canSteer }) return send(conversationId, text)
+ viewModelScope.launch {
+ runCatching {
+ val (origin, token) = live()
+ withContext(Dispatchers.IO) { api.steer(origin, token, conversationId, turnId, text) }
+ syncConversationTimeline(conversationId, forceRows = true)
+ }.onFailure { fail(it) }
+ }
+ }
+
+ fun cancelRateLimitWait(conversationId: String) {
+ if (!_state.value.connection.allowsWrites) return
+ viewModelScope.launch {
+ runCatching {
+ val (origin, token) = live()
+ withContext(Dispatchers.IO) { api.rateLimitCancelWait(origin, token, conversationId) }
+ sessions[conversationId]?.let {
+ synchronized(it) { it.rateLimit = null }
+ publishTimeline(it)
+ }
+ }.onFailure { fail(it) }
+ }
+ }
+
+ fun setRateLimitAutoResume(conversationId: String, autoResume: Boolean) {
+ if (!_state.value.connection.allowsWrites) return
+ viewModelScope.launch {
+ runCatching {
+ val (origin, token) = live()
+ withContext(Dispatchers.IO) {
+ api.rateLimitUpdateAutoResume(origin, token, conversationId, autoResume)
+ }
+ }.onFailure { fail(it) }
+ }
}
private suspend fun loadConversations(silent: Boolean = false) {
@@ -2071,8 +3074,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
if (notifiedEventKeys.add(alertKey)) {
val project = resolveProjectName(conv.workspaceId)
val titleText = conv.title.ifBlank { "新对话已创建,点击查看" }
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
alertKey,
"$project · 新会话已创建",
titleText,
@@ -2090,25 +3092,11 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
kind = AttentionToastKind.Created,
),
)
- if (_state.value.route == Route.Conversations) {
- userRequestedNewChatLanding = false
- openConversation(conv.id)
- }
}
}
}
}
- if (
- !hasAutoOpenedInitialConversation &&
- !userRequestedNewChatLanding &&
- merged.isNotEmpty() &&
- _state.value.route == Route.Conversations
- ) {
- hasAutoOpenedInitialConversation = true
- openConversation(merged.first().id)
- }
-
viewModelScope.launch(Dispatchers.IO) {
var anyChanged = false
merged.take(6).forEach { summary ->
@@ -2157,9 +3145,9 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
private fun resolveProjectName(workspaceId: String): String {
- val cat = _state.value.catalog ?: return "VibeX"
- val ws = cat.workspaces.find { it.id == workspaceId } ?: return "VibeX"
- return cat.projects.find { it.id == ws.projectId }?.name?.ifBlank { "VibeX" } ?: "VibeX"
+ val cat = _state.value.catalog ?: return "Dimo"
+ val ws = cat.workspaces.find { it.id == workspaceId } ?: return "Dimo"
+ return cat.projects.find { it.id == ws.projectId }?.name?.ifBlank { "Dimo" } ?: "Dimo"
}
fun dismissAttentionToast() {
@@ -2358,8 +3346,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
add(SystemNotificationAction("拒绝", "perm_reject", convId, perm.id, reject.id))
}
}
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
eventKey,
"$project:需要批准操作权限",
"$sessionTitle · $subtitle",
@@ -2390,8 +3377,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
SystemNotificationAction("批准执行", "question_confirm", convId, quest.id, "Yes"),
SystemNotificationAction("拒绝", "question_reject", convId, quest.id, ""),
)
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
eventKey,
"$project:等待你的回答",
"$sessionTitle · $qText",
@@ -2420,8 +3406,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
if (notifiedEventKeys.add(eventKey)) {
if (lastRow?.kind == "turn_failed") {
val errText = lastRow.body.ifBlank { sessionTitle }
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
eventKey,
"$project · 会话执行异常",
errText,
@@ -2441,8 +3426,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
)
finishLiveActivity(convId, failedMessage = errText)
} else {
- SystemNotifier.notifyAlert(
- getApplication(),
+ notifyAlertIfAllowed(
eventKey,
"$project · 会话已完成",
sessionTitle,
@@ -2667,7 +3651,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
return ResolvedStage(
phase = VibeXActivityPhase.Thinking,
stageTitle = "准备执行中",
- stageSubtitle = "VibeX 正在同步工作区状态",
+ stageSubtitle = "Dimo 正在同步工作区状态",
progress = 0.16f,
)
}
@@ -2805,10 +3789,12 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
accountCodeSent = false,
accountCodeResendAtMs = 0L,
accountError = null,
- desktopConnect = if (it.connection == ConnectionState.Online) null else DesktopConnectSheet(),
+ desktopConnect = null,
+ isAutoConnectingInBackground = it.connection != ConnectionState.Online,
+ autoConnectingHostName = null,
)
}
- refreshAccount()
+ refreshAccount(justLoggedIn = true)
discoverHosts()
}
@@ -2832,6 +3818,9 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
accountLoginPollJob?.cancel()
accountLoginPollJob = null
connectPollJob?.cancel()
+ lastPushedSavedHostsSignature = null
+ rawAccountDesktops = emptyList()
+ removedAccountHostIds.clear()
viewModelScope.launch {
_state.update { it.copy(accountSigningOut = true) }
accountRepo.signOut()
@@ -2856,9 +3845,17 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
_state.update { it.copy(accountLoginRequested = requested) }
}
- fun refreshAccount() {
+ fun refreshAccount(justLoggedIn: Boolean = false) {
if (accountRepo.getToken() == null) {
- _state.update { it.copy(accountSignedIn = false, accountOverview = null, desktopConnect = null) }
+ _state.update {
+ it.copy(
+ accountSignedIn = false,
+ accountOverview = null,
+ desktopConnect = null,
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
+ )
+ }
return
}
viewModelScope.launch {
@@ -2879,10 +3876,12 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
accountError = null,
)
}
- syncAccountHosts(forcePush = true)
+ syncAccountHosts(forcePush = true, justLoggedIn = justLoggedIn)
}
.onFailure { err ->
if (err is VibeXAccountException && err.code == "signed_out") {
+ rawAccountDesktops = emptyList()
+ removedAccountHostIds.clear()
_state.update {
it.copy(
accountSignedIn = false,
@@ -2891,16 +3890,20 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
accountSavedHosts = emptyList(),
accountLoading = false,
desktopConnect = null,
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
)
}
} else {
_state.update {
val sheet = it.desktopConnect?.takeIf { s -> s.stage == DesktopConnectStage.Syncing }
- ?.copy(stage = DesktopConnectStage.Failed(DESKTOP_SYNC_FAILED, route = null))
+ ?.copy(stage = DesktopConnectStage.Failed(DESKTOP_SYNC_FAILED, retryTarget = null))
it.copy(
accountLoading = false,
accountError = describeAccountError(err),
desktopConnect = sheet ?: it.desktopConnect,
+ isAutoConnectingInBackground = false,
+ autoConnectingHostName = null,
)
}
}
@@ -2908,33 +3911,105 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
- fun syncAccountHosts(forcePush: Boolean = false) {
+ private fun savedHostsSignature(items: List): String =
+ items
+ .map { p ->
+ val rawId = AccountDesktops.rawHostId(p.hostId.ifBlank { p.profileId })
+ val devId = p.deviceId.ifBlank { rawId }
+ "$rawId|$devId|${p.accessToken}"
+ }
+ .sorted()
+ .joinToString("\n")
+
+ fun syncAccountHosts(forcePush: Boolean = false, justLoggedIn: Boolean = false) {
if (accountRepo.getToken() == null) return
viewModelScope.launch {
_state.update { it.copy(accountSyncingHosts = true) }
- val desktops = runCatching { accountRepo.fetchDesktops() }
+ val relayBase = currentAccountRelayBase()
+ val probedDesktops = runCatching { accountRepo.fetchProbedDesktops(relayBase = relayBase) }
val remoteSaved = runCatching { accountRepo.fetchSavedHosts() }.getOrDefault(emptyList())
mergeRemoteAccountProfiles(remoteSaved)
+ probedDesktops.getOrNull()?.let { rawAccountDesktops = it }
val localExport = exportSyncableProfiles()
- val finalSaved = if (localExport.isNotEmpty() && (forcePush || localExport.size != remoteSaved.size)) {
- runCatching { accountRepo.putSavedHosts(localExport) }.getOrDefault(remoteSaved)
+ val localSig = savedHostsSignature(localExport)
+ val remoteSig = savedHostsSignature(remoteSaved)
+ val shouldPush = localExport.isNotEmpty() &&
+ localSig != remoteSig &&
+ (forcePush || localSig != lastPushedSavedHostsSignature)
+ val finalSaved = if (shouldPush) {
+ runCatching { accountRepo.putSavedHosts(localExport) }
+ .onSuccess { lastPushedSavedHostsSignature = localSig }
+ .getOrDefault(remoteSaved)
} else {
+ if (localExport.isNotEmpty() && localSig == remoteSig) {
+ lastPushedSavedHostsSignature = localSig
+ }
remoteSaved
}
+ var autoConnectDesktop: AccountDesktop? = null
_state.update { current ->
- val listed = desktops.getOrDefault(current.accountDesktops)
- val sheet = current.desktopConnect?.takeIf { it.stage == DesktopConnectStage.Syncing }?.let {
- if (desktops.isSuccess) {
- it.copy(stage = DesktopConnectStage.Choosing, selectedHostId = listed.firstOrNull()?.hostId)
- } else {
- it.copy(stage = DesktopConnectStage.Failed(DESKTOP_SYNC_FAILED, route = null))
+ val listed = probedDesktops.map { probed ->
+ filterAndDeduplicateAccountDesktops(
+ source = probed,
+ hosts = current.discoveredHosts,
+ profileList = current.profiles,
+ )
+ }.getOrDefault(current.accountDesktops)
+ val shouldAutoConnectSingle = listed.size == 1 &&
+ current.connection != ConnectionState.Online &&
+ current.desktopConnect == null &&
+ (justLoggedIn || (!didAttemptInitialAccountAutoConnect && current.profiles.isEmpty() && current.autoConnect))
+ if (shouldAutoConnectSingle) {
+ didAttemptInitialAccountAutoConnect = true
+ autoConnectDesktop = listed.single()
+ }
+ val sheet = when {
+ current.desktopConnect?.stage == DesktopConnectStage.Syncing -> {
+ if (probedDesktops.isSuccess) {
+ current.desktopConnect.copy(
+ stage = DesktopConnectStage.Choosing,
+ selectedHostId = listed.firstOrNull()?.hostId,
+ )
+ } else {
+ current.desktopConnect.copy(
+ stage = DesktopConnectStage.Failed(DESKTOP_SYNC_FAILED, retryTarget = null),
+ )
+ }
+ }
+ justLoggedIn && autoConnectDesktop == null && current.connection != ConnectionState.Online -> {
+ DesktopConnectSheet(
+ stage = if (probedDesktops.isSuccess) {
+ DesktopConnectStage.Choosing
+ } else {
+ DesktopConnectStage.Failed(DESKTOP_SYNC_FAILED, retryTarget = null)
+ },
+ selectedHostId = listed.firstOrNull()?.hostId,
+ )
+ }
+ current.desktopConnect != null -> {
+ val curSel = current.desktopConnect.selectedHostId
+ val nextSel = if (curSel == null || listed.none { it.hostId == curSel }) {
+ listed.firstOrNull()?.hostId
+ } else {
+ curSel
+ }
+ current.desktopConnect.copy(selectedHostId = nextSel)
}
- } ?: current.desktopConnect
+ else -> current.desktopConnect
+ }
current.copy(
accountDesktops = listed,
accountSavedHosts = finalSaved,
accountSyncingHosts = false,
desktopConnect = sheet,
+ isAutoConnectingInBackground = if (autoConnectDesktop != null) true else false,
+ autoConnectingHostName = autoConnectDesktop?.displayName,
+ )
+ }
+ autoConnectDesktop?.let { desktop ->
+ connectDesktopTarget(
+ target = DesktopConnectTarget.Account(desktop),
+ silentUntilNeeded = true,
)
}
}
@@ -2945,7 +4020,10 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
val localExport = exportSyncableProfiles()
if (localExport.isEmpty()) return@launch
+ val signature = savedHostsSignature(localExport)
+ if (signature == lastPushedSavedHostsSignature) return@launch
runCatching { accountRepo.putSavedHosts(localExport) }.onSuccess { saved ->
+ lastPushedSavedHostsSignature = signature
_state.update { it.copy(accountSavedHosts = saved) }
}
}
@@ -2956,21 +4034,30 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
val currentList = _state.value.profiles.toMutableList()
var didChange = false
+ for (i in currentList.indices) {
+ val migrated = migrateProfileOrigins(currentList[i])
+ if (migrated != currentList[i]) {
+ currentList[i] = migrated
+ didChange = true
+ }
+ }
+
for (remote in remoteSaved) {
if (remote.accessToken.isBlank()) continue
- val cleanHostId = remote.hostId.ifBlank { remote.profileId }
- if (cleanHostId.isBlank()) continue
- var targetOrigin = remote.origin.trim().trimEnd('/')
+ val cleanHostId = AccountDesktops.rawHostId(remote.hostId.ifBlank { remote.profileId })
+ if (cleanHostId.isBlank() || AccountDesktops.isPlaceholderHostId(cleanHostId)) continue
+ var targetOrigin = PairingClient.migrateLegacyRelayOrigin(remote.origin.trim().trimEnd('/'))
if (
(targetOrigin.isBlank() || targetOrigin.contains("127.0.0.1") || targetOrigin.contains("localhost")) &&
remote.hostId.isNotBlank() &&
relayBase.isNotEmpty()
) {
- targetOrigin = "$relayBase/t/${remote.hostId}"
+ targetOrigin = "$relayBase/t/${AccountDesktops.rawHostId(remote.hostId)}"
}
+ targetOrigin = PairingClient.migrateLegacyRelayOrigin(targetOrigin)
if (targetOrigin.isBlank()) continue
val exists = currentList.any {
- it.hostId == cleanHostId ||
+ AccountDesktops.rawHostId(it.hostId) == cleanHostId ||
it.lastSuccessOrigin == targetOrigin ||
it.reachability.any { r -> r.origin == targetOrigin }
}
@@ -2978,7 +4065,7 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
credentials.put(cleanHostId, remote.accessToken)
currentList += HostProfile(
hostId = cleanHostId,
- name = remote.name.ifBlank { "VibeX 电脑" },
+ name = remote.name.takeUnless { AccountDesktops.isGenericHostName(it) } ?: "Dimo 电脑",
deviceId = remote.deviceId.ifBlank { remote.profileId },
reachability = listOf(StoredReachability(targetOrigin, "published")),
lastSuccessOrigin = targetOrigin,
@@ -2997,30 +4084,41 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
private fun exportSyncableProfiles(): List {
val nowIso = Instant.now().toString()
- return _state.value.profiles.mapNotNull { profile ->
- val token = credentials.get(profile.hostId)?.takeIf { it.isNotBlank() } ?: return@mapNotNull null
- val origin = profile.lastSuccessOrigin
+ val byRawHostId = LinkedHashMap>()
+ for (profile in _state.value.profiles) {
+ val token = credentials.get(profile.hostId)?.takeIf { it.isNotBlank() } ?: continue
+ val rawOrigin = profile.lastSuccessOrigin
?: profile.reachability.firstOrNull()?.origin
- ?: return@mapNotNull null
- VibeXSyncableHostProfile(
- syncKey = profile.hostId,
- profileId = profile.deviceId.ifBlank { profile.hostId },
- hostId = profile.hostId,
+ ?: continue
+ val origin = PairingClient.migrateLegacyRelayOrigin(rawOrigin)
+ val rawHostId = AccountDesktops.rawHostId(profile.hostId)
+ if (rawHostId.isBlank() || AccountDesktops.isPlaceholderHostId(rawHostId)) continue
+ val devId = profile.deviceId.ifBlank { rawHostId }
+ val syncable = VibeXSyncableHostProfile(
+ syncKey = rawHostId,
+ profileId = devId,
+ hostId = rawHostId,
name = profile.name,
origin = origin,
provisionKind = "http",
- deviceId = profile.deviceId.ifBlank { profile.hostId },
+ deviceId = devId,
accessToken = token,
lastConnectedAt = nowIso,
updatedAt = nowIso,
)
+ val syncTs = profile.lastSyncAt ?: 0L
+ val prev = byRawHostId[rawHostId]
+ if (prev == null || syncTs >= prev.first) {
+ byRawHostId[rawHostId] = syncTs to syncable
+ }
}
+ return byRawHostId.values.map { it.second }
}
private fun describeAccountError(err: Throwable): String {
if (err is VibeXAccountException) {
return when (err.code) {
- "network" -> "无法连接到 VibeX 账号服务,请检查网络后重试"
+ "network" -> "无法连接到 Dimo 账号服务,请检查网络后重试"
"signed_out" -> "登录状态已失效,请重新登录"
else -> "账号服务请求失败(${err.code})"
}
@@ -3029,7 +4127,20 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
private fun persist(transform: (StoredState) -> StoredState) {
- val next = transform(StoredState(_state.value.selectedHostId, _state.value.profiles, _state.value.appearance, _state.value.streamDisplay, _state.value.accent))
+ val cur = _state.value
+ val next = transform(
+ StoredState(
+ selectedHostId = cur.selectedHostId,
+ profiles = cur.profiles,
+ appearance = cur.appearance,
+ streamDisplay = cur.streamDisplay,
+ accent = cur.accent,
+ language = cur.language,
+ confirmHighRiskApproval = cur.confirmHighRiskApproval,
+ muteForegroundNotifications = cur.muteForegroundNotifications,
+ customRelayOrigin = cur.customRelayOrigin,
+ ),
+ )
viewModelScope.launch(Dispatchers.IO) {
profiles.save(next)
}
@@ -3142,25 +4253,58 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
- suspend fun fetchCollabChatState(spaceId: String, isGroup: Boolean): Pair> {
+ suspend fun fetchCollabChatState(
+ spaceId: String,
+ isGroup: Boolean,
+ limit: Int = 80,
+ ): Pair> {
val (origin, token) = live()
return withContext(Dispatchers.IO) {
- val page = api.collabMessagesPage(origin, token, spaceId)
+ val page = api.collabMessagesPage(origin, token, spaceId, limit = limit, latest = true)
val members = if (isGroup) api.collabSpaceMembers(origin, token, spaceId) else emptyList()
page to members
}
}
+ suspend fun fetchCollabMessagesPage(
+ spaceId: String,
+ limit: Int = 80,
+ sinceSeq: Long? = null,
+ beforeSeq: Long? = null,
+ latest: Boolean = sinceSeq == null && beforeSeq == null,
+ ): CollabMessagesPage {
+ val (origin, token) = live()
+ return withContext(Dispatchers.IO) {
+ api.collabMessagesPage(
+ origin = origin,
+ token = token,
+ spaceId = spaceId,
+ limit = limit,
+ sinceSeq = sinceSeq,
+ beforeSeq = beforeSeq,
+ latest = latest,
+ )
+ }
+ }
+
+ suspend fun fetchCollabSpaceMembersOnly(spaceId: String): List {
+ val (origin, token) = live()
+ return withContext(Dispatchers.IO) {
+ api.collabSpaceMembers(origin, token, spaceId)
+ }
+ }
+
suspend fun postCollabMessage(
spaceId: String,
content: String,
to: List = emptyList(),
inReplyTo: String? = null,
delaySeconds: Int? = null,
+ operationId: String = java.util.UUID.randomUUID().toString().lowercase(),
) {
val (origin, token) = live()
withContext(Dispatchers.IO) {
- api.collabPostMessage(origin, token, spaceId, content, to, inReplyTo, delaySeconds)
+ api.collabPostMessage(origin, token, spaceId, content, to, inReplyTo, delaySeconds, operationId)
}
}
@@ -3285,6 +4429,146 @@ class CompanionModel(application: Application) : AndroidViewModel(application) {
}
}
+ // ---- Engine handoff (conversation_preview/confirm_engine_handoff) ----
+ private val _handoff = MutableStateFlow(HandoffUiState())
+ val handoff: StateFlow = _handoff
+
+ fun openHandoff(conversationId: String) {
+ _handoff.value = HandoffUiState(open = true, conversationId = conversationId, loadingInstances = true)
+ viewModelScope.launch {
+ runCatching {
+ val (origin, token) = live()
+ withContext(Dispatchers.IO) { api.providerInstances(origin, token) }
+ }.onSuccess { list ->
+ _handoff.update { it.copy(instances = list, loadingInstances = false) }
+ }.onFailure { e ->
+ // Instances are optional (default instance is used); engine choice still works.
+ _handoff.update { it.copy(loadingInstances = false, instancesError = e.message ?: "无法读取账号实例") }
+ }
+ }
+ if (_state.value.catalog == null) loadCatalogSilent()
+ }
+
+ fun closeHandoff() { _handoff.value = HandoffUiState() }
+
+ fun selectHandoffTarget(engine: String, instanceId: String?) {
+ _handoff.update { it.copy(targetEngine = engine, targetInstanceId = instanceId, preview = null, error = null, done = false) }
+ }
+
+ fun previewHandoff() {
+ val h = _handoff.value
+ if (h.targetEngine.isBlank() || h.busy) return
+ _handoff.update { it.copy(busy = true, error = null, preview = null) }
+ viewModelScope.launch {
+ runCatching {
+ val (origin, token) = live()
+ withContext(Dispatchers.IO) {
+ api.previewEngineHandoff(origin, token, h.conversationId, h.targetEngine, h.targetInstanceId)
+ }
+ }.onSuccess { p -> _handoff.update { it.copy(busy = false, preview = p) } }
+ .onFailure { e -> _handoff.update { it.copy(busy = false, error = e.message ?: "预览失败") } }
+ }
+ }
+
+ fun confirmHandoff() {
+ val h = _handoff.value
+ if (h.targetEngine.isBlank() || h.busy || !_state.value.connection.allowsWrites) return
+ _handoff.update { it.copy(busy = true, error = null) }
+ viewModelScope.launch {
+ runCatching {
+ val (origin, token) = live()
+ withContext(Dispatchers.IO) {
+ api.confirmEngineHandoff(origin, token, h.conversationId, h.targetEngine, h.targetInstanceId)
+ }
+ }.onSuccess {
+ _handoff.update { it.copy(busy = false, done = true) }
+ loadCatalogSilent()
+ }.onFailure { e -> _handoff.update { it.copy(busy = false, error = e.message ?: "切换失败") } }
+ }
+ }
+
+ // ---- Side chat (conversation_side_chat_send/abort); one-shot request, no streaming over HTTP ----
+ private val sideChatApi by lazy {
+ HostApi(
+ OkHttpTransport(
+ okhttp3.OkHttpClient.Builder()
+ .socketFactory(dev.vibex.companion.app.net.TcpNoDelaySocketFactory)
+ .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
+ // Host side-chat timeout is 180s.
+ .readTimeout(200, java.util.concurrent.TimeUnit.SECONDS)
+ .build(),
+ ),
+ )
+ }
+ private val sideChatJobs = java.util.concurrent.ConcurrentHashMap()
+ private val _sideChats = MutableStateFlow