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>(emptyMap()) + val sideChats: StateFlow> = _sideChats + + private fun updateSideChat(conversationId: String, f: (SideChatUiState) -> SideChatUiState) { + _sideChats.update { it + (conversationId to f(it[conversationId] ?: SideChatUiState())) } + } + + fun sendSideChat(conversationId: String, prompt: String, items: List) { + val text = prompt.trim() + val cur = _sideChats.value[conversationId] ?: SideChatUiState() + if (text.isEmpty() || cur.sending) return + val history = cur.messages + val reqId = cur.sideChatId + val userMsg = SideChatMessage(java.util.UUID.randomUUID().toString(), "user", text) + updateSideChat(conversationId) { it.copy(messages = it.messages + userMsg, sending = true) } + val context = buildSideChatContext(items) + sideChatJobs[conversationId] = viewModelScope.launch { + runCatching { + val (origin, token) = live() + withContext(Dispatchers.IO) { + sideChatApi.sideChatSend(origin, token, conversationId, reqId, text, context, history) + } + }.onSuccess { r -> + updateSideChat(conversationId) { + it.copy( + sending = false, + messages = it.messages + SideChatMessage(java.util.UUID.randomUUID().toString(), "assistant", r.content, r.toolCalls), + ) + } + }.onFailure { e -> + if (e is kotlinx.coroutines.CancellationException) return@onFailure + if (e is AuthRequiredException) { fail(e); updateSideChat(conversationId) { it.copy(sending = false) }; return@onFailure } + val raw = e.message.orEmpty() + val msg = when { + raw.contains("cancelled", true) -> "已中止" + raw.contains("timeout", true) || raw.contains("timed out", true) -> "旁路对话超时,Host 未在限定时间内返回" + raw.contains("not currently connected to the relay", true) -> "电脑当前离线或未连接到 Dimo 云中继" + raw.isBlank() -> "旁路对话失败" + else -> raw.replace(Regex("vibex", RegexOption.IGNORE_CASE), "Dimo") + } + updateSideChat(conversationId) { + it.copy(sending = false, messages = it.messages + SideChatMessage(java.util.UUID.randomUUID().toString(), "assistant", msg, isError = true)) + } + } + } + } + + fun abortSideChat(conversationId: String) { + val cur = _sideChats.value[conversationId] ?: return + if (!cur.sending) return + sideChatJobs.remove(conversationId)?.cancel() + updateSideChat(conversationId) { + it.copy(sending = false, messages = it.messages + SideChatMessage(java.util.UUID.randomUUID().toString(), "assistant", "已中止", isError = true)) + } + // Tell the Host to stop the in-flight run; best-effort, failure surfaced. + viewModelScope.launch { + runCatching { + val (origin, token) = live() + withContext(Dispatchers.IO) { api.sideChatAbort(origin, token, conversationId, cur.sideChatId) } + }.onFailure { fail(it) } + } + } + + fun clearSideChat(conversationId: String) { + sideChatJobs.remove(conversationId)?.cancel() + _sideChats.update { it - conversationId } + } + internal fun fail(error: Throwable) { if (error is AuthRequiredException) { handleForcedOfflineByRevocation() @@ -3294,12 +4578,36 @@ class CompanionModel(application: Application) : AndroidViewModel(application) { val message = when { raw.contains("is not registered") -> "电脑端需要更新后重启" raw.contains("timeout", true) || raw.contains("timed out", true) -> "连接超时" + raw.contains("not currently connected to the relay", true) || + raw.contains("Host is offline", true) || + raw.contains("Bad Gateway", true) || + raw.contains("502") -> "电脑当前离线或未连接到 Dimo 云中继" raw.contains("Host health check", true) || raw.contains("/t/") -> "电脑端暂未响应,请确认电脑在线" raw.isBlank() -> "请求失败" - else -> raw + else -> raw.replace(Regex("vibex", RegexOption.IGNORE_CASE), "Dimo") } _state.update { it.copy(error = message, pairing = false) } scheduleAutoDismissNotice(3_500L) } } + +data class HandoffUiState( + val open: Boolean = false, + val conversationId: String = "", + val instances: List = emptyList(), + val loadingInstances: Boolean = false, + val instancesError: String? = null, + val targetEngine: String = "", + val targetInstanceId: String? = null, + val preview: EngineHandoffPreview? = null, + val busy: Boolean = false, + val error: String? = null, + val done: Boolean = false, +) + +data class SideChatUiState( + val sideChatId: String = java.util.UUID.randomUUID().toString(), + val messages: List = emptyList(), + val sending: Boolean = false, +) diff --git a/app/src/main/java/dev/vibex/companion/app/DesktopConnect.kt b/app/src/main/java/dev/vibex/companion/app/DesktopConnect.kt index 866b924..693c93a 100644 --- a/app/src/main/java/dev/vibex/companion/app/DesktopConnect.kt +++ b/app/src/main/java/dev/vibex/companion/app/DesktopConnect.kt @@ -1,25 +1,61 @@ package dev.vibex.companion.app +import dev.vibex.companion.AccountDesktop import dev.vibex.companion.AccountLinkException import dev.vibex.companion.AccountLinkFailure +import dev.vibex.companion.DiscoveredLanHost import dev.vibex.companion.HostUnreachableException import dev.vibex.companion.PairingException import java.io.IOException -enum class DesktopConnectRoute { Cloud, Lan } +data class ConnectedSasNotice( + val id: String, + val hostName: String, + val sasCode: String, +) + +sealed interface DesktopConnectTarget { + data class Account(val desktop: AccountDesktop) : DesktopConnectTarget + data class Lan(val host: DiscoveredLanHost) : DesktopConnectTarget + + val displayName: String + get() = when (this) { + is Account -> desktop.displayName + is Lan -> host.displayName + } + + val hostId: String? + get() = when (this) { + is Account -> desktop.hostId + is Lan -> host.hostId + } +} + +sealed interface LanSasInlineState { + data class Connecting(val host: DiscoveredLanHost) : LanSasInlineState + data class AwaitingApproval( + val host: DiscoveredLanHost, + val sasCode: String, + val hostName: String, + ) : LanSasInlineState +} -/** Steps of the account popup that finds the user's desktops and connects one in a single tap. */ +/** Steps of the popup that finds the user's desktops or LAN hosts and connects in a single tap. */ sealed interface DesktopConnectStage { data object Syncing : DesktopConnectStage data object Choosing : DesktopConnectStage - data class Connecting(val route: DesktopConnectRoute) : DesktopConnectStage + data class Connecting(val target: DesktopConnectTarget) : DesktopConnectStage - data class AwaitingApproval(val route: DesktopConnectRoute, val sasCode: String) : DesktopConnectStage + data class AwaitingApproval( + val target: DesktopConnectTarget, + val sasCode: String, + val hostName: String, + ) : DesktopConnectStage - /** [route] is null when the desktop list itself could not be loaded. */ - data class Failed(val message: String, val route: DesktopConnectRoute?) : DesktopConnectStage + /** [retryTarget] is null when the desktop list itself could not be loaded. */ + data class Failed(val message: String, val retryTarget: DesktopConnectTarget?) : DesktopConnectStage } data class DesktopConnectSheet( @@ -31,19 +67,18 @@ internal const val DESKTOP_SYNC_FAILED = "同步失败,请重试" internal const val DESKTOP_APPROVAL_REJECTED = "电脑端已拒绝连接" internal const val DESKTOP_APPROVAL_EXPIRED = "确认超时,请重试" private const val ACCOUNT_VERIFICATION_UNAVAILABLE = "暂时无法验证账号,请稍后重试" - private const val HOST_UNREACHABLE = "无法连接到电脑,请确认电脑端在线并已开启远程连接" internal fun desktopConnectErrorMessage(error: Throwable): String = when (error) { - is AccountLinkException -> when (error.failure) { - AccountLinkFailure.AccountMismatch -> "这台电脑登录的是其他 VibeX 账号" - AccountLinkFailure.HostAccountSignedOut -> "这台电脑未登录 VibeX 账号" - AccountLinkFailure.AccountTokenInvalid, - AccountLinkFailure.VerificationUnavailable, - -> ACCOUNT_VERIFICATION_UNAVAILABLE - } - is HostUnreachableException, is IOException -> HOST_UNREACHABLE - is PairingException -> error.message ?: HOST_UNREACHABLE + is AccountLinkException -> when (error.failure) { + AccountLinkFailure.AccountMismatch -> "这台电脑登录的是其他 Dimo 账号" + AccountLinkFailure.HostAccountSignedOut -> "这台电脑未登录 Dimo 账号" + AccountLinkFailure.AccountTokenInvalid, + AccountLinkFailure.VerificationUnavailable, + -> ACCOUNT_VERIFICATION_UNAVAILABLE + } + is HostUnreachableException, is IOException -> HOST_UNREACHABLE + is PairingException -> error.message ?: HOST_UNREACHABLE else -> error.message ?: HOST_UNREACHABLE } diff --git a/app/src/main/java/dev/vibex/companion/app/MainActivity.kt b/app/src/main/java/dev/vibex/companion/app/MainActivity.kt index 9476c1d..04f061f 100644 --- a/app/src/main/java/dev/vibex/companion/app/MainActivity.kt +++ b/app/src/main/java/dev/vibex/companion/app/MainActivity.kt @@ -18,9 +18,11 @@ import dev.vibex.companion.app.monitor.SystemIslandOverlayController import dev.vibex.companion.app.monitor.SystemNotifier import dev.vibex.companion.app.ui.CompanionApp import dev.vibex.companion.app.ui.theme.CompanionTheme +import dev.vibex.companion.app.update.AppUpdateManager class MainActivity : ComponentActivity() { private val model: CompanionModel by viewModels() + private val updateManager by lazy { AppUpdateManager.getInstance(this) } private val notificationPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), ) {} @@ -44,6 +46,12 @@ class MainActivity : ComponentActivity() { super.onStart() SystemIslandOverlayController.setAppForeground(this, true) model.onAppForegroundChanged(true) + updateManager.checkIfDue(fromBackground = false) + } + + override fun onResume() { + super.onResume() + updateManager.onActivityResumed() } override fun onStop() { @@ -68,6 +76,11 @@ class MainActivity : ComponentActivity() { } private fun handleIntentExtras(intent: Intent?) { + if (intent?.getBooleanExtra(AppUpdateManager.EXTRA_OPEN_UPDATE_DIALOG, false) == true) { + intent.removeExtra(AppUpdateManager.EXTRA_OPEN_UPDATE_DIALOG) + updateManager.openUpdateDialog() + return + } val notifAction = intent?.getStringExtra("vibex_notif_action")?.takeIf { it.isNotBlank() } if (notifAction != null) { val convId = intent.getStringExtra("vibex_notif_conv_id").orEmpty() @@ -99,7 +112,7 @@ class MainActivity : ComponentActivity() { return } val raw = intent?.getStringExtra("pairing_invitation")?.takeIf { it.isNotBlank() } - ?: intent?.dataString?.takeIf { it.startsWith("vibex-pairing:", ignoreCase = true) } + ?: intent?.dataString?.takeIf { it.startsWith("vibex-pairing:", ignoreCase = true) || it.startsWith("dimo-pairing:", ignoreCase = true) } ?: return intent?.removeExtra("pairing_invitation") model.pairFromRaw(raw) diff --git a/app/src/main/java/dev/vibex/companion/app/data/ModelPreferencesStore.kt b/app/src/main/java/dev/vibex/companion/app/data/ModelPreferencesStore.kt new file mode 100644 index 0000000..3400354 --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/data/ModelPreferencesStore.kt @@ -0,0 +1,79 @@ +package dev.vibex.companion.app.data + +import android.content.Context +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update + +class ModelPreferencesStore(context: Context) { + private val prefs = context.getSharedPreferences("vibex_model_prefs", Context.MODE_PRIVATE) + + private val _favoriteIds = MutableStateFlow(loadSet(KEY_FAVORITES)) + val favoriteIds: StateFlow> = _favoriteIds + + private val _hiddenIds = MutableStateFlow(loadSet(KEY_HIDDEN)) + val hiddenIds: StateFlow> = _hiddenIds + + private val _customModelsByAgent = MutableStateFlow(loadCustomMap()) + val customModelsByAgent: StateFlow>> = _customModelsByAgent + + fun toggleFavorite(modelId: String) { + val next = _favoriteIds.value.toMutableSet().apply { + if (!add(modelId)) remove(modelId) + } + _favoriteIds.value = next + saveSet(KEY_FAVORITES, next) + } + + fun toggleHidden(modelId: String) { + val next = _hiddenIds.value.toMutableSet().apply { + if (!add(modelId)) remove(modelId) + } + _hiddenIds.value = next + saveSet(KEY_HIDDEN, next) + } + + fun addCustomModel(agentId: String, modelId: String) { + val trimmed = modelId.trim() + if (trimmed.isEmpty()) return + _customModelsByAgent.update { current -> + val updated = (listOf(trimmed) + current[agentId].orEmpty()).distinct() + val next = current + (agentId to updated) + saveCustomMap(next) + next + } + } + + private fun loadSet(key: String): Set = + prefs.getStringSet(key, emptySet()).orEmpty().filter { it.isNotBlank() }.toSet() + + private fun saveSet(key: String, values: Set) { + prefs.edit().putStringSet(key, values).apply() + } + + private fun loadCustomMap(): Map> { + val raw = prefs.getString(KEY_CUSTOM, "").orEmpty() + if (raw.isBlank()) return emptyMap() + return raw.lineSequence() + .mapNotNull { line -> + val parts = line.split('\t', limit = 2) + if (parts.size == 2 && parts[0].isNotBlank() && parts[1].isNotBlank()) { + parts[0] to parts[1].split(',').map { it.trim() }.filter { it.isNotEmpty() } + } else null + } + .toMap() + } + + private fun saveCustomMap(map: Map>) { + val encoded = map.entries + .filter { it.key.isNotBlank() && it.value.isNotEmpty() } + .joinToString("\n") { (agent, models) -> "$agent\t${models.joinToString(",")}" } + prefs.edit().putString(KEY_CUSTOM, encoded).apply() + } + + companion object { + private const val KEY_FAVORITES = "vibex.favoriteModelIDs" + private const val KEY_HIDDEN = "vibex.hiddenModelIDs" + private const val KEY_CUSTOM = "vibex.customModelsByAgent" + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/data/ProfileStore.kt b/app/src/main/java/dev/vibex/companion/app/data/ProfileStore.kt index 3828960..72111f8 100644 --- a/app/src/main/java/dev/vibex/companion/app/data/ProfileStore.kt +++ b/app/src/main/java/dev/vibex/companion/app/data/ProfileStore.kt @@ -7,6 +7,7 @@ import dev.vibex.companion.asText import dev.vibex.companion.asArray import dev.vibex.companion.asNumber import dev.vibex.companion.encodeObject +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 java.io.File @@ -20,6 +21,10 @@ class ProfileStore(context: Context) { val root = JsonValue.parse(file.readText()) as? JsonValue.Object ?: return StoredState() val selected = root.value["selected"]?.asText() val appearance = Appearance.from(root.value["appearance"]?.asText()) + val language = AppLanguage.from(root.value["language"]?.asText()) + val confirmHighRiskApproval = (root.value["confirmHighRiskApproval"] as? JsonValue.Bool)?.value ?: true + val muteForegroundNotifications = (root.value["muteForegroundNotifications"] as? JsonValue.Bool)?.value ?: true + val customRelayOrigin = root.value["customRelayOrigin"]?.asText()?.trim().orEmpty() val accent = AccentChoice.from(root.value["accent"]?.asText()) val streamDisplay = StreamDisplayPrefs.from(root.value["streamDisplay"]) val profiles = root.value["profiles"]?.asArray()?.value.orEmpty().mapNotNull { item -> @@ -40,7 +45,17 @@ class ProfileStore(context: Context) { selectedProjectId = obj.value["selectedProjectId"]?.asText(), ) } - return StoredState(selected, profiles, appearance, streamDisplay, accent) + return StoredState( + selectedHostId = selected, + profiles = profiles, + appearance = appearance, + streamDisplay = streamDisplay, + accent = accent, + language = language, + confirmHighRiskApproval = confirmHighRiskApproval, + muteForegroundNotifications = muteForegroundNotifications, + customRelayOrigin = customRelayOrigin, + ) } @Synchronized @@ -50,6 +65,10 @@ class ProfileStore(context: Context) { "selected" to state.selectedHostId, "appearance" to state.appearance.id, "accent" to state.accent.id, + "language" to state.language.id, + "confirmHighRiskApproval" to state.confirmHighRiskApproval, + "muteForegroundNotifications" to state.muteForegroundNotifications, + "customRelayOrigin" to state.customRelayOrigin, "streamDisplay" to state.streamDisplay.toMap(), "profiles" to state.profiles.map { profile -> mapOf( @@ -76,4 +95,8 @@ data class StoredState( val appearance: Appearance = Appearance.System, val streamDisplay: StreamDisplayPrefs = StreamDisplayPrefs(), val accent: AccentChoice = AccentChoice.Ink, + val language: AppLanguage = AppLanguage.ZhHans, + val confirmHighRiskApproval: Boolean = true, + val muteForegroundNotifications: Boolean = true, + val customRelayOrigin: String = "", ) diff --git a/app/src/main/java/dev/vibex/companion/app/data/VibeXAccountRepository.kt b/app/src/main/java/dev/vibex/companion/app/data/VibeXAccountRepository.kt index 23546e6..6498f46 100644 --- a/app/src/main/java/dev/vibex/companion/app/data/VibeXAccountRepository.kt +++ b/app/src/main/java/dev/vibex/companion/app/data/VibeXAccountRepository.kt @@ -6,6 +6,7 @@ import dev.vibex.companion.AccountAuthRequests import dev.vibex.companion.AccountDesktop import dev.vibex.companion.AccountDesktops import dev.vibex.companion.AssignedRelayServer +import dev.vibex.companion.PairingClient import dev.vibex.companion.asArray import dev.vibex.companion.asBool import dev.vibex.companion.asNumber @@ -14,6 +15,9 @@ import dev.vibex.companion.asText import dev.vibex.companion.encodeObject import dev.vibex.remote.v1.JsonValue import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import okhttp3.Cookie @@ -39,12 +43,12 @@ data class VibeXAccountUser( val resolvedDisplayName: String get() = displayName.trim().ifEmpty { username.trim().ifEmpty { - email.substringBefore("@").trim().ifEmpty { "VibeX User" } + email.substringBefore("@").trim().ifEmpty { "Dimo User" } } } val avatarInitial: String - get() = resolvedDisplayName.firstOrNull()?.uppercaseChar()?.toString() ?: "V" + get() = resolvedDisplayName.firstOrNull()?.uppercaseChar()?.toString() ?: "D" val accountIdentifier: String get() = username.trim().ifEmpty { email.trim() } @@ -115,13 +119,16 @@ data class VibeXAccountOverview( val hasActiveCreditsOrTier: Boolean get() = user.tier != "regular" || balanceMicro > 0L || activeGrants.isNotEmpty() + val canUseCloudRelay: Boolean + get() = relayPermission ?: hasActiveCreditsOrTier + val planDisplayName: String get() = when (user.tier) { - "subscriber" -> "VibeX 订阅会员" - "sponsor" -> "VibeX 赞助会员" - "beta" -> "VibeX Beta 计划" - "admin" -> "VibeX 管理员" - else -> if (hasActiveCreditsOrTier) "按量付费 · 已激活" else "VibeX 免费版" + "subscriber" -> "Dimo 订阅会员" + "sponsor" -> "Dimo 赞助会员" + "beta" -> "Dimo Beta 计划" + "admin" -> "Dimo 管理员" + else -> if (hasActiveCreditsOrTier) "按量付费 · 已激活" else "Dimo 免费版" } } @@ -154,7 +161,13 @@ class VibeXAccountException( class VibeXAccountRepository(context: Context) { companion object { - const val SITE_BASE_URL = "https://vibex.xforever.xin" + val SITE_BASE_URL: String = + (System.getenv("DIMO_SITE_URL") ?: System.getenv("VIBEX_SITE_URL")) + ?.trim() + ?.trimEnd('/') + ?.takeIf { it.isNotEmpty() } + ?: "https://dimo-ai.com" + val DEFAULT_OFFICIAL_RELAY_BASE: String = PairingClient.DEFAULT_OFFICIAL_RELAY_BASE const val PRIVACY_PATH = "/docs/privacy" const val LOGIN_CODE_COOLDOWN_SECONDS = 60 private const val PREF_TOKEN_KEY = "vibex.account.token" @@ -181,6 +194,11 @@ class VibeXAccountRepository(context: Context) { .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .build() + private val relayProbeHttp = http.newBuilder() + .connectTimeout(1_500, TimeUnit.MILLISECONDS) + .readTimeout(1_500, TimeUnit.MILLISECONDS) + .callTimeout(2_500, TimeUnit.MILLISECONDS) + .build() fun getToken(): String? = prefs.getString(PREF_TOKEN_KEY, null)?.trim()?.takeIf { it.isNotEmpty() } @@ -230,7 +248,7 @@ class VibeXAccountRepository(context: Context) { } private fun startDeviceLogin(client: OkHttpClient): VibeXDeviceLogin { - val deviceName = "${Build.MANUFACTURER} ${Build.MODEL}".trim().ifEmpty { "VibeX Android" } + val deviceName = "${Build.MANUFACTURER} ${Build.MODEL}".trim().ifEmpty { "Dimo Android" } val body = AccountAuthRequests.deviceStart(deviceName) val obj = requestObject("/api/auth/desktop/start", "POST", body, token = null, client = client) return VibeXDeviceLogin( @@ -339,9 +357,61 @@ class VibeXAccountRepository(context: Context) { ) } - suspend fun fetchDesktops(): List = withContext(Dispatchers.IO) { + suspend fun probeRelayHostOnline(relayBase: String, hostId: String): Boolean = withContext(Dispatchers.IO) { + val cleanBase = relayBase.trim() + val rawId = AccountDesktops.rawHostId(hostId) + if (cleanBase.isEmpty() || rawId.isEmpty() || AccountDesktops.isPlaceholderHostId(rawId)) { + return@withContext false + } + val url = "${AccountDesktops.tenantOrigin(cleanBase, rawId)}/health" + runCatching { + val request = Request.Builder().url(url).get().build() + relayProbeHttp.newCall(request).execute().use { resp -> + resp.code in 200..299 + } + }.getOrDefault(false) + } + + suspend fun fetchProbedDesktops(relayBase: String? = null): List = withContext(Dispatchers.IO) { val token = getToken() ?: throw VibeXAccountException("signed_out") - AccountDesktops.parse(requestObject("/api/account/desktop/host-configs", "GET", null, token = token)) + val parsed = AccountDesktops.parse(requestObject("/api/account/desktop/host-configs", "GET", null, token = token)) + val cleanRelay = relayBase?.trim().orEmpty() + if (cleanRelay.isEmpty() || parsed.isEmpty()) { + parsed + } else { + coroutineScope { + parsed.map { desktop -> + async { + desktop.copy(cloudOnline = probeRelayHostOnline(cleanRelay, desktop.hostId)) + } + }.awaitAll() + } + } + } + + suspend fun fetchDesktops( + relayBase: String? = null, + onlineLanHostIds: Set = emptySet(), + pairedHostIds: Set = emptySet(), + ): List = withContext(Dispatchers.IO) { + val probed = fetchProbedDesktops(relayBase) + AccountDesktops.deduplicate( + desktops = probed, + onlineLanHostIds = onlineLanHostIds, + pairedHostIds = pairedHostIds, + ) + } + + suspend fun deleteHostConfig(hostId: String) = withContext(Dispatchers.IO) { + val rawId = AccountDesktops.rawHostId(hostId) + if (rawId.isEmpty()) return@withContext + for (candidate in listOf("host:$rawId", rawId).distinct()) { + val token = getToken() ?: return@withContext + val body = encodeObject(mapOf("hostId" to candidate)) + runCatching { + requestObject("/api/account/desktop/host-configs", "DELETE", body, token = token) + } + } } suspend fun fetchSavedHosts(): List = withContext(Dispatchers.IO) { @@ -406,7 +476,7 @@ class VibeXAccountRepository(context: Context) { syncKey = o.value["syncKey"]?.asText()?.trim().orEmpty(), profileId = profileId.ifEmpty { origin }, hostId = o.value["hostId"]?.asText()?.trim().orEmpty(), - name = o.value["name"]?.asText()?.trim().orEmpty().ifEmpty { "VibeX 电脑" }, + name = o.value["name"]?.asText()?.trim().orEmpty().ifEmpty { "Dimo 电脑" }, origin = origin, provisionKind = o.value["provisionKind"]?.asText()?.trim().orEmpty().ifEmpty { "http" }, deviceId = cred?.value?.get("deviceId")?.asText()?.trim().orEmpty(), diff --git a/app/src/main/java/dev/vibex/companion/app/monitor/CompanionMonitorService.kt b/app/src/main/java/dev/vibex/companion/app/monitor/CompanionMonitorService.kt index 949cbfb..022655e 100644 --- a/app/src/main/java/dev/vibex/companion/app/monitor/CompanionMonitorService.kt +++ b/app/src/main/java/dev/vibex/companion/app/monitor/CompanionMonitorService.kt @@ -45,9 +45,18 @@ import dev.vibex.companion.app.ui.DynamicIslandOverlay import dev.vibex.companion.app.ui.theme.Appearance import dev.vibex.companion.app.ui.theme.AccentChoice import dev.vibex.companion.app.ui.theme.CompanionTheme +import dev.vibex.companion.app.update.AppUpdateManager import kotlinx.coroutines.flow.MutableStateFlow class CompanionMonitorService : Service() { + private val updatePollHandler = Handler(Looper.getMainLooper()) + private val updatePollRunnable = object : Runnable { + override fun run() { + AppUpdateManager.getInstance(this@CompanionMonitorService).checkIfDue(fromBackground = true) + updatePollHandler.postDelayed(this, UPDATE_POLL_INTERVAL_MS) + } + } + override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { @@ -55,7 +64,7 @@ class CompanionMonitorService : Service() { val manager = getSystemService(NotificationManager::class.java) if (Build.VERSION.SDK_INT >= 26) { manager.createNotificationChannel( - NotificationChannel(CHANNEL, "VibeX 后台实时同步", NotificationManager.IMPORTANCE_LOW).apply { + NotificationChannel(CHANNEL, "Dimo 后台实时同步", NotificationManager.IMPORTANCE_LOW).apply { description = "保持后台连接以驱动系统灵动岛与即时通知" setShowBadge(false) }, @@ -71,7 +80,7 @@ class CompanionMonitorService : Service() { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) val notification: Notification = NotificationCompat.Builder(this, CHANNEL) - .setContentTitle("VibeX 后台守护中") + .setContentTitle("Dimo 后台守护中") .setContentText("正在实时同步 AI 任务进度与通知") .setSmallIcon(R.mipmap.ic_launcher_round) .setOngoing(true) @@ -79,15 +88,19 @@ class CompanionMonitorService : Service() { .setContentIntent(pendingIntent) .build() startForeground(1, notification) + updatePollHandler.postDelayed(updatePollRunnable, UPDATE_POLL_INITIAL_DELAY_MS) } override fun onDestroy() { + updatePollHandler.removeCallbacks(updatePollRunnable) SystemIslandOverlayController.detach() super.onDestroy() } companion object { private const val CHANNEL = "vibex-monitor" + private const val UPDATE_POLL_INITIAL_DELAY_MS = 60_000L + private const val UPDATE_POLL_INTERVAL_MS = 15 * 60 * 1000L fun start(context: Context) { runCatching { diff --git a/app/src/main/java/dev/vibex/companion/app/monitor/SystemNotifier.kt b/app/src/main/java/dev/vibex/companion/app/monitor/SystemNotifier.kt index b6b25a1..6279103 100644 --- a/app/src/main/java/dev/vibex/companion/app/monitor/SystemNotifier.kt +++ b/app/src/main/java/dev/vibex/companion/app/monitor/SystemNotifier.kt @@ -89,7 +89,7 @@ object SystemNotifier { val manager = context.getSystemService(NotificationManager::class.java) ?: return val alertsChannel = NotificationChannel( CHANNEL_ALERTS, - "VibeX 即时通知与审批提醒", + "Dimo 即时通知与审批提醒", NotificationManager.IMPORTANCE_HIGH, ).apply { description = "会话完成、执行异常、新会话及权限审批横幅提醒" @@ -98,7 +98,7 @@ object SystemNotifier { } val liveChannel = NotificationChannel( CHANNEL_LIVE, - "VibeX 灵动岛与实时任务进度", + "Dimo 灵动岛与实时任务进度", NotificationManager.IMPORTANCE_DEFAULT, ).apply { description = "实时同步 AI Agent 思考、代码开发、验证与完成进度" @@ -109,7 +109,7 @@ object SystemNotifier { } val statusChannel = NotificationChannel( CHANNEL_STATUS, - "VibeX 状态通知", + "Dimo 状态通知", NotificationManager.IMPORTANCE_DEFAULT, ).apply { description = "电脑连接状态与系统提示" diff --git a/app/src/main/java/dev/vibex/companion/app/net/EventSocket.kt b/app/src/main/java/dev/vibex/companion/app/net/EventSocket.kt index 79f7215..eb97cba 100644 --- a/app/src/main/java/dev/vibex/companion/app/net/EventSocket.kt +++ b/app/src/main/java/dev/vibex/companion/app/net/EventSocket.kt @@ -1,6 +1,7 @@ package dev.vibex.companion.app.net import android.util.Base64 +import android.util.Log import dev.vibex.companion.E2eeSessionManager import dev.vibex.companion.asObject import dev.vibex.companion.asText @@ -18,11 +19,13 @@ import java.util.concurrent.TimeUnit class EventSocket( private val http: OkHttpClient = OkHttpClient.Builder() .socketFactory(TcpNoDelaySocketFactory) + .connectTimeout(10, TimeUnit.SECONDS) .pingInterval(20, TimeUnit.SECONDS) .readTimeout(0, TimeUnit.MILLISECONDS) .build(), ) { private var socket: WebSocket? = null + @Volatile private var generation = 0 @Volatile private var activeE2eeSession: E2eeSessionManager.SessionState? = null @@ -37,6 +40,52 @@ class EventSocket( onEvent: (String, RemoteEvent) -> Unit, onSnapshot: (String, JsonValue) -> Unit, onClosed: (String?) -> Unit, + ) { + connectInternal( + origin = origin, + token = token, + allowE2eeRetry = true, + onOpen = onOpen, + onPongRttMs = onPongRttMs, + onEvent = onEvent, + onSnapshot = onSnapshot, + onClosed = onClosed, + ) + } + + private fun bootstrapE2eeSession(origin: String) { + val originKey = E2eeSessionManager.originKey(origin) + runCatching { + val req = Request.Builder() + .url("$originKey/api/v1/e2ee/handshake") + .header(E2eeSessionManager.HEADER_CLIENT_PUB, E2eeSessionManager.clientPublicKeyBase64) + .get() + .build() + http.newBuilder() + .connectTimeout(5, TimeUnit.SECONDS) + .readTimeout(5, TimeUnit.SECONDS) + .build() + .newCall(req) + .execute() + .use { resp -> + E2eeSessionManager.ingestHandshake( + originKey, + resp.header(E2eeSessionManager.HEADER_SESSION), + resp.header(E2eeSessionManager.HEADER_SERVER_PUB), + ) + } + } + } + + private fun connectInternal( + origin: String, + token: String, + allowE2eeRetry: Boolean, + onOpen: () -> Unit, + onPongRttMs: (Long) -> Unit, + onEvent: (String, RemoteEvent) -> Unit, + onSnapshot: (String, JsonValue) -> Unit, + onClosed: (String?) -> Unit, ) { val session = ++generation socket?.cancel() @@ -46,9 +95,9 @@ class EventSocket( val e2ee = E2eeSessionManager.session(origin) activeE2eeSession = e2ee val protocols = if (e2ee != null) { - "vibex.v1, vibex.token.$encoded, vibex.e2ee.${e2ee.sessionId}" + "dimo.v1, dimo.token.$encoded, dimo.e2ee.${e2ee.sessionId}" } else { - "vibex.v1, vibex.token.$encoded" + "dimo.v1, dimo.token.$encoded" } val reqBuilder = Request.Builder() .url(ws) @@ -70,6 +119,7 @@ class EventSocket( socket = http.newWebSocket(request, object : WebSocketListener() { private fun live(): Boolean = session == generation override fun onOpen(webSocket: WebSocket, response: Response) { + Log.i("VxSocket", "onOpen origin=$origin http=${response.code}") if (live()) { E2eeSessionManager.ingestHandshake( origin, @@ -129,10 +179,34 @@ class EventSocket( } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { - if (live()) onClosed(t.message) + val code = response?.code + Log.w("VxSocket", "onFailure live=${live()} origin=$origin http=$code err=${t::class.simpleName}: ${t.message}") + if (!live()) return + if (allowE2eeRetry && e2ee != null && (code == 401 || code == 412)) { + Log.i("VxSocket", "clearing stale E2EE session and retrying ws origin=$origin http=$code") + E2eeSessionManager.clearSession(origin) + bootstrapE2eeSession(origin) + connectInternal( + origin = origin, + token = token, + allowE2eeRetry = false, + onOpen = onOpen, + onPongRttMs = onPongRttMs, + onEvent = onEvent, + onSnapshot = onSnapshot, + onClosed = onClosed, + ) + return + } + if (code == 401) { + onClosed("auth") + } else { + onClosed(t.message) + } } override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + Log.w("VxSocket", "onClosed live=${live()} origin=$origin code=$code reason=$reason") if (live()) onClosed(reason) } }) diff --git a/app/src/main/java/dev/vibex/companion/app/net/OkHttpTransport.kt b/app/src/main/java/dev/vibex/companion/app/net/OkHttpTransport.kt index 3dc9a22..c75e7fa 100644 --- a/app/src/main/java/dev/vibex/companion/app/net/OkHttpTransport.kt +++ b/app/src/main/java/dev/vibex/companion/app/net/OkHttpTransport.kt @@ -3,7 +3,7 @@ package dev.vibex.companion.app.net import dev.vibex.companion.E2eeSessionManager import dev.vibex.companion.HttpExchange import dev.vibex.companion.HttpTransport -import dev.vibex.companion.PairingClient +import dev.vibex.companion.requestReadTimeoutMs import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request @@ -31,17 +31,20 @@ object TcpNoDelaySocketFactory : SocketFactory() { class OkHttpTransport( private val client: OkHttpClient = OkHttpClient.Builder() .socketFactory(TcpNoDelaySocketFactory) - .connectTimeout(5, TimeUnit.SECONDS) + .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(), ) : HttpTransport { private val fastLanClient: OkHttpClient = client.newBuilder() - .connectTimeout(900, TimeUnit.MILLISECONDS) + .connectTimeout(1_500, TimeUnit.MILLISECONDS) + .readTimeout(15, TimeUnit.SECONDS) .build() private fun isLocalOrPrivateLan(url: String): Boolean { val lower = url.lowercase() + if (lower.contains("/t/")) return false return lower.startsWith("http://127.") || + lower.startsWith("http://10.0.2.2") || lower.startsWith("http://localhost") || lower.startsWith("http://192.168.") || lower.startsWith("http://10.") || @@ -49,9 +52,11 @@ class OkHttpTransport( } override fun execute(method: String, url: String, headers: Map, body: String?): HttpExchange { + val hadActiveE2ee = E2eeSessionManager.isE2eeActive(url) val first = executeOnce(method, url, headers, body, allowBootstrap = true) - if (first.status == 412) { - return executeOnce(method, url, headers, body, allowBootstrap = false) + if (first.status == 412 || (first.status == 401 && hadActiveE2ee)) { + E2eeSessionManager.clearSession(url) + return executeOnce(method, url, headers, body, allowBootstrap = true) } return first } @@ -73,7 +78,11 @@ class OkHttpTransport( .header(E2eeSessionManager.HEADER_CLIENT_PUB, E2eeSessionManager.clientPublicKeyBase64) .get() .build() - (if (isPrivateLan) fastLanClient else client).newCall(hsReq).execute().use { hsResp -> + val hsClient = (if (isPrivateLan) fastLanClient else client) + .newBuilder() + .readTimeout(if (isPrivateLan) 3_000L else 8_000L, TimeUnit.MILLISECONDS) + .build() + hsClient.newCall(hsReq).execute().use { hsResp -> E2eeSessionManager.ingestHandshake( originKey, hsResp.header(E2eeSessionManager.HEADER_SESSION), @@ -125,7 +134,11 @@ class OkHttpTransport( if (method == "DELETE" && wireBody != null) { builder.method("DELETE", wireBody!!.toRequestBody(media)) } - val activeClient = if (isPrivateLan) fastLanClient else client + val readTimeoutMs = requestReadTimeoutMs(method, isPrivateLan).toLong() + val activeClient = (if (isPrivateLan) fastLanClient else client) + .newBuilder() + .readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS) + .build() activeClient.newCall(builder.build()).execute().use { response -> val updatedSession = E2eeSessionManager.ingestHandshake( originKey, diff --git a/app/src/main/java/dev/vibex/companion/app/ui/AppNavigation.kt b/app/src/main/java/dev/vibex/companion/app/ui/AppNavigation.kt new file mode 100644 index 0000000..717ad0f --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/AppNavigation.kt @@ -0,0 +1,433 @@ +package dev.vibex.companion.app.ui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.spring +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.animation.shrinkHorizontally +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowLeft +import androidx.compose.material.icons.outlined.BarChart +import androidx.compose.material.icons.outlined.ChatBubbleOutline +import androidx.compose.material.icons.outlined.Folder +import androidx.compose.material.icons.outlined.Groups +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.BarChart +import androidx.compose.material.icons.rounded.ChatBubble +import androidx.compose.material.icons.rounded.Code +import androidx.compose.material.icons.rounded.Groups +import androidx.compose.material.icons.rounded.Settings +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.Route +import dev.vibex.companion.app.ui.theme.PlexMono +import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.app.ui.theme.l + +val BOTTOM_DOCK_CLEARANCE = 78.dp + +enum class AppDestination( + val title: String, + val englishTitle: String, + val icon: ImageVector, + val selectedIcon: ImageVector, +) { + Conversations("会话", "Chats", Icons.Outlined.ChatBubbleOutline, Icons.Rounded.ChatBubble), + Status("看板", "Board", Icons.Outlined.BarChart, Icons.Rounded.BarChart), + Collaboration("协作", "Team", Icons.Outlined.Groups, Icons.Rounded.Groups), + Settings("设置", "Settings", Icons.Outlined.Settings, Icons.Rounded.Settings); + + @Composable + fun localizedTitle(): String = l(title, englishTitle) +} + +val Route.destination: AppDestination + get() = when (this) { + Route.Status -> AppDestination.Status + Route.Collaboration -> AppDestination.Collaboration + is Route.Settings -> AppDestination.Settings + Route.Conversations, + Route.NewThread, + Route.Folders, + Route.ManualPair, + is Route.Timeline, + -> AppDestination.Conversations + } + +fun CompanionModel.navigate(to: AppDestination) = when (to) { + AppDestination.Conversations -> go(Route.Conversations) + AppDestination.Status -> go(Route.Status) + AppDestination.Collaboration -> go(Route.Collaboration) + AppDestination.Settings -> go(Route.Settings()) +} + +/** + * 1:1 port of iOS `FloatingWorkspaceCapsuleDock` (`MainWorkspaceView.swift`). + * Floating bottom capsule dock with contextual center `+` action on the Conversations hub. + */ +@Composable +fun FloatingWorkspaceCapsuleDock( + selected: AppDestination, + collabUnreadCount: Int, + onSelect: (AppDestination) -> Unit, + onNewThread: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = VibexTheme.colors + val haptic = LocalHapticFeedback.current + val capsuleShape = RoundedCornerShape(50) + + Box( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 20.dp) + .padding(bottom = 8.dp), + contentAlignment = Alignment.Center, + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .height(58.dp) + .shadow( + elevation = if (colors.isDark) 14.dp else 10.dp, + shape = capsuleShape, + ambientColor = Color.Black.copy(alpha = if (colors.isDark) 0.30f else 0.08f), + spotColor = Color.Black.copy(alpha = if (colors.isDark) 0.36f else 0.12f), + ) + .clip(capsuleShape) + .background(colors.card.copy(alpha = 0.96f)) + .border(0.75.dp, colors.stroke, capsuleShape) + .padding(horizontal = 6.dp, vertical = 5.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + DockTabItem( + destination = AppDestination.Conversations, + isSelected = selected == AppDestination.Conversations, + badgeCount = 0, + onClick = { + if (selected != AppDestination.Conversations) { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + } + onSelect(AppDestination.Conversations) + }, + modifier = Modifier.weight(1f), + ) + + DockTabItem( + destination = AppDestination.Status, + isSelected = selected == AppDestination.Status, + badgeCount = 0, + onClick = { + if (selected != AppDestination.Status) { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + } + onSelect(AppDestination.Status) + }, + modifier = Modifier.weight(1f), + ) + + AnimatedVisibility( + visible = selected == AppDestination.Conversations, + enter = expandHorizontally( + animationSpec = spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessMediumLow), + expandFrom = Alignment.CenterHorizontally, + ) + scaleIn( + animationSpec = spring(dampingRatio = 0.80f, stiffness = Spring.StiffnessMediumLow), + ) + fadeIn(), + exit = shrinkHorizontally( + animationSpec = spring(dampingRatio = 0.86f, stiffness = Spring.StiffnessMedium), + shrinkTowards = Alignment.CenterHorizontally, + ) + scaleOut() + fadeOut(), + ) { + Box( + modifier = Modifier + .padding(horizontal = 4.dp) + .size(42.dp) + .clip(CircleShape) + .background(colors.textPrimary) + .clickable { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + onNewThread() + }, + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.Add, + contentDescription = "新建会话", + tint = colors.bg, + modifier = Modifier.size(22.dp), + ) + } + } + + DockTabItem( + destination = AppDestination.Collaboration, + isSelected = selected == AppDestination.Collaboration, + badgeCount = collabUnreadCount, + onClick = { + if (selected != AppDestination.Collaboration) { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + } + onSelect(AppDestination.Collaboration) + }, + modifier = Modifier.weight(1f), + ) + + DockTabItem( + destination = AppDestination.Settings, + isSelected = selected == AppDestination.Settings, + badgeCount = 0, + onClick = { + if (selected != AppDestination.Settings) { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + } + onSelect(AppDestination.Settings) + }, + modifier = Modifier.weight(1f), + ) + } + } +} + +@Composable +private fun DockTabItem( + destination: AppDestination, + isSelected: Boolean, + badgeCount: Int, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = VibexTheme.colors + val pillShape = RoundedCornerShape(50) + val bgColor = if (isSelected) { + colors.textPrimary.copy(alpha = if (colors.isDark) 0.14f else 0.09f) + } else { + Color.Transparent + } + val fgColor = if (isSelected) colors.textPrimary else colors.textSecondary + + Column( + modifier = modifier + .fillMaxHeight() + .clip(pillShape) + .background(bgColor) + .selectable(selected = isSelected, role = Role.Tab, onClick = onClick), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box { + Icon( + imageVector = if (isSelected) destination.selectedIcon else destination.icon, + contentDescription = destination.localizedTitle(), + tint = fgColor, + modifier = Modifier.size(20.dp), + ) + if (badgeCount > 0) { + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = 7.dp, y = (-3).dp) + .clip(CircleShape) + .background(colors.danger) + .padding(horizontal = if (badgeCount > 9) 3.5.dp else 4.dp, vertical = 0.5.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = if (badgeCount > 99) "99+" else "$badgeCount", + style = TextStyle( + fontSize = 8.5.sp, + fontWeight = FontWeight.Bold, + fontFeatureSettings = "tnum", + color = Color.White, + ), + ) + } + } + } + Text( + text = destination.localizedTitle(), + fontSize = 10.5.sp, + fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium, + color = fgColor, + maxLines = 1, + ) + } +} + +/** + * 40dp circular back button for Level-2 screens (`NewThreadScreen`, `TimelineScreen`). + */ +@Composable +fun FloatingCircleBackButton( + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = VibexTheme.colors + Box( + modifier = modifier + .size(40.dp) + .shadow( + elevation = if (colors.isDark) 4.dp else 2.dp, + shape = CircleShape, + ambientColor = Color.Black.copy(alpha = 0.06f), + spotColor = Color.Black.copy(alpha = 0.08f), + ) + .clip(CircleShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, CircleShape) + .clickable(onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowLeft, + contentDescription = "返回", + tint = colors.textPrimary, + modifier = Modifier.size(22.dp), + ) + } +} + +/** + * 40dp top-right dual-action capsule (`Diff` | `Files`) for Level-2 workspace screens. + */ +@Composable +fun WorkspaceDualToolsCapsule( + diffCount: Int = 0, + additionCount: Long = 0L, + deletionCount: Long = 0L, + enabled: Boolean = true, + onOpenDiff: () -> Unit, + onOpenFiles: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = VibexTheme.colors + val shape = RoundedCornerShape(50) + + Row( + modifier = modifier + .height(40.dp) + .shadow( + elevation = if (colors.isDark) 4.dp else 2.dp, + shape = shape, + ambientColor = Color.Black.copy(alpha = 0.06f), + spotColor = Color.Black.copy(alpha = 0.08f), + ) + .clip(shape) + .background(colors.card) + .border(0.6.dp, colors.stroke, shape), + verticalAlignment = Alignment.CenterVertically, + ) { + Row( + modifier = Modifier + .fillMaxHeight() + .clickable(enabled = enabled, onClick = onOpenDiff) + .padding(horizontal = 11.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon( + imageVector = Icons.Rounded.Code, + contentDescription = "查看代码变更", + tint = if (enabled) colors.textPrimary else colors.textTertiary, + modifier = Modifier.size(17.dp), + ) + if (additionCount > 0L || deletionCount > 0L) { + if (additionCount > 0L) { + Text( + text = "+$additionCount", + style = TextStyle( + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.pass, + ), + ) + } + if (deletionCount > 0L) { + Text( + text = "-$deletionCount", + style = TextStyle( + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.danger, + ), + ) + } + } else if (diffCount > 0) { + Text( + text = "$diffCount", + style = TextStyle( + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.accent, + ), + ) + } + } + + Box( + modifier = Modifier + .width(0.6.dp) + .height(18.dp) + .background(colors.stroke), + ) + + Box( + modifier = Modifier + .fillMaxHeight() + .clickable(enabled = enabled, onClick = onOpenFiles) + .padding(horizontal = 11.dp), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Outlined.Folder, + contentDescription = "浏览工作区文件", + tint = if (enabled) colors.textPrimary else colors.textTertiary, + modifier = Modifier.size(17.dp), + ) + } + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/AppUpdateDialog.kt b/app/src/main/java/dev/vibex/companion/app/ui/AppUpdateDialog.kt new file mode 100644 index 0000000..aaf6bf6 --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/AppUpdateDialog.kt @@ -0,0 +1,382 @@ +package dev.vibex.companion.app.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight +import androidx.compose.material.icons.rounded.SystemUpdate +import androidx.compose.material.icons.rounded.Verified +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import dev.vibex.companion.app.ui.theme.PlexMono +import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.app.update.ApkDownloadState +import dev.vibex.companion.app.update.AppUpdateUiState +import java.util.Locale + +@Composable +fun AppUpdateDialog( + state: AppUpdateUiState, + onConfirmUpdate: () -> Unit, + onDismiss: () -> Unit, +) { + val release = state.release ?: return + if (!state.dialogVisible) return + + val colors = VibexTheme.colors + val isDownloading = state.downloadState is ApkDownloadState.Downloading + val canDismiss = !release.forceUpdate && !isDownloading + + Dialog( + onDismissRequest = { if (canDismiss) onDismiss() }, + properties = DialogProperties( + dismissOnBackPress = canDismiss, + dismissOnClickOutside = canDismiss, + usePlatformDefaultWidth = false, + ), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp) + .clip(RoundedCornerShape(20.dp)) + .background(colors.card) + .border(1.dp, colors.hairline, RoundedCornerShape(20.dp)) + .padding(20.dp), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + modifier = Modifier + .size(42.dp) + .clip(CircleShape) + .background(colors.accent.copy(alpha = 0.14f)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.SystemUpdate, + contentDescription = null, + tint = colors.accent, + modifier = Modifier.size(22.dp), + ) + } + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = "发现新版本", + fontSize = 17.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + Box( + modifier = Modifier + .clip(RoundedCornerShape(999.dp)) + .background(colors.accent.copy(alpha = 0.14f)) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) { + Text( + text = "v${release.version}", + fontSize = 11.sp, + fontFamily = PlexMono, + fontWeight = FontWeight.SemiBold, + color = colors.accent, + ) + } + } + Text( + text = buildString { + append("当前版本 v${state.currentVersionName}") + if (release.apkSize > 0L) { + append(" · 安装包 ${formatApkMegabytes(release.apkSize)}") + } + }, + fontSize = 12.sp, + fontFamily = PlexMono, + color = colors.textSecondary, + ) + } + } + + Column( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 72.dp, max = 220.dp) + .clip(RoundedCornerShape(12.dp)) + .background(colors.segmentedTrack) + .padding(12.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = "更新内容", + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + ) + Text( + text = release.changelog.ifBlank { "• 性能优化与体验改进" }, + fontSize = 13.5.sp, + lineHeight = 20.sp, + color = colors.textPrimary, + ) + } + + when (val dl = state.downloadState) { + is ApkDownloadState.Downloading -> { + val pct = (dl.progress * 100f).toInt().coerceIn(0, 100) + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = "正在下载更新包…", + fontSize = 12.sp, + color = colors.textSecondary, + ) + Text( + text = if (dl.totalBytes > 0L) { + "${formatApkMegabytes(dl.downloadedBytes)} / ${formatApkMegabytes(dl.totalBytes)} ($pct%)" + } else { + formatApkMegabytes(dl.downloadedBytes) + }, + style = TextStyle( + fontSize = 12.sp, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textPrimary, + ), + ) + } + LinearProgressIndicator( + progress = { dl.progress }, + modifier = Modifier + .fillMaxWidth() + .height(6.dp) + .clip(RoundedCornerShape(999.dp)), + color = colors.accent, + trackColor = colors.segmentedTrack, + ) + } + } + is ApkDownloadState.PendingInstallPermission -> { + Text( + text = "安装包已就绪,请开启「允许来自此来源的应用」权限后自动完成覆盖安装。", + fontSize = 12.5.sp, + color = colors.textSecondary, + ) + } + is ApkDownloadState.ReadyToInstall -> { + Text( + text = "已调起系统安装器,直接点击「更新」即可覆盖安装并保留全部登录与连接数据。", + fontSize = 12.5.sp, + color = colors.textSecondary, + ) + } + is ApkDownloadState.Error -> { + Text( + text = dl.message, + fontSize = 12.5.sp, + color = colors.danger, + ) + } + ApkDownloadState.Idle -> Unit + } + + Spacer(Modifier.height(2.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (!release.forceUpdate) { + Box( + modifier = Modifier + .weight(1f) + .clip(RoundedCornerShape(12.dp)) + .background(colors.segmentedTrack) + .clickable(enabled = !isDownloading) { onDismiss() } + .padding(vertical = 12.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = "稍后提醒", + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + ) + } + } + + val primaryLabel = when (state.downloadState) { + is ApkDownloadState.Downloading -> "正在下载…" + is ApkDownloadState.PendingInstallPermission -> "授权并安装" + is ApkDownloadState.ReadyToInstall -> "立即安装" + is ApkDownloadState.Error -> "重试下载" + ApkDownloadState.Idle -> "立即更新" + } + + Box( + modifier = Modifier + .weight(if (release.forceUpdate) 1f else 1.25f) + .clip(RoundedCornerShape(12.dp)) + .background(if (isDownloading) colors.accent.copy(alpha = 0.6f) else colors.accent) + .clickable(enabled = !isDownloading) { onConfirmUpdate() } + .padding(vertical = 12.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = primaryLabel, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = Color.White, + ) + } + } + } + } +} + +private fun formatApkMegabytes(bytes: Long): String { + if (bytes <= 0L) return "0.0 MB" + return String.format(Locale.US, "%.1f MB", bytes.toDouble() / (1024.0 * 1024.0)) +} + +@Composable +fun SettingsVersionUpdateRow( + state: AppUpdateUiState, + protocolVersion: String, + onClick: () -> Unit, +) { + val colors = VibexTheme.colors + val release = state.release + Row( + Modifier + .fillMaxWidth() + .clickable(enabled = !state.checking, onClick = onClick) + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box( + Modifier + .size(32.dp) + .clip(RoundedCornerShape(8.dp)) + .background((if (state.hasUpdate) Color(0xFFFF3B30) else Color(0xFF34C759)).copy(0.14f)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = if (state.hasUpdate) Icons.Rounded.SystemUpdate else Icons.Rounded.Verified, + contentDescription = null, + tint = if (state.hasUpdate) Color(0xFFFF3B30) else Color(0xFF34C759), + modifier = Modifier.size(17.dp), + ) + } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + if (state.hasUpdate) "版本更新" else "当前版本", + fontSize = 15.5.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + ) + Text( + when { + state.checking -> "正在检查更新…" + state.hasUpdate && release != null -> "点击覆盖安装新版本 v${release.version}" + else -> "点击检查在线更新 · 协议 v${protocolVersion.ifBlank { "1.0" }}" + }, + fontSize = 12.sp, + color = colors.textSecondary, + ) + } + if (state.hasUpdate && release != null) { + Text( + "新版本 v${release.version}", + fontSize = 11.5.sp, + fontFamily = PlexMono, + fontWeight = FontWeight.SemiBold, + color = Color(0xFFFF3B30), + modifier = Modifier + .clip(CircleShape) + .background(Color(0xFFFF3B30).copy(alpha = 0.14f)) + .padding(horizontal = 8.dp, vertical = 3.dp), + ) + } else { + Text( + "v${state.currentVersionName}", + fontSize = 13.sp, + fontFamily = PlexMono, + color = colors.textSecondary, + ) + } + Icon( + Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(18.dp), + ) + } +} + +@Composable +fun AboutUpdateActionButton( + state: AppUpdateUiState, + onClick: () -> Unit, +) { + val colors = VibexTheme.colors + val release = state.release + val label = when { + state.checking -> "正在检查更新…" + state.hasUpdate && release != null -> "发现新版本 v${release.version} · 立即覆盖安装" + else -> "检查在线更新" + } + Box( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(if (state.hasUpdate) colors.accent else colors.segmentedTrack) + .clickable(enabled = !state.checking, onClick = onClick) + .padding(vertical = 11.dp), + contentAlignment = Alignment.Center, + ) { + Text( + label, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = if (state.hasUpdate) Color.White else colors.accent, + ) + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/ApprovalCard.kt b/app/src/main/java/dev/vibex/companion/app/ui/ApprovalCard.kt index 7a39f09..29c4fab 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/ApprovalCard.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/ApprovalCard.kt @@ -44,8 +44,10 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.AlertDialog import androidx.compose.material3.Icon import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -76,8 +78,10 @@ import dev.vibex.companion.QuestionAnswer import dev.vibex.companion.QuestionChoice import dev.vibex.companion.QuestionForm import dev.vibex.companion.ToolStep +import dev.vibex.companion.app.ui.theme.LocalConfirmHighRiskApproval import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.app.ui.theme.l import dev.vibex.remote.v1.JsonValue /** @@ -788,8 +792,71 @@ fun PermissionBanner( modifier: Modifier = Modifier, ) { val colors = VibexTheme.colors + val confirmHighRisk = LocalConfirmHighRiskApproval.current var expandedDiffPaths by remember(prompt.id) { mutableStateOf(setOf()) } var scopeMenuExpanded by remember(prompt.id) { mutableStateOf(false) } + var pendingHighRiskChoice by remember(prompt.id) { mutableStateOf?>(null) } + + val isHighRisk = remember(prompt.id, prompt.command, prompt.displayHeading, prompt.displaySubtitle) { + val text = listOfNotNull(prompt.command, prompt.displayHeading, prompt.displaySubtitle) + .joinToString(" ") + .lowercase() + val highRiskTokens = listOf( + "rm ", "rm -", "sudo ", "git push --force", "git push -f", + "git reset --hard", "git clean -", "drop ", "truncate ", + "delete from", "chmod ", "chown ", "kill -9", "pkill ", + "mkfs", "dd ", "> /dev/", "curl | sh", "curl | bash", "wget | sh", + ) + highRiskTokens.any { text.contains(it) } + } + + fun submitAllow(option: PermissionOption?, scope: PermissionAllowScope) { + if (confirmHighRisk && (isHighRisk || scope == PermissionAllowScope.Always)) { + pendingHighRiskChoice = option to scope + } else { + respond(option, scope) + } + } + + pendingHighRiskChoice?.let { (option, scope) -> + AlertDialog( + onDismissRequest = { pendingHighRiskChoice = null }, + containerColor = colors.card, + title = { + Text( + l("确认执行高危操作?", "Confirm High-Risk Action?"), + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + }, + text = { + Text( + l( + "此操作可能修改系统文件、覆盖代码或赋予永久权限,请确认后再授权。", + "This action may modify system files, overwrite code, or grant permanent permission. Confirm before approving.", + ), + fontSize = 14.sp, + color = colors.textSecondary, + ) + }, + confirmButton = { + TextButton( + onClick = { + pendingHighRiskChoice = null + respond(option, scope) + }, + ) { + Text(l("确认允许", "Confirm Allow"), fontWeight = FontWeight.SemiBold, color = colors.danger) + } + }, + dismissButton = { + TextButton(onClick = { pendingHighRiskChoice = null }) { + Text(l("取消", "Cancel"), color = colors.textSecondary) + } + }, + ) + } val hasPreview = prompt.displaySubtitle != null || prompt.command != null || @@ -992,7 +1059,7 @@ fun PermissionBanner( .fillMaxHeight() .clickable(enabled = !busy) { val option = prompt.resolveAllowOption(PermissionAllowScope.Once) - respond(option, PermissionAllowScope.Once) + submitAllow(option, PermissionAllowScope.Once) }, contentAlignment = Alignment.Center, ) { @@ -1027,17 +1094,17 @@ fun PermissionBanner( } } - DropdownMenu( + VibexDropdownMenu( expanded = scopeMenuExpanded, onDismissRequest = { scopeMenuExpanded = false }, ) { PermissionAllowScope.entries.forEach { scope -> - DropdownMenuItem( - text = { Text(scope.label, fontSize = 14.sp) }, + VibexDropdownMenuItem( + text = scope.label, onClick = { scopeMenuExpanded = false val option = prompt.resolveAllowOption(scope) - respond(option, scope) + submitAllow(option, scope) }, ) } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/CollabLongConversationComponents.kt b/app/src/main/java/dev/vibex/companion/app/ui/CollabLongConversationComponents.kt new file mode 100644 index 0000000..5cb96d9 --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/CollabLongConversationComponents.kt @@ -0,0 +1,889 @@ +package dev.vibex.companion.app.ui + +import android.widget.Toast +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.Reply +import androidx.compose.material.icons.outlined.ArrowDownward +import androidx.compose.material.icons.outlined.ArrowUpward +import androidx.compose.material.icons.outlined.Check +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.ContentCopy +import androidx.compose.material.icons.outlined.ExpandLess +import androidx.compose.material.icons.outlined.ExpandMore +import androidx.compose.material.icons.outlined.HelpOutline +import androidx.compose.material.icons.outlined.History +import androidx.compose.material.icons.outlined.OpenInFull +import androidx.compose.material.icons.outlined.Shield +import androidx.compose.material.icons.outlined.SwapHoriz +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.State +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.vibex.companion.CollabBotAvatarConfig +import dev.vibex.companion.CollabCard +import dev.vibex.companion.CollabEmbeddedCard +import dev.vibex.companion.CollabEmbeddedHandoff +import dev.vibex.companion.CollabScheduledMessage +import dev.vibex.companion.CollabSpaceMember +import dev.vibex.companion.CollabSpaceMessage +import dev.vibex.companion.applyMention +import dev.vibex.companion.buildCollabMessageLookup +import dev.vibex.companion.collabMessagePreviewText +import dev.vibex.companion.countCollabMessageLines +import dev.vibex.companion.mergeCollabMessages +import dev.vibex.companion.mentionTokenAt +import dev.vibex.companion.parseCollabStructuredMessage +import dev.vibex.companion.reconcileCollabStreamingDrafts +import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.ui.theme.PlexMono +import dev.vibex.companion.app.ui.theme.VibexTheme +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +private val CollabUserBubbleBlue = Color(0xFF2563EB) + +@Stable +class CollabConversationController( + private val spaceId: String, + private val threadId: String, + private val isGroup: Boolean, + private val model: CompanionModel, + private val listState: LazyListState, + private val scope: CoroutineScope, + private val nearBottomState: State, +) { + var messages by mutableStateOf>(emptyList()) + var scheduled by mutableStateOf>(emptyList()) + var cards by mutableStateOf>(emptyList()) + var spaceMembers by mutableStateOf>(emptyList()) + var hasMoreBefore by mutableStateOf(false) + var oldestSeq by mutableStateOf(null) + var loadingEarlier by mutableStateOf(false) + var loading by mutableStateOf(true) + var unreadNewCount by mutableIntStateOf(0) + var initialScrollDone by mutableStateOf(false) + var readerMessage by mutableStateOf(null) + val expandedMessageIds = mutableStateMapOf() + private var lastMarkedReadSeq: Int = 0 + + val isNearBottom: Boolean get() = nearBottomState.value + + fun bottomItemIndex(msgCount: Int = messages.size, withBanner: Boolean = hasMoreBefore): Int = + ((if (withBanner) 1 else 0) + msgCount - 1).coerceAtLeast(0) + + fun markLatestConfirmedRead(list: List = messages) { + val maxSeq = list.asSequence().filter { !it.isStreamingDraft && it.seq > 0 }.maxOfOrNull { it.seq } ?: return + if (maxSeq > lastMarkedReadSeq) { + lastMarkedReadSeq = maxSeq + scope.launch { runCatching { model.markCollabThreadRead(threadId, maxSeq, true) } } + } + } + + fun jumpToBottom() { + unreadNewCount = 0 + markLatestConfirmedRead(messages) + if (messages.isNotEmpty()) { + scope.launch { runCatching { listState.animateScrollToItem(bottomItemIndex()) } } + } + } + + suspend fun loadInitial() { + loading = true + initialScrollDone = false + runCatching { model.fetchCollabChatState(spaceId, isGroup, limit = 80) } + .onSuccess { (page, members) -> + val initial = mergeCollabMessages(emptyList(), page.messages, isIncremental = false) + messages = initial + scheduled = page.scheduled + cards = page.cards + hasMoreBefore = page.hasMoreBefore + oldestSeq = page.oldestSeq ?: initial.asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 } + .minOfOrNull { it.seq.toLong() } + if (isGroup) spaceMembers = members + markLatestConfirmedRead(initial) + loading = false + if (initial.isNotEmpty()) { + runCatching { listState.scrollToItem(bottomItemIndex(initial.size, page.hasMoreBefore)) } + } + initialScrollDone = true + } + .onFailure { + loading = false + initialScrollDone = true + } + } + + suspend fun syncIncrementalTail(refreshMembers: Boolean = false, forceScrollToBottom: Boolean = false) { + val current = messages + val isDirectThread = !isGroup || spaceId.startsWith("direct:") + val latestConfirmedSeq = current.asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 } + .maxOfOrNull { it.seq.toLong() } ?: 0L + val earliestActiveReceiptSeq = current.asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 && it.receipts.any { r -> r.isProcessing } } + .minOfOrNull { it.seq.toLong() } + val hasStreaming = current.any { it.isStreamingDraft } + + val pageResult = runCatching { + when { + isDirectThread -> model.fetchCollabMessagesPage(spaceId = spaceId, limit = 40, latest = true) + latestConfirmedSeq <= 0L -> model.fetchCollabMessagesPage(spaceId = spaceId, limit = 80, latest = true) + else -> { + val syncCursorSeq = if (earliestActiveReceiptSeq != null) { + (earliestActiveReceiptSeq - 1L).takeIf { it > 0L } + } else { + latestConfirmedSeq + } + model.fetchCollabMessagesPage( + spaceId = spaceId, + limit = 80, + sinceSeq = syncCursorSeq, + latest = syncCursorSeq == null, + ) + } + } + } + if (refreshMembers && isGroup) { + runCatching { model.fetchCollabSpaceMembersOnly(spaceId) }.onSuccess { spaceMembers = it } + } + val page = pageResult.getOrNull() ?: return + + val seenKeys = HashSet(current.size * 4) + for (prev in current) { + seenKeys += "id:${prev.id}" + prev.rawId?.takeIf { it.isNotBlank() }?.let { seenKeys += "raw:$it" } + prev.operationId?.takeIf { it.isNotBlank() }?.let { seenKeys += "op:$it" } + if (!prev.isStreamingDraft && prev.seq > 0) seenKeys += "seq:${prev.seq}" + prev.effectiveTurnId?.let { seenKeys += "turn:$it" } + if (prev.isStreamingDraft && prev.envelope.sender.isNotBlank()) { + seenKeys += "draft-sender:${prev.envelope.sender.lowercase()}" + } + } + val prevTailContent = current.lastOrNull()?.envelope?.content + + var merged = mergeCollabMessages(current, page.messages, isIncremental = true) + if (isDirectThread || hasStreaming || latestConfirmedSeq <= 0L) { + merged = reconcileCollabStreamingDrafts(merged, page.messages) + } + val newCount = merged.count { msg -> + val inTail = msg.isStreamingDraft || msg.seq.toLong() > latestConfirmedSeq + inTail && !( + ("id:${msg.id}" in seenKeys) || + (msg.rawId?.takeIf { it.isNotBlank() }?.let { "raw:$it" in seenKeys } == true) || + (msg.operationId?.takeIf { it.isNotBlank() }?.let { "op:$it" in seenKeys } == true) || + (!msg.isStreamingDraft && msg.seq > 0 && "seq:${msg.seq}" in seenKeys) || + (msg.effectiveTurnId?.let { "turn:$it" in seenKeys } == true) || + (msg.envelope.sender.isNotBlank() && "draft-sender:${msg.envelope.sender.lowercase()}" in seenKeys) + ) + } + val streamingUpdated = merged.lastOrNull()?.isStreamingDraft == true && + merged.lastOrNull()?.envelope?.content != prevTailContent + + val wasNearBottom = isNearBottom + val nextHasMore = if (current.isEmpty()) page.hasMoreBefore else hasMoreBefore + if (current.isEmpty()) { + hasMoreBefore = page.hasMoreBefore + oldestSeq = page.oldestSeq ?: merged.asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 } + .minOfOrNull { it.seq.toLong() } + } + messages = merged + scheduled = page.scheduled + cards = page.cards + + if (forceScrollToBottom || wasNearBottom) { + unreadNewCount = 0 + markLatestConfirmedRead(merged) + if (merged.isNotEmpty()) { + val targetBottom = bottomItemIndex(merged.size, nextHasMore) + if (forceScrollToBottom || newCount > 0) { + runCatching { listState.animateScrollToItem(targetBottom) } + } else if (streamingUpdated) { + runCatching { listState.scrollToItem(targetBottom) } + } + } + } else if (newCount > 0) { + unreadNewCount += newCount + } + } + + fun refreshNow(refreshMembers: Boolean = false, forceScrollToBottom: Boolean = false) { + scope.launch { syncIncrementalTail(refreshMembers, forceScrollToBottom) } + } + + fun loadEarlierMessages() { + if (!hasMoreBefore || loadingEarlier) return + val targetBeforeSeq = oldestSeq ?: messages.asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 } + .minOfOrNull { it.seq.toLong() } ?: return + loadingEarlier = true + val prevFirstIndex = listState.firstVisibleItemIndex + val prevOffset = listState.firstVisibleItemScrollOffset + val prevSize = messages.size + val wasHasMore = hasMoreBefore + scope.launch { + runCatching { + model.fetchCollabMessagesPage(spaceId = spaceId, limit = 80, beforeSeq = targetBeforeSeq, latest = false) + }.onSuccess { earlierPage -> + val merged = mergeCollabMessages(messages, earlierPage.messages, isIncremental = true) + val added = (merged.size - prevSize).coerceAtLeast(0) + val nextHasMore = earlierPage.hasMoreBefore && earlierPage.messages.isNotEmpty() && added > 0 + messages = merged + hasMoreBefore = nextHasMore + oldestSeq = earlierPage.oldestSeq ?: merged.asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 } + .minOfOrNull { it.seq.toLong() } + if (added > 0) { + val prevHeader = if (wasHasMore) 1 else 0 + val nextHeader = if (nextHasMore) 1 else 0 + val anchorMsgIdx = (prevFirstIndex - prevHeader).coerceAtLeast(0) + val targetIdx = (nextHeader + anchorMsgIdx + added) + .coerceIn(0, (nextHeader + merged.size - 1).coerceAtLeast(0)) + runCatching { + listState.scrollToItem(targetIdx, if (prevFirstIndex >= prevHeader) prevOffset else 0) + } + } + } + loadingEarlier = false + } + } +} + +@Composable +fun rememberCollabConversationController( + spaceId: String, + threadId: String, + isGroup: Boolean, + model: CompanionModel, + listState: LazyListState, +): Pair> { + val scope = rememberCoroutineScope() + val nearBottomState = remember(listState) { + derivedStateOf { + val layout = listState.layoutInfo + val total = layout.totalItemsCount + if (total == 0) true else (layout.visibleItemsInfo.lastOrNull()?.index ?: 0) >= total - 3 + } + } + val controller = remember(spaceId, threadId, isGroup) { + CollabConversationController(spaceId, threadId, isGroup, model, listState, scope, nearBottomState) + } + + LaunchedEffect(controller.isNearBottom) { + if (controller.isNearBottom && controller.unreadNewCount > 0) { + controller.unreadNewCount = 0 + controller.markLatestConfirmedRead() + } + } + + LaunchedEffect(spaceId) { + controller.loadInitial() + var pollTick = 0 + while (isActive) { + delay(2_500L) + pollTick += 1 + controller.syncIncrementalTail(refreshMembers = isGroup && pollTick % 10 == 0) + } + } + + LaunchedEffect(spaceId, listState) { + var lastIdx = Int.MAX_VALUE + var lastOffset = Int.MAX_VALUE + snapshotFlow { + Triple(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset, listState.isScrollInProgress) + }.collect { (idx, offset, scrolling) -> + val movedUp = idx < lastIdx || (idx == lastIdx && offset < lastOffset) + lastIdx = idx + lastOffset = offset + if (controller.initialScrollDone && scrolling && movedUp && idx <= 1 && controller.hasMoreBefore && !controller.loadingEarlier) { + controller.loadEarlierMessages() + } + } + } + + val lookup = remember(controller.messages) { buildCollabMessageLookup(controller.messages) } + return controller to lookup +} + +private fun takeCollapsedPreviewSlice(text: String, maxLines: Int = 24, maxChars: Int = 1_400): String { + val capped = if (text.length <= maxChars) text else text.take(maxChars) + val lines = capped.lines() + return if (lines.size <= maxLines) capped else lines.take(maxLines).joinToString("\n") +} + +@Composable +fun CollabRichBubbleContent( + message: CollabSpaceMessage, + knownCardsById: Map, + bubbleBackground: Color, + isExpanded: Boolean, + onToggleExpand: () -> Unit, + onOpenFullReader: () -> Unit, + modifier: Modifier = Modifier, +) { + val c = VibexTheme.colors + val isOwn = message.isFromUser + val parsed = remember(message.envelope.content) { parseCollabStructuredMessage(message.envelope.content) } + val canCollapse = !message.streaming && parsed.isCollapsible + val collapsed = canCollapse && !isExpanded + + Column(modifier = modifier) { + Box(modifier = if (collapsed) Modifier.heightIn(max = 220.dp).clipToBounds() else Modifier) { + Column( + modifier = Modifier.padding(start = 13.dp, end = 13.dp, top = 9.dp, bottom = if (canCollapse) 6.dp else 9.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + parsed.handoffs.forEach { CollabEmbeddedHandoffCard(it, isOwn) } + parsed.cards.forEach { CollabEmbeddedCardBlock(it, knownCardsById[it.id], isOwn) } + + val displayText = if (collapsed) takeCollapsedPreviewSlice(parsed.cleanText) else parsed.cleanText + if (displayText.isNotEmpty()) { + when { + message.streaming -> Text( + text = displayText, + color = if (isOwn) Color.White else c.textPrimary, + fontSize = 14.sp, + lineHeight = 21.sp, + ) + isOwn -> CollabOwnBubbleMarkdown(displayText) + else -> CollabBotBubbleMarkdown(displayText) + } + } else if (message.streaming && !parsed.hasStructuredBlocks) { + Text("思考中…", color = if (isOwn) Color.White.copy(alpha = 0.85f) else c.textSecondary, fontSize = 14.sp, lineHeight = 20.sp) + } + } + + if (collapsed) { + Box( + modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(44.dp) + .background(Brush.verticalGradient(listOf(bubbleBackground.copy(alpha = 0f), bubbleBackground))), + ) + } + } + + if (canCollapse) { + val actionTint = if (isOwn) Color.White else CollabUserBubbleBlue + val secondaryTint = if (isOwn) Color.White.copy(alpha = 0.88f) else c.textSecondary + HorizontalDivider(color = if (isOwn) Color.White.copy(alpha = 0.18f) else c.stroke, thickness = 0.5.dp) + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Row( + modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable(onClick = onToggleExpand).padding(horizontal = 4.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + ) { + Icon(if (collapsed) Icons.Outlined.ExpandMore else Icons.Outlined.ExpandLess, null, tint = actionTint, modifier = Modifier.size(15.dp)) + Text( + text = if (collapsed) "展开全文 · ${parsed.lineCount} 行" else "收起", + style = TextStyle(color = actionTint, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, fontFeatureSettings = "tnum"), + ) + } + Row( + modifier = Modifier.clip(RoundedCornerShape(8.dp)).clickable(onClick = onOpenFullReader).padding(horizontal = 4.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon(Icons.Outlined.OpenInFull, null, tint = secondaryTint, modifier = Modifier.size(13.dp)) + Text("全屏阅读", color = secondaryTint, fontSize = 12.sp, fontWeight = FontWeight.Medium) + } + } + } + } +} + +@Composable +private fun CollabBotBubbleMarkdown(raw: String) { + val blocks = remember(raw) { parseMarkdownBlocks(raw) } + val fillWidth = remember(raw, blocks) { + blocks.size > 1 || raw.length > 38 || raw.contains('\n') || blocks.any { it !is MarkdownBlock.Paragraph } + } + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (block in blocks) SingleBlockView(block = block, fillWidth = fillWidth) + } +} + +@Composable +private fun CollabOwnBubbleMarkdown(raw: String) { + val blocks = remember(raw) { parseMarkdownBlocks(raw) } + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + for (block in blocks) { + when (block) { + is MarkdownBlock.Code -> Box( + modifier = Modifier.clip(RoundedCornerShape(10.dp)).background(Color(0xFF172554)) + .horizontalScroll(rememberScrollState()).padding(horizontal = 10.dp, vertical = 8.dp), + ) { + Text(block.code, color = Color(0xFFF8FAFC), fontFamily = PlexMono, fontSize = 12.sp, lineHeight = 18.sp) + } + is MarkdownBlock.Heading -> Text( + text = rememberOwnInlineMarkdown(block.text), + color = Color.White, + fontWeight = FontWeight.Bold, + fontSize = if (block.level <= 2) 16.sp else 14.5.sp, + lineHeight = 22.sp, + ) + is MarkdownBlock.BulletList -> Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { + block.items.forEach { item -> + Row(horizontalArrangement = Arrangement.spacedBy(5.dp)) { + Text("•", color = Color.White.copy(alpha = 0.8f), fontSize = 14.sp) + Text(rememberOwnInlineMarkdown(item), color = Color.White, fontSize = 14.sp, lineHeight = 20.sp) + } + } + } + is MarkdownBlock.NumberedList -> Column(verticalArrangement = Arrangement.spacedBy(3.dp)) { + block.items.forEach { (marker, item) -> + Row(horizontalArrangement = Arrangement.spacedBy(5.dp)) { + Text(marker, style = TextStyle(color = Color.White.copy(alpha = 0.8f), fontSize = 14.sp, fontFeatureSettings = "tnum")) + Text(rememberOwnInlineMarkdown(item), color = Color.White, fontSize = 14.sp, lineHeight = 20.sp) + } + } + } + is MarkdownBlock.Quote -> Row(horizontalArrangement = Arrangement.spacedBy(7.dp)) { + Box(Modifier.width(2.5.dp).height(18.dp).clip(RoundedCornerShape(1.dp)).background(Color.White.copy(alpha = 0.6f))) + Text(rememberOwnInlineMarkdown(block.text), color = Color.White.copy(alpha = 0.9f), fontStyle = FontStyle.Italic, fontSize = 13.5.sp, lineHeight = 20.sp) + } + MarkdownBlock.Rule -> HorizontalDivider(color = Color.White.copy(alpha = 0.24f), thickness = 0.5.dp) + is MarkdownBlock.Table -> Text( + text = (listOf(block.header) + block.rows).joinToString("\n") { it.joinToString(" | ") }, + color = Color.White, + fontFamily = PlexMono, + fontSize = 12.sp, + lineHeight = 18.sp, + ) + is MarkdownBlock.Paragraph -> Text(rememberOwnInlineMarkdown(block.text), color = Color.White, fontSize = 14.sp, lineHeight = 20.sp) + } + } + } +} + +@Composable +private fun rememberOwnInlineMarkdown(raw: String): AnnotatedString = remember(raw) { + buildAnnotatedString { + var i = 0 + while (i < raw.length) { + val ch = raw[i] + when { + ch == '`' && raw.indexOf('`', i + 1) > i -> { + val end = raw.indexOf('`', i + 1) + withStyle(SpanStyle(fontFamily = PlexMono, background = Color.White.copy(alpha = 0.18f), color = Color.White)) { + append(" ${raw.substring(i + 1, end)} ") + } + i = end + 1 + } + (ch == '*' || ch == '_') && i + 1 < raw.length && raw[i + 1] == ch && raw.indexOf("$ch$ch", i + 2) > i + 1 -> { + val end = raw.indexOf("$ch$ch", i + 2) + withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(raw.substring(i + 2, end)) } + i = end + 2 + } + raw.startsWith("~~", i) && raw.indexOf("~~", i + 2) > i + 1 -> { + val end = raw.indexOf("~~", i + 2) + withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) { append(raw.substring(i + 2, end)) } + i = end + 2 + } + else -> { + append(ch) + i++ + } + } + } + } +} + +@Composable +private fun CollabEmbeddedCardBlock(card: CollabEmbeddedCard, liveCard: CollabCard?, isOwn: Boolean) { + val c = VibexTheme.colors + val containerBg = if (isOwn) Color(0xFF1D4ED8) else c.bgElevated + val borderColor = if (isOwn) Color.White.copy(alpha = 0.22f) else c.stroke + val primaryText = if (isOwn) Color.White else c.textPrimary + val secondaryText = if (isOwn) Color.White.copy(alpha = 0.82f) else c.textSecondary + val resolvedStatus = (liveCard?.status ?: card.status ?: "pending").lowercase() + val (statusLabel, statusColor) = when (resolvedStatus) { + "approved", "allow_once", "allow_always" -> "已批准" to Color(0xFF16A34A) + "denied", "declined", "rejected", "deny" -> "已拒绝" to Color(0xFFDC2626) + "answered", "resolved", "completed", "responded" -> "已处理" to Color(0xFF16A34A) + else -> "待处理" to Color(0xFFD97706) + } + + Surface(shape = RoundedCornerShape(10.dp), color = containerBg, border = BorderStroke(0.5.dp, borderColor), modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Icon(if (card.kind == "approval") Icons.Outlined.Shield else Icons.Outlined.HelpOutline, null, tint = if (isOwn) Color.White else Color(0xFFF97316), modifier = Modifier.size(14.dp)) + Text(if (card.kind == "approval") "审批请求" else "助手提问", color = primaryText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.weight(1f)) + Surface(shape = RoundedCornerShape(50), color = if (isOwn) Color.White.copy(alpha = 0.16f) else statusColor.copy(alpha = 0.14f)) { + Text(statusLabel, color = if (isOwn) Color.White else statusColor, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(horizontal = 7.dp, vertical = 2.dp)) + } + } + val mainLine = if (card.kind == "approval") (card.action ?: card.body) else (card.question ?: card.body) + if (mainLine.isNotBlank()) { + Text(mainLine, color = primaryText, fontSize = 13.sp, lineHeight = 18.sp, fontWeight = FontWeight.Medium) + } + if (!card.command.isNullOrBlank()) { + Box(Modifier.fillMaxWidth().clip(RoundedCornerShape(7.dp)).background(if (isOwn) Color(0xFF172554) else c.codeSurface).padding(horizontal = 8.dp, vertical = 5.dp)) { + Text(card.command.orEmpty(), color = if (isOwn) Color(0xFFF8FAFC) else c.textPrimary, fontFamily = PlexMono, fontSize = 11.5.sp, lineHeight = 16.sp) + } + } + if (!card.reason.isNullOrBlank() && card.reason != mainLine) { + Text(card.reason.orEmpty(), color = secondaryText, fontSize = 12.sp, lineHeight = 17.sp) + } + if (card.options.isNotEmpty()) { + Row(modifier = Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(5.dp)) { + card.options.forEach { opt -> + Surface(shape = RoundedCornerShape(50), color = if (isOwn) Color.White.copy(alpha = 0.16f) else c.card, border = BorderStroke(0.5.dp, borderColor)) { + Text(opt, color = primaryText, fontSize = 11.sp, modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)) + } + } + } + } + } + } +} + +@Composable +private fun CollabEmbeddedHandoffCard(handoff: CollabEmbeddedHandoff, isOwn: Boolean) { + val c = VibexTheme.colors + val containerBg = if (isOwn) Color(0xFF1D4ED8) else c.bgElevated + val borderColor = if (isOwn) Color.White.copy(alpha = 0.22f) else c.stroke + val primaryText = if (isOwn) Color.White else c.textPrimary + val secondaryText = if (isOwn) Color.White.copy(alpha = 0.82f) else c.textSecondary + val routeTitle = if (!handoff.from.isNullOrBlank() || !handoff.to.isNullOrBlank()) { + "${handoff.from ?: "助手"} → ${handoff.to ?: "助手"}" + } else { + "任务交接" + } + + Surface(shape = RoundedCornerShape(10.dp), color = containerBg, border = BorderStroke(0.5.dp, borderColor), modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Icon(Icons.Outlined.SwapHoriz, null, tint = if (isOwn) Color.White else CollabUserBubbleBlue, modifier = Modifier.size(14.dp)) + Text(routeTitle, color = primaryText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) + if (!handoff.depth.isNullOrBlank()) { + Spacer(Modifier.weight(1f)) + Text("L${handoff.depth}", style = TextStyle(color = secondaryText, fontSize = 10.sp, fontFamily = PlexMono, fontFeatureSettings = "tnum")) + } + } + if (handoff.summary.isNotBlank()) { + Text(handoff.summary, color = primaryText, fontSize = 12.5.sp, lineHeight = 18.sp, fontWeight = FontWeight.Medium) + } + if (!handoff.done.isNullOrBlank() && handoff.done != handoff.summary) { + Text("已完成:${handoff.done}", color = secondaryText, fontSize = 11.5.sp, lineHeight = 16.sp) + } + if (!handoff.inputsConstraints.isNullOrBlank()) { + Text("约束:${handoff.inputsConstraints}", color = secondaryText, fontSize = 11.5.sp, lineHeight = 16.sp) + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CollabFullMessageReaderSheet( + message: CollabSpaceMessage, + avatarConfig: CollabBotAvatarConfig, + knownCardsById: Map, + onDismiss: () -> Unit, +) { + val c = VibexTheme.colors + val context = LocalContext.current + val clipboard = LocalClipboardManager.current + val haptics = LocalHapticFeedback.current + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val parsed = remember(message.envelope.content) { parseCollabStructuredMessage(message.envelope.content) } + val copyableText = remember(parsed, message.envelope.content) { + parsed.cleanText.ifBlank { collabMessagePreviewText(message.envelope.content) } + } + var copied by remember { mutableStateOf(false) } + LaunchedEffect(copied) { + if (copied) { + delay(1_800L) + copied = false + } + } + + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = c.card, contentColor = c.textPrimary) { + Column(modifier = Modifier.fillMaxWidth().fillMaxHeight(0.9f).navigationBarsPadding()) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (!message.isFromUser) MemberBotAvatarView(config = avatarConfig, size = 30.dp, sessionActive = false) + Column(modifier = Modifier.weight(1f)) { + Text(message.envelope.displaySender, color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) + val metaParts = buildList { + message.envelope.published?.takeIf { it.isNotBlank() }?.let { + val rel = formatCollabRelativeTime(it) + if (rel.isNotBlank()) add(rel) + } + if (parsed.lineCount > 0) add("${parsed.lineCount} 行") + } + if (metaParts.isNotEmpty()) { + Text(metaParts.joinToString(" · "), style = TextStyle(color = c.textSecondary, fontSize = 12.sp, fontFeatureSettings = "tnum")) + } + } + Surface( + onClick = { + clipboard.setText(AnnotatedString(copyableText)) + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + Toast.makeText(context, "已复制全文", Toast.LENGTH_SHORT).show() + copied = true + }, + shape = RoundedCornerShape(10.dp), + color = c.bgElevated, + border = BorderStroke(0.75.dp, c.stroke), + ) { + Row(modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { + Icon(if (copied) Icons.Outlined.Check else Icons.Outlined.ContentCopy, null, tint = if (copied) Color(0xFF16A34A) else c.textPrimary, modifier = Modifier.size(15.dp)) + Text(if (copied) "已复制" else "复制全文", color = if (copied) Color(0xFF16A34A) else c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) + } + } + IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) { + Icon(Icons.Outlined.Close, contentDescription = "关闭", tint = c.textSecondary, modifier = Modifier.size(18.dp)) + } + } + HorizontalDivider(color = c.stroke, thickness = 0.5.dp) + Column( + modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 18.dp, vertical = 16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + parsed.handoffs.forEach { SelectionContainer { CollabEmbeddedHandoffCard(it, isOwn = false) } } + parsed.cards.forEach { SelectionContainer { CollabEmbeddedCardBlock(it, knownCardsById[it.id], isOwn = false) } } + if (parsed.cleanText.isNotBlank()) { + MarkdownText(source = parsed.cleanText, modifier = Modifier.fillMaxWidth()) + } + } + } + } +} + +@Composable +fun CollabJumpToBottomPill(unreadNewCount: Int, onClick: () -> Unit, modifier: Modifier = Modifier) { + val c = VibexTheme.colors + val hasUnread = unreadNewCount > 0 + val contentColor = if (hasUnread) Color.White else c.textPrimary + Surface( + onClick = onClick, + shape = CircleShape, + color = if (hasUnread) CollabUserBubbleBlue else c.card, + border = if (hasUnread) null else BorderStroke(0.75.dp, c.stroke), + modifier = modifier.shadow( + elevation = if (c.isDark) 8.dp else 4.dp, + shape = CircleShape, + ambientColor = Color.Black.copy(alpha = if (c.isDark) 0.28f else 0.08f), + spotColor = Color.Black.copy(alpha = if (c.isDark) 0.34f else 0.12f), + ), + ) { + Row(modifier = Modifier.padding(horizontal = 13.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { + Icon(Icons.Outlined.ArrowDownward, null, tint = contentColor, modifier = Modifier.size(15.dp)) + Text( + text = if (hasUnread) "$unreadNewCount 条新消息" else "回到底部", + style = TextStyle(color = contentColor, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, fontFeatureSettings = "tnum"), + ) + } + } +} + +@Composable +fun CollabLoadEarlierBanner(loading: Boolean, onLoadEarlier: () -> Unit, modifier: Modifier = Modifier) { + val c = VibexTheme.colors + Box(modifier = modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = Alignment.Center) { + Surface(onClick = { if (!loading) onLoadEarlier() }, shape = CircleShape, color = c.card, border = BorderStroke(0.75.dp, c.stroke)) { + Row(modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (loading) { + CircularProgressIndicator(color = c.accent, strokeWidth = 1.8.dp, modifier = Modifier.size(13.dp)) + Text("加载更早消息…", color = c.textSecondary, fontSize = 12.sp, fontWeight = FontWeight.Medium) + } else { + Icon(Icons.Outlined.History, null, tint = c.textSecondary, modifier = Modifier.size(14.dp)) + Text("加载更早消息", color = c.textSecondary, fontSize = 12.sp, fontWeight = FontWeight.Medium) + } + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CollabExpandedComposerSheet( + title: String, + isGroup: Boolean, + leadMemberId: String?, + agentMembers: List, + selectedTargets: List, + replyingTo: CollabSpaceMessage?, + inputValue: TextFieldValue, + sending: Boolean, + onInputChange: (TextFieldValue) -> Unit, + onToggleTarget: (String) -> Unit, + onClearReply: () -> Unit, + onSend: () -> Unit, + onDismiss: () -> Unit, +) { + val c = VibexTheme.colors + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val canSend = inputValue.text.trim().isNotEmpty() && !sending + val lineCount = remember(inputValue.text) { countCollabMessageLines(inputValue.text) } + + fun insertChipMention(label: String, target: String) { + val text = inputValue.text + val caret = inputValue.selection.start.coerceIn(0, text.length) + val activeToken = if (inputValue.selection.collapsed) mentionTokenAt(text, caret) else null + if (activeToken != null) { + val (next, nextCaret) = applyMention(text, activeToken, label) + onInputChange(TextFieldValue(next, TextRange(nextCaret))) + } else { + val insert = (if (caret > 0 && !text[caret - 1].isWhitespace()) " " else "") + "@$label " + onInputChange(TextFieldValue(text.substring(0, caret) + insert + text.substring(caret), TextRange(caret + insert.length))) + } + if (!selectedTargets.contains(target)) onToggleTarget(target) + } + + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = c.card, contentColor = c.textPrimary) { + Column( + modifier = Modifier.fillMaxWidth().navigationBarsPadding().imePadding().padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { + Column(modifier = Modifier.weight(1f)) { + Text(title, color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text("${lineCount.coerceAtLeast(1)} 行 · ${inputValue.text.length} 字", style = TextStyle(color = c.textSecondary, fontSize = 11.5.sp, fontFeatureSettings = "tnum")) + } + IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) { + Icon(Icons.Outlined.Close, contentDescription = "收起编辑器", tint = c.textSecondary, modifier = Modifier.size(18.dp)) + } + } + if (replyingTo != null) { + Row( + modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(c.bgElevated).padding(horizontal = 10.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Icons.AutoMirrored.Outlined.Reply, null, tint = CollabUserBubbleBlue, modifier = Modifier.size(14.dp)) + Text("回复 ${replyingTo.envelope.displaySender}:${collabMessagePreviewText(replyingTo.envelope.content)}", color = c.textSecondary, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + Icon(Icons.Outlined.Close, "取消回复", tint = c.textSecondary, modifier = Modifier.size(16.dp).clickable(onClick = onClearReply)) + } + } + if (isGroup && agentMembers.isNotEmpty()) { + Row(modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) { + val allSelected = selectedTargets.contains("@all") + Surface(onClick = { insertChipMention("全体成员", "@all") }, shape = RoundedCornerShape(50), color = if (allSelected) CollabUserBubbleBlue else c.bgElevated) { + Text("@全体成员", color = if (allSelected) Color.White else c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.Medium, modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)) + } + agentMembers.forEach { member -> + val selected = selectedTargets.contains(member.resolvedIdentityId) + Surface(onClick = { insertChipMention(member.nickname, member.resolvedIdentityId) }, shape = RoundedCornerShape(50), color = if (selected) CollabUserBubbleBlue else c.bgElevated) { + Row(modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { + MemberBotAvatarView(config = member.botAvatar, size = 16.dp, sessionActive = false, isLead = leadMemberId == member.resolvedIdentityId) + Text("@${member.nickname}", color = if (selected) Color.White else c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.Medium) + } + } + } + } + } + Box( + modifier = Modifier.fillMaxWidth().heightIn(min = 180.dp, max = 340.dp).clip(RoundedCornerShape(14.dp)).background(c.bgElevated) + .border(0.75.dp, c.stroke, RoundedCornerShape(14.dp)).verticalScroll(rememberScrollState()).padding(14.dp), + ) { + if (inputValue.text.isEmpty()) { + Text("输入多行提示词、架构说明或代码片段…", color = c.textTertiary, fontSize = 15.sp) + } + BasicTextField( + value = inputValue, + onValueChange = onInputChange, + textStyle = TextStyle(color = c.textPrimary, fontSize = 15.sp, lineHeight = 22.sp), + cursorBrush = SolidColor(c.accent), + modifier = Modifier.fillMaxWidth(), + ) + } + Row(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), horizontalArrangement = Arrangement.End) { + Button( + onClick = { onSend(); onDismiss() }, + enabled = canSend, + shape = RoundedCornerShape(50), + colors = ButtonDefaults.buttonColors(containerColor = c.textPrimary, contentColor = c.bg), + contentPadding = PaddingValues(horizontal = 18.dp, vertical = 10.dp), + ) { + Icon(Icons.Outlined.ArrowUpward, null, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(5.dp)) + Text("发送", fontSize = 13.sp, fontWeight = FontWeight.SemiBold) + } + } + } + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/CollaborationScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/CollaborationScreen.kt index 08de49b..0037b05 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/CollaborationScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/CollaborationScreen.kt @@ -57,10 +57,12 @@ import androidx.compose.material.icons.outlined.HelpOutline import androidx.compose.material.icons.outlined.MarkChatRead import androidx.compose.material.icons.outlined.MarkChatUnread import androidx.compose.material.icons.outlined.MoreHoriz +import androidx.compose.material.icons.outlined.OpenInFull import androidx.compose.material.icons.outlined.Palette import androidx.compose.material.icons.outlined.PersonAdd import androidx.compose.material.icons.outlined.PersonRemove import androidx.compose.material.icons.outlined.Psychology +import androidx.compose.material.icons.outlined.Public import androidx.compose.material.icons.outlined.Schedule import androidx.compose.material.icons.outlined.Search import androidx.compose.material.icons.outlined.Shield @@ -89,6 +91,7 @@ import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -130,6 +133,9 @@ import dev.vibex.companion.CollabSpaceSummary import dev.vibex.companion.CollabTeam import dev.vibex.companion.SubagentRoleItem import dev.vibex.companion.agentDisplayName +import dev.vibex.companion.collabMessagePreviewText +import dev.vibex.companion.lookupCollabReplyMessage +import dev.vibex.companion.parseCollabStructuredMessage import dev.vibex.companion.app.CompanionModel import dev.vibex.companion.app.UiState import dev.vibex.companion.app.ui.theme.VibexTheme @@ -148,7 +154,7 @@ private enum class CollabTab(val title: String) { fun CollaborationScreen( state: UiState, model: CompanionModel, - onChatOpenChange: (Boolean) -> Unit = {}, + onActiveChatChanged: (Boolean) -> Unit = {}, ) { val c = VibexTheme.colors val scope = rememberCoroutineScope() @@ -163,8 +169,16 @@ fun CollaborationScreen( var activeChatItem by remember { mutableStateOf(null) } var openedBotConversationId by remember { mutableStateOf(null) } - LaunchedEffect(activeChatItem != null || openedBotConversationId != null) { - onChatOpenChange(activeChatItem != null || openedBotConversationId != null) + + val inNestedChat = activeChatItem != null || openedBotConversationId != null + LaunchedEffect(inNestedChat) { + onActiveChatChanged(inNestedChat) + } + DisposableEffect(Unit) { + onDispose { onActiveChatChanged(false) } + } + LaunchedEffect(sidebarItems) { + model.updateCollabUnreadCount(sidebarItems.sumOf { it.unreadCount }) } var showAddMenu by remember { mutableStateOf(false) } @@ -222,24 +236,27 @@ fun CollaborationScreen( val filteredItems = remember(sidebarItems, selectedTab, searchText) { val q = searchText.trim().lowercase() - val basePool = when (selectedTab) { - CollabTab.All -> sidebarItems - CollabTab.Primary -> { - val primary = sidebarItems.filter { item -> - item.isGroup || - item.member?.isSupervisor == true || - item.unreadCount > 0 || - item.lastMessage != null - } - if (primary.isEmpty()) sidebarItems else primary + if (q.isNotEmpty()) { + sidebarItems.filter { item -> + val agentMatch = item.member?.agent?.let { ag -> + ag.lowercase().contains(q) || agentDisplayName(ag).lowercase().contains(q) + } == true + item.displayName.lowercase().contains(q) || + item.lastMessage?.preview?.lowercase()?.contains(q) == true || + agentMatch } - } - if (q.isEmpty()) { - basePool } else { - basePool.filter { item -> - item.displayName.lowercase().contains(q) || - item.lastMessage?.preview?.lowercase()?.contains(q) == true + when (selectedTab) { + CollabTab.All -> sidebarItems + CollabTab.Primary -> { + val primary = sidebarItems.filter { item -> + item.isGroup || + item.member?.isSupervisor == true || + item.unreadCount > 0 || + item.lastMessage != null + } + if (primary.isEmpty()) sidebarItems else primary + } } } } @@ -259,52 +276,71 @@ fun CollaborationScreen( modifier = Modifier .fillMaxSize() .background(c.bg) - // The list stays composed under an open chat; keep it out of TalkBack's reach. .then(if (activeChatItem != null) Modifier.clearAndSetSemantics { } else Modifier), ) { - // Top Header Bar (Project Selector | 协作空间 | + Menu) — Strictly Centered Title + // Top Header Bar: Plain Project Selector | 协作空间 | + Menu Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 10.dp), ) { - Box(modifier = Modifier.align(Alignment.CenterStart)) { - Surface( - onClick = { showProjectMenu = true }, - shape = RoundedCornerShape(50), - color = c.bgElevated, - border = BorderStroke(0.5.dp, c.stroke), + Box( + modifier = Modifier + .align(Alignment.CenterStart) + .fillMaxWidth(0.5f) + .padding(end = 42.dp), + ) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { showProjectMenu = true } + .padding(horizontal = 4.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), ) { - Row( - modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(5.dp), - ) { - Icon(Icons.Outlined.Folder, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(13.dp)) - Text( - text = activeProject?.name ?: "项目", - color = c.textPrimary, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.widthIn(max = 110.dp), - ) - Icon(Icons.Outlined.UnfoldMore, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(12.dp)) - } + Icon( + Icons.Outlined.Folder, + contentDescription = null, + tint = c.textSecondary, + modifier = Modifier.size(15.dp), + ) + Text( + text = if (state.selectedProjectId == null) "全局" else (activeProject?.name ?: "项目"), + color = c.textPrimary, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + Icon( + Icons.Outlined.ExpandMore, + contentDescription = null, + tint = c.textSecondary, + modifier = Modifier.size(15.dp), + ) } - DropdownMenu( + VibexDropdownMenu( expanded = showProjectMenu, onDismissRequest = { showProjectMenu = false }, ) { + VibexDropdownMenuItem( + text = "全局", + leadingIcon = Icons.Outlined.Public, + selected = state.selectedProjectId == null, + onClick = { + showProjectMenu = false + model.selectProjectInPlace(null) + }, + ) + if (state.catalog?.projects.orEmpty().isNotEmpty()) { + VibexDropdownDivider() + } state.catalog?.projects.orEmpty().forEach { project -> - DropdownMenuItem( - text = { Text(project.name) }, - trailingIcon = { - if (state.selectedProjectId == project.id) { - Icon(Icons.Outlined.Check, contentDescription = null, modifier = Modifier.size(16.dp)) - } - }, + VibexDropdownMenuItem( + text = project.name, + leadingIcon = Icons.Outlined.Folder, + selected = state.selectedProjectId == project.id, onClick = { showProjectMenu = false model.selectProjectInPlace(project.id) @@ -318,7 +354,7 @@ fun CollaborationScreen( text = "协作空间", color = c.textPrimary, fontSize = 17.sp, - fontWeight = FontWeight.SemiBold, + fontWeight = FontWeight.Bold, modifier = Modifier.align(Alignment.Center), textAlign = TextAlign.Center, ) @@ -327,48 +363,48 @@ fun CollaborationScreen( Surface( onClick = { showAddMenu = true }, shape = CircleShape, - color = c.bgElevated, - border = BorderStroke(0.5.dp, c.stroke), - modifier = Modifier.size(32.dp), + color = c.card, + border = BorderStroke(0.6.dp, c.stroke), + modifier = Modifier.size(34.dp), ) { Box(contentAlignment = Alignment.Center) { - Icon(Icons.Outlined.Add, contentDescription = "新建", tint = c.textPrimary, modifier = Modifier.size(17.dp)) + Icon(Icons.Outlined.Add, contentDescription = "新建", tint = c.textPrimary, modifier = Modifier.size(18.dp)) } } - DropdownMenu( + VibexDropdownMenu( expanded = showAddMenu, onDismissRequest = { showAddMenu = false }, ) { - DropdownMenuItem( - text = { Text("新建助手") }, - leadingIcon = { Icon(Icons.Outlined.SmartToy, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "新建助手", + leadingIcon = Icons.Outlined.SmartToy, onClick = { showAddMenu = false showCreateAssistantSheet = true }, ) - DropdownMenuItem( - text = { Text("新建群组") }, - leadingIcon = { Icon(Icons.Outlined.Groups, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "新建群组", + leadingIcon = Icons.Outlined.Groups, onClick = { showAddMenu = false newGroupName = "" showCreateGroupAlert = true }, ) - DropdownMenuItem( - text = { Text("新建联系人分组") }, - leadingIcon = { Icon(Icons.Outlined.CreateNewFolder, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "新建联系人分组", + leadingIcon = Icons.Outlined.CreateNewFolder, onClick = { showAddMenu = false newContactGroupName = "" showCreateContactGroupAlert = true }, ) - HorizontalDivider() - DropdownMenuItem( - text = { Text("角色与团队管理") }, - leadingIcon = { Icon(Icons.Outlined.Shield, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownDivider() + VibexDropdownMenuItem( + text = "角色与团队管理", + leadingIcon = Icons.Outlined.Shield, onClick = { showAddMenu = false showRolesAndTeamsSheet = true @@ -378,77 +414,63 @@ fun CollaborationScreen( } } - // Centered Segmented Switcher (主要 | 全部) + Search Bar + // Unified Search Bar + Filter Row (主要 | 全部 + count) Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(bottom = 10.dp), - horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp), ) { - Row( - modifier = Modifier - .width(196.dp) - .clip(RoundedCornerShape(9.dp)) - .background(c.segmentedTrack) - .padding(3.dp), - ) { - CollabTab.entries.forEach { tab -> - val selected = selectedTab == tab - Text( - text = tab.title, - color = if (selected) c.textPrimary else c.textSecondary, - fontSize = 13.sp, - fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, - textAlign = TextAlign.Center, - modifier = Modifier - .weight(1f) - .then( - if (selected) Modifier.shadow(1.5.dp, RoundedCornerShape(7.dp), ambientColor = Color.Black.copy(alpha = 0.08f)) - else Modifier, - ) - .clip(RoundedCornerShape(7.dp)) - .background(if (selected) c.segmentedThumb else Color.Transparent) - .clickable { selectedTab = tab } - .padding(vertical = 6.dp), - ) - } - } + UnifiedSearchBar( + query = searchText, + onQueryChange = { searchText = it }, + placeholder = "搜索群组或助手…", + ) Row( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(10.dp)) - .background(c.bgElevated) - .padding(horizontal = 12.dp, vertical = 9.dp), + modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - Icon(Icons.Outlined.Search, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(15.dp)) - Box(modifier = Modifier.weight(1f)) { - if (searchText.isEmpty()) { - Text("搜索群组或助手…", color = c.textSecondary, fontSize = 14.sp) + Row( + modifier = Modifier + .width(148.dp) + .clip(RoundedCornerShape(8.dp)) + .background(c.segmentedTrack) + .padding(2.dp), + ) { + CollabTab.entries.forEach { tab -> + val selected = selectedTab == tab + Text( + text = tab.title, + color = if (selected) c.textPrimary else c.textSecondary, + fontSize = 12.5.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + textAlign = TextAlign.Center, + modifier = Modifier + .weight(1f) + .then( + if (selected) Modifier.shadow(1.5.dp, RoundedCornerShape(6.dp), ambientColor = Color.Black.copy(alpha = 0.08f)) + else Modifier, + ) + .clip(RoundedCornerShape(6.dp)) + .background(if (selected) c.segmentedThumb else Color.Transparent) + .clickable { selectedTab = tab } + .padding(vertical = 5.dp), + ) } - BasicTextField( - value = searchText, - onValueChange = { searchText = it }, - singleLine = true, - textStyle = TextStyle(color = c.textPrimary, fontSize = 14.sp), - cursorBrush = SolidColor(c.accent), - modifier = Modifier.fillMaxWidth(), - ) - } - if (searchText.isNotEmpty()) { - Icon( - Icons.Outlined.Close, - contentDescription = "清除", - tint = c.textSecondary, - modifier = Modifier - .size(16.dp) - .clickable { searchText = "" }, - ) } + + Spacer(modifier = Modifier.weight(1f)) + + Text( + text = "${filteredItems.size} 个协作", + style = TextStyle( + fontSize = 12.sp, + fontFeatureSettings = "tnum", + color = c.textSecondary, + ), + ) } } @@ -456,20 +478,50 @@ fun CollaborationScreen( if (loading && sidebarItems.isEmpty()) { CollaborationListSkeletonView(modifier = Modifier.fillMaxSize()) } else if (filteredItems.isEmpty()) { - Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - Icon(Icons.Outlined.Groups, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(36.dp)) - Text("暂无协作空间或助手", color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) - Text("点击右上角 + 创建你的第一个助手或协作群组", color = c.textSecondary, fontSize = 13.sp) + Box( + modifier = Modifier + .fillMaxSize() + .padding(bottom = BOTTOM_DOCK_CLEARANCE), + contentAlignment = Alignment.Center, + ) { + if (searchText.isNotBlank()) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon(Icons.Outlined.Search, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(32.dp)) + Text("没有匹配的群组或助手", color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) + Text( + text = "清除搜索", + color = c.accent, + fontSize = 13.5.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { searchText = "" } + .padding(horizontal = 12.dp, vertical = 6.dp), + ) + } + } else { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon(Icons.Outlined.Groups, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(36.dp)) + Text("暂无协作空间或助手", color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) + Text("点击右上角 + 创建你的第一个助手或协作群组", color = c.textSecondary, fontSize = 13.sp) + } } } } else { LazyColumn( modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 32.dp), + contentPadding = PaddingValues( + start = 16.dp, + end = 16.dp, + top = 4.dp, + bottom = BOTTOM_DOCK_CLEARANCE + 18.dp, + ), verticalArrangement = Arrangement.spacedBy(12.dp), ) { // Supervisor Slot @@ -537,8 +589,8 @@ fun CollaborationScreen( val groupEntries = filteredItems.filter { item -> item.id != supervisorItem?.id && item.groupId == group.groupId } - if (groupEntries.isNotEmpty() || searchText.isEmpty()) { - val isCollapsed = collapsedGroupIds.contains(group.groupId) + if (groupEntries.isNotEmpty() || searchText.isBlank()) { + val isCollapsed = searchText.isBlank() && collapsedGroupIds.contains(group.groupId) var showGroupMenu by remember { mutableStateOf(false) } Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { @@ -577,22 +629,23 @@ fun CollaborationScreen( ) { Icon(Icons.Outlined.MoreHoriz, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(16.dp)) } - DropdownMenu( + VibexDropdownMenu( expanded = showGroupMenu, onDismissRequest = { showGroupMenu = false }, ) { - DropdownMenuItem( - text = { Text("重命名分组") }, - leadingIcon = { Icon(Icons.Outlined.Edit, contentDescription = null, modifier = Modifier.size(17.dp)) }, + VibexDropdownMenuItem( + text = "重命名分组", + leadingIcon = Icons.Outlined.Edit, onClick = { showGroupMenu = false renameContactGroupText = group.name renamingContactGroup = group }, ) - DropdownMenuItem( - text = { Text("删除分组", color = c.danger) }, - leadingIcon = { Icon(Icons.Outlined.DeleteOutline, contentDescription = null, tint = c.danger, modifier = Modifier.size(17.dp)) }, + VibexDropdownMenuItem( + text = "删除分组", + leadingIcon = Icons.Outlined.DeleteOutline, + tint = c.danger, onClick = { showGroupMenu = false scope.launch { @@ -1187,7 +1240,7 @@ private fun CollabContactRow( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - val previewText = item.lastMessage?.preview + val previewText = item.lastMessage?.preview?.let(::collabMessagePreviewText)?.ifBlank { null } ?: if (item.isGroup) "点击进入群聊" else "点击发起私聊" Text( text = previewText, @@ -1214,23 +1267,23 @@ private fun CollabContactRow( } } - DropdownMenu( + VibexDropdownMenu( expanded = showMenu, onDismissRequest = { showMenu = false }, ) { if (item.unreadCount > 0) { - DropdownMenuItem( - text = { Text("标为已读") }, - leadingIcon = { Icon(Icons.Outlined.MarkChatRead, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "标为已读", + leadingIcon = Icons.Outlined.MarkChatRead, onClick = { showMenu = false onMarkRead(true) }, ) } else { - DropdownMenuItem( - text = { Text("标为未读") }, - leadingIcon = { Icon(Icons.Outlined.MarkChatUnread, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "标为未读", + leadingIcon = Icons.Outlined.MarkChatUnread, onClick = { showMenu = false onMarkRead(false) @@ -1241,15 +1294,9 @@ private fun CollabContactRow( if (!item.isGroup && item.member != null) { val member = item.member!! val nextSup = !member.isSupervisor - DropdownMenuItem( - text = { Text(if (nextSup) "设为主管" else "取消主管身份") }, - leadingIcon = { - Icon( - if (nextSup) Icons.Outlined.Star else Icons.Outlined.StarOutline, - contentDescription = null, - modifier = Modifier.size(18.dp), - ) - }, + VibexDropdownMenuItem( + text = if (nextSup) "设为主管" else "取消主管身份", + leadingIcon = if (nextSup) Icons.Outlined.Star else Icons.Outlined.StarOutline, onClick = { showMenu = false onToggleSupervisor(member.resolvedIdentityId, nextSup) @@ -1258,27 +1305,20 @@ private fun CollabContactRow( } if (item.isGroup) { - HorizontalDivider() + VibexDropdownDivider() CollabTagPalette.presets.forEach { tag -> - DropdownMenuItem( - text = { Text("标签颜色:${tag.label}") }, - leadingIcon = { - Box( - modifier = Modifier - .size(12.dp) - .clip(CircleShape) - .background(tag.color), - ) - }, + VibexDropdownMenuItem( + text = "标签颜色:${tag.label}", + leadingDotColor = tag.color, onClick = { showMenu = false onUpdateSpaceTagColor(item.targetSpaceId, tag.id) }, ) } - DropdownMenuItem( - text = { Text("清除标签颜色") }, - leadingIcon = { Icon(Icons.Outlined.Palette, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "清除标签颜色", + leadingIcon = Icons.Outlined.Palette, onClick = { showMenu = false onUpdateSpaceTagColor(item.targetSpaceId, null) @@ -1287,20 +1327,20 @@ private fun CollabContactRow( } if (contactGroups.isNotEmpty()) { - HorizontalDivider() + VibexDropdownDivider() contactGroups.forEach { group -> - DropdownMenuItem( - text = { Text("移至分组:${group.name}") }, - leadingIcon = { Icon(Icons.Outlined.Folder, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "移至分组:${group.name}", + leadingIcon = Icons.Outlined.Folder, onClick = { showMenu = false onMoveToContactGroup(group.groupId) }, ) } - DropdownMenuItem( - text = { Text("移出分组(未分组)") }, - leadingIcon = { Icon(Icons.Outlined.Close, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "移出分组(未分组)", + leadingIcon = Icons.Outlined.Close, onClick = { showMenu = false onMoveToContactGroup(null) @@ -1308,10 +1348,11 @@ private fun CollabContactRow( ) } - HorizontalDivider() - DropdownMenuItem( - text = { Text(if (item.isGroup) "删除群组" else "删除助手", color = c.danger) }, - leadingIcon = { Icon(Icons.Outlined.DeleteOutline, contentDescription = null, tint = c.danger, modifier = Modifier.size(18.dp)) }, + VibexDropdownDivider() + VibexDropdownMenuItem( + text = if (item.isGroup) "删除群组" else "删除助手", + leadingIcon = Icons.Outlined.DeleteOutline, + tint = c.danger, onClick = { showMenu = false onDelete() @@ -1366,25 +1407,34 @@ private fun CollaborationChatView( val scope = rememberCoroutineScope() val clipboard = LocalClipboardManager.current val listState = rememberLazyListState() - val spaceId = item.targetSpaceId - var messages by remember { mutableStateOf>(emptyList()) } - var scheduled by remember { mutableStateOf>(emptyList()) } - var cards by remember { mutableStateOf>(emptyList()) } - var spaceMembers by remember { mutableStateOf>(emptyList()) } - - var inputText by remember { mutableStateOf("") } - var selectedTargets by remember { mutableStateOf>(emptyList()) } - var replyingTo by remember { mutableStateOf(null) } - var delaySeconds by remember { mutableIntStateOf(0) } + val (conv, messageLookup) = rememberCollabConversationController( + spaceId = spaceId, + threadId = item.threadId, + isGroup = item.isGroup, + model = model, + listState = listState, + ) + val messages = conv.messages + val scheduled = conv.scheduled + val cards = conv.cards + val spaceMembers = conv.spaceMembers + val cardsById = remember(cards) { cards.associateBy { it.id } } + + var showExpandedComposer by remember(spaceId) { mutableStateOf(false) } + var inputValue by remember(spaceId) { mutableStateOf(androidx.compose.ui.text.input.TextFieldValue("")) } + val inputText = inputValue.text + var sendError by remember(spaceId) { mutableStateOf(null) } + var pendingOperationId by remember(spaceId) { mutableStateOf(null) } + var selectedTargets by remember(spaceId) { mutableStateOf>(emptyList()) } + var replyingTo by remember(spaceId) { mutableStateOf(null) } + var delaySeconds by remember(spaceId) { mutableIntStateOf(0) } var showDelayMenu by remember { mutableStateOf(false) } var sending by remember { mutableStateOf(false) } - var loading by remember { mutableStateOf(true) } var showDetailSheet by remember { mutableStateOf(false) } var headerReactionTrigger by remember { mutableIntStateOf(0) } - - val questionDrafts = remember { mutableStateMapOf() } + val questionDrafts = remember(spaceId) { mutableStateMapOf() } val agentMembers = remember(spaceMembers, item) { if (item.isGroup) { @@ -1409,38 +1459,7 @@ private fun CollaborationChatView( } val isChatActive = remember(messages) { - messages.any { it.streaming } || - messages.any { m -> m.receipts.any { it.isProcessing } } - } - - fun loadChatState(silent: Boolean = false) { - scope.launch { - if (!silent && messages.isEmpty()) loading = true - runCatching { - model.fetchCollabChatState(spaceId, item.isGroup) - }.onSuccess { (page, members) -> - val prevCount = messages.size - messages = page.messages - scheduled = page.scheduled - cards = page.cards - if (item.isGroup) spaceMembers = members - page.messages.lastOrNull()?.seq?.let { lastSeq -> - runCatching { model.markCollabThreadRead(item.threadId, lastSeq, true) } - } - if (page.messages.size > prevCount && page.messages.isNotEmpty()) { - runCatching { listState.animateScrollToItem(page.messages.lastIndex) } - } - } - loading = false - } - } - - LaunchedEffect(spaceId) { - loadChatState(silent = false) - while (isActive) { - delay(2_500L) - loadChatState(silent = true) - } + messages.any { it.streaming } || messages.any { m -> m.receipts.any { it.isProcessing } } } fun memberAvatarConfig(sender: String, isSystem: Boolean): CollabBotAvatarConfig { @@ -1485,25 +1504,46 @@ private fun CollaborationChatView( val text = inputText.trim() if (text.isEmpty() || sending) return sending = true + sendError = null val targets = selectedTargets - val replyId = replyingTo?.id + val replyTo = replyingTo + val replyId = replyTo?.id val delaySec = if (delaySeconds > 0) delaySeconds else null - inputText = "" - replyingTo = null - delaySeconds = 0 + val savedDelay = delaySeconds + val savedInput = inputValue + val opId = pendingOperationId ?: java.util.UUID.randomUUID().toString().lowercase() + pendingOperationId = opId scope.launch { - runCatching { + val result = runCatching { model.postCollabMessage( spaceId = spaceId, content = text, to = targets, inReplyTo = replyId, delaySeconds = delaySec, + operationId = opId, ) } sending = false - loadChatState(silent = true) - onMutated() + if (result.isSuccess) { + pendingOperationId = null + if (inputValue.text == savedInput.text) { + inputValue = androidx.compose.ui.text.input.TextFieldValue("") + selectedTargets = emptyList() + replyingTo = null + delaySeconds = 0 + } + conv.unreadNewCount = 0 + conv.syncIncrementalTail(forceScrollToBottom = true) + onMutated() + } else { + // Keep draft, targets, reply and operationId so a retry is idempotent. + sendError = "发送失败:" + (result.exceptionOrNull()?.message?.take(120) ?: "网络错误") + ",点击发送重试" + if (inputValue.text.isEmpty()) inputValue = savedInput + replyingTo = replyTo + selectedTargets = targets + delaySeconds = savedDelay + } } } @@ -1528,7 +1568,6 @@ private fun CollaborationChatView( Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = "返回", tint = c.textPrimary, modifier = Modifier.size(20.dp)) } - // Center Interactive Header (tap plays bot emote!) Row( modifier = Modifier .weight(1f) @@ -1538,17 +1577,8 @@ private fun CollaborationChatView( horizontalArrangement = Arrangement.Center, ) { if (item.isGroup) { - val configs = if (agentMembers.isNotEmpty()) { - agentMembers.map { it.botAvatar } - } else { - item.membersPreview.map { it.botAvatar } - } - CollabGroupAvatarView( - avatars = configs, - tagColorHex = item.tagColor, - size = 28.dp, - sessionActive = isChatActive, - ) + val configs = if (agentMembers.isNotEmpty()) agentMembers.map { it.botAvatar } else item.membersPreview.map { it.botAvatar } + CollabGroupAvatarView(avatars = configs, tagColorHex = item.tagColor, size = 28.dp, sessionActive = isChatActive) } else { MemberBotAvatarView( config = item.member?.botAvatar ?: CollabBotAvatarConfig.derive(item.displayName), @@ -1559,34 +1589,15 @@ private fun CollaborationChatView( ) } Spacer(modifier = Modifier.width(8.dp)) - Text( - text = item.displayName, - color = c.textPrimary, - fontSize = 15.sp, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) + Text(item.displayName, color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) if (item.isGroup) { Spacer(modifier = Modifier.width(4.dp)) - Text( - text = "(${maxOf(item.memberCount, agentMembers.size)})", - color = c.textSecondary, - fontSize = 12.sp, - ) + Text("(${maxOf(item.memberCount, agentMembers.size)})", style = TextStyle(color = c.textSecondary, fontSize = 12.sp, fontFeatureSettings = "tnum")) } } - IconButton( - onClick = { showDetailSheet = true }, - modifier = Modifier.size(34.dp), - ) { - Icon( - if (item.isGroup) Icons.Outlined.Groups else Icons.Outlined.Tune, - contentDescription = "详情配置", - tint = c.textPrimary, - modifier = Modifier.size(19.dp), - ) + IconButton(onClick = { showDetailSheet = true }, modifier = Modifier.size(34.dp)) { + Icon(if (item.isGroup) Icons.Outlined.Groups else Icons.Outlined.Tune, contentDescription = "详情配置", tint = c.textPrimary, modifier = Modifier.size(19.dp)) } } @@ -1595,17 +1606,11 @@ private fun CollaborationChatView( // Scheduled Messages Banner if (scheduled.isNotEmpty()) { Column( - modifier = Modifier - .fillMaxWidth() - .background(Color(0xFFF97316).copy(alpha = 0.08f)) - .padding(horizontal = 14.dp, vertical = 8.dp), + modifier = Modifier.fillMaxWidth().background(Color(0xFFF97316).copy(alpha = 0.08f)).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { scheduled.forEach { sched -> - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Icon(Icons.Outlined.Schedule, contentDescription = null, tint = Color(0xFFF97316), modifier = Modifier.size(14.dp)) Column(modifier = Modifier.weight(1f)) { Text(sched.content, color = c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis) @@ -1618,10 +1623,8 @@ private fun CollaborationChatView( fontWeight = FontWeight.SemiBold, modifier = Modifier.clickable { scope.launch { - runCatching { - model.execCollabCommand("space.cancelScheduledMessage", mapOf("scheduleId" to sched.id)) - } - loadChatState(silent = true) + runCatching { model.execCollabCommand("space.cancelScheduledMessage", mapOf("scheduleId" to sched.id)) } + conv.syncIncrementalTail() } }, ) @@ -1632,21 +1635,14 @@ private fun CollaborationChatView( // Message Stream Box(modifier = Modifier.weight(1f)) { - if (loading && messages.isEmpty()) { + if (conv.loading && messages.isEmpty()) { CollaborationChatSkeletonView(modifier = Modifier.fillMaxSize()) } else if (messages.isEmpty()) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { Icon(Icons.Outlined.Groups, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(32.dp)) Text("开始对话", color = c.textPrimary, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) - Text( - text = if (item.isGroup) "输入消息并使用 @ 指定群内助手协作" else "直接发送消息与助手对话", - color = c.textSecondary, - fontSize = 13.sp, - ) + Text(if (item.isGroup) "输入消息并使用 @ 指定群内助手协作" else "直接发送消息与助手对话", color = c.textSecondary, fontSize = 13.sp) } } } else { @@ -1656,39 +1652,51 @@ private fun CollaborationChatView( contentPadding = PaddingValues(horizontal = 14.dp, vertical = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { + if (conv.hasMoreBefore) { + item(key = "header:load-earlier") { + CollabLoadEarlierBanner(loading = conv.loadingEarlier, onLoadEarlier = conv::loadEarlierMessages) + } + } + items(messages, key = { it.id }) { msg -> - val repliedMsg = msg.inReplyTo?.let { refId -> messages.firstOrNull { it.id == refId || it.rawId == refId } } + val repliedMsg = lookupCollabReplyMessage(messageLookup, msg.inReplyTo) + val isMsgExpanded = conv.expandedMessageIds[msg.id] == true CollabMessageRow( message = msg, repliedMessage = repliedMsg, + knownCardsById = cardsById, + isExpanded = isMsgExpanded, isGroup = item.isGroup, leadMemberId = spaceSummary?.leadMemberId, avatarConfig = memberAvatarConfig(msg.envelope.sender, msg.envelope.isSystem), agentMembers = agentMembers, + onToggleExpand = { conv.expandedMessageIds[msg.id] = !isMsgExpanded }, + onOpenFullReader = { conv.readerMessage = msg }, onAvatarTap = { - if (!msg.isFromUser && !msg.envelope.isSystem) { - openMemberUnderlyingSession(msg.envelope.sender) - } + if (!msg.isFromUser && !msg.envelope.isSystem) openMemberUnderlyingSession(msg.envelope.sender) }, onReact = { emoji -> scope.launch { runCatching { model.reactCollab(spaceId, msg.id, emoji) } - loadChatState(silent = true) + conv.syncIncrementalTail() } }, onReply = { replyingTo = msg }, - onCopy = { clipboard.setText(AnnotatedString(msg.envelope.content)) }, + onCopy = { + val clean = parseCollabStructuredMessage(msg.envelope.content).cleanText.ifBlank { msg.envelope.content } + clipboard.setText(AnnotatedString(clean)) + }, onCollect = { scope.launch { - val title = msg.envelope.content.take(40).ifBlank { "收藏消息" } + val clean = parseCollabStructuredMessage(msg.envelope.content).cleanText.ifBlank { msg.envelope.content } runCatching { model.execCollabCommand( "space.addCollectionItem", mapOf( "spaceId" to spaceId, "kind" to "message", - "name" to title, - "textContent" to msg.envelope.content, + "name" to clean.take(40).ifBlank { "收藏消息" }, + "textContent" to clean, "sourceMessageId" to msg.id, ), ) @@ -1697,23 +1705,26 @@ private fun CollaborationChatView( }, onDistill = { scope.launch { - runCatching { - model.execCollabCommand( - "space.memory.distillMessage", - mapOf("spaceId" to spaceId, "messageId" to msg.id), - ) - } + runCatching { model.execCollabCommand("space.memory.distillMessage", mapOf("spaceId" to spaceId, "messageId" to msg.id)) } } }, onStopReceiptTurn = { receiptMemberId -> scope.launch { runCatching { model.cancelCollabSpaceTurn(spaceId, receiptMemberId) } - loadChatState(silent = true) + conv.syncIncrementalTail() } }, ) } } + + if (!conv.isNearBottom && messages.isNotEmpty()) { + CollabJumpToBottomPill( + unreadNewCount = conv.unreadNewCount, + onClick = conv::jumpToBottom, + modifier = Modifier.align(Alignment.BottomEnd).padding(end = 14.dp, bottom = 12.dp), + ) + } } } @@ -1721,122 +1732,67 @@ private fun CollaborationChatView( val pendingCards = remember(cards) { cards.filter { it.isPending } } if (pendingCards.isNotEmpty()) { Column( - modifier = Modifier - .fillMaxWidth() - .background(c.bgElevated) - .padding(horizontal = 14.dp, vertical = 8.dp), + modifier = Modifier.fillMaxWidth().background(c.bgElevated).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { pendingCards.forEach { card -> - Surface( - shape = RoundedCornerShape(12.dp), - color = c.card, - border = BorderStroke(0.5.dp, c.stroke), - modifier = Modifier.fillMaxWidth(), - ) { - Column( - modifier = Modifier.padding(12.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - Icon( - if (card.kind == "approval") Icons.Outlined.Shield else Icons.Outlined.HelpOutline, - contentDescription = null, - tint = Color(0xFFF97316), - modifier = Modifier.size(15.dp), - ) - Text( - text = if (card.kind == "approval") "待审批请求" else "助手提问", - color = c.textPrimary, - fontSize = 12.sp, - fontWeight = FontWeight.Bold, - ) + Surface(shape = RoundedCornerShape(12.dp), color = c.card, border = BorderStroke(0.5.dp, c.stroke), modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Icon(if (card.kind == "approval") Icons.Outlined.Shield else Icons.Outlined.HelpOutline, contentDescription = null, tint = Color(0xFFF97316), modifier = Modifier.size(15.dp)) + Text(if (card.kind == "approval") "待审批请求" else "助手提问", color = c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.Bold) Spacer(modifier = Modifier.weight(1f)) - val actionName = card.action ?: card.command - if (!actionName.isNullOrBlank()) { - Text( - text = actionName, - color = c.textSecondary, - fontSize = 11.sp, - fontFamily = FontFamily.Monospace, - ) + (card.action ?: card.command)?.takeIf { it.isNotBlank() }?.let { + Text(it, color = c.textSecondary, fontSize = 11.sp, fontFamily = FontFamily.Monospace) } } - - val promptText = card.question ?: card.reason ?: card.action - if (!promptText.isNullOrBlank()) { - Text(promptText, color = c.textPrimary, fontSize = 13.sp) + (card.question ?: card.reason ?: card.action)?.takeIf { it.isNotBlank() }?.let { + Text(it, color = c.textPrimary, fontSize = 13.sp) } - if (card.kind == "approval") { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Button( onClick = { scope.launch { runCatching { model.resolveCollabPendingCard(card.id, decision = "approved") } - loadChatState(silent = true) + conv.syncIncrementalTail() } }, colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF22C55E)), contentPadding = PaddingValues(horizontal = 14.dp, vertical = 6.dp), - ) { - Text("批准", fontSize = 12.sp, fontWeight = FontWeight.SemiBold) - } + ) { Text("批准", fontSize = 12.sp, fontWeight = FontWeight.SemiBold) } OutlinedButton( onClick = { scope.launch { runCatching { model.resolveCollabPendingCard(card.id, decision = "denied", declined = true) } - loadChatState(silent = true) + conv.syncIncrementalTail() } }, contentPadding = PaddingValues(horizontal = 14.dp, vertical = 6.dp), - ) { - Text("拒绝", color = c.danger, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) - } + ) { Text("拒绝", color = c.danger, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) } } } else { if (card.options.isNotEmpty()) { - Row( - modifier = Modifier.horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { + Row(modifier = Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { card.options.forEach { opt -> Surface( onClick = { scope.launch { runCatching { model.resolveCollabPendingCard(card.id, answer = opt) } - loadChatState(silent = true) + conv.syncIncrementalTail() } }, shape = RoundedCornerShape(50), color = Color(0xFF2563EB).copy(alpha = 0.12f), ) { - Text( - text = opt, - color = Color(0xFF2563EB), - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp), - ) + Text(opt, color = Color(0xFF2563EB), fontSize = 12.sp, fontWeight = FontWeight.Medium, modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)) } } } } - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { val draft = questionDrafts[card.id].orEmpty() - OutlinedTextField( - value = draft, - onValueChange = { questionDrafts[card.id] = it }, - placeholder = { Text("输入回答…", fontSize = 12.sp) }, - singleLine = true, - modifier = Modifier.weight(1f), - ) + OutlinedTextField(value = draft, onValueChange = { questionDrafts[card.id] = it }, placeholder = { Text("输入回答…", fontSize = 12.sp) }, singleLine = true, modifier = Modifier.weight(1f)) Button( onClick = { val ans = draft.trim() @@ -1844,25 +1800,21 @@ private fun CollaborationChatView( questionDrafts.remove(card.id) scope.launch { runCatching { model.resolveCollabPendingCard(card.id, answer = ans) } - loadChatState(silent = true) + conv.syncIncrementalTail() } } }, enabled = draft.trim().isNotEmpty(), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - ) { - Text("发送", fontSize = 12.sp) - } + ) { Text("发送", fontSize = 12.sp) } TextButton( onClick = { scope.launch { runCatching { model.resolveCollabPendingCard(card.id, declined = true) } - loadChatState(silent = true) + conv.syncIncrementalTail() } }, - ) { - Text("跳过", color = c.textSecondary, fontSize = 12.sp) - } + ) { Text("跳过", color = c.textSecondary, fontSize = 12.sp) } } } } @@ -1880,198 +1832,183 @@ private fun CollaborationChatView( .padding(horizontal = 14.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - // Reply Quote Banner if (replyingTo != null) { val rep = replyingTo!! Row( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(8.dp)) - .background(c.bgElevated) - .padding(horizontal = 10.dp, vertical = 6.dp), + modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(c.bgElevated).padding(horizontal = 10.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { Icon(Icons.AutoMirrored.Outlined.Reply, contentDescription = null, tint = Color(0xFF2563EB), modifier = Modifier.size(14.dp)) - Text( - text = "回复 ${rep.envelope.displaySender}:${rep.envelope.content}", - color = c.textSecondary, - fontSize = 12.sp, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - Icon( - Icons.Outlined.Close, - contentDescription = "取消回复", - tint = c.textSecondary, - modifier = Modifier - .size(16.dp) - .clickable { replyingTo = null }, - ) + Text("回复 ${rep.envelope.displaySender}:${collabMessagePreviewText(rep.envelope.content)}", color = c.textSecondary, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + Icon(Icons.Outlined.Close, contentDescription = "取消回复", tint = c.textSecondary, modifier = Modifier.size(16.dp).clickable { replyingTo = null }) } } - // Group @ Mention Selector Bar if (item.isGroup && agentMembers.isNotEmpty()) { Row( - modifier = Modifier - .fillMaxWidth() - .horizontalScroll(rememberScrollState()), + modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, ) { val allSelected = selectedTargets.contains("@all") - Surface( - onClick = { toggleTarget("@all") }, - shape = RoundedCornerShape(50), - color = if (allSelected) Color(0xFF2563EB) else c.bgElevated, - ) { - Text( - text = "@全体成员", - color = if (allSelected) Color.White else c.textPrimary, - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp), - ) + Surface(onClick = { toggleTarget("@all") }, shape = RoundedCornerShape(50), color = if (allSelected) Color(0xFF2563EB) else c.bgElevated) { + Text("@全体成员", color = if (allSelected) Color.White else c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.Medium, modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)) } - agentMembers.forEach { member -> val selected = selectedTargets.contains(member.resolvedIdentityId) - Surface( - onClick = { toggleTarget(member.resolvedIdentityId) }, - shape = RoundedCornerShape(50), - color = if (selected) Color(0xFF2563EB) else c.bgElevated, - ) { - Row( - modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(5.dp), - ) { - MemberBotAvatarView( - config = member.botAvatar, - size = 17.dp, - sessionActive = false, - isLead = spaceSummary?.leadMemberId == member.resolvedIdentityId, - ) - Text( - text = "@${member.nickname}", - color = if (selected) Color.White else c.textPrimary, - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - ) + Surface(onClick = { toggleTarget(member.resolvedIdentityId) }, shape = RoundedCornerShape(50), color = if (selected) Color(0xFF2563EB) else c.bgElevated) { + Row(modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { + MemberBotAvatarView(config = member.botAvatar, size = 17.dp, sessionActive = false, isLead = spaceSummary?.leadMemberId == member.resolvedIdentityId) + Text("@${member.nickname}", color = if (selected) Color.White else c.textPrimary, fontSize = 12.sp, fontWeight = FontWeight.Medium) } } } } } - // Input Row + val mentionToken = if (item.isGroup && inputValue.selection.collapsed) { + dev.vibex.companion.mentionTokenAt(inputValue.text, inputValue.selection.start) + } else { + null + } + if (mentionToken != null) { + val q = mentionToken.query + val showAll = q.isEmpty() || "全体成员".contains(q, ignoreCase = true) || "all".startsWith(q, ignoreCase = true) + val matches = agentMembers.filter { it.nickname.contains(q, ignoreCase = true) } + fun insertMention(label: String, target: String) { + val (nextText, caret) = dev.vibex.companion.applyMention(inputValue.text, mentionToken, label) + inputValue = androidx.compose.ui.text.input.TextFieldValue(nextText, androidx.compose.ui.text.TextRange(caret)) + if (!selectedTargets.contains(target)) toggleTarget(target) + } + if (showAll || matches.isNotEmpty()) { + Column( + modifier = Modifier.fillMaxWidth().heightIn(max = 220.dp).clip(RoundedCornerShape(16.dp)).background(c.card) + .border(0.75.dp, c.stroke, RoundedCornerShape(16.dp)).verticalScroll(rememberScrollState()).padding(vertical = 4.dp), + ) { + if (showAll) { + Text("@全体成员", color = c.textPrimary, fontSize = 14.sp, modifier = Modifier.fillMaxWidth().clickable { insertMention("全体成员", "@all") }.padding(horizontal = 14.dp, vertical = 10.dp)) + } + matches.forEach { member -> + Text("@" + member.nickname, color = c.textPrimary, fontSize = 14.sp, modifier = Modifier.fillMaxWidth().clickable { insertMention(member.nickname, member.resolvedIdentityId) }.padding(horizontal = 14.dp, vertical = 10.dp)) + } + } + } + } + + sendError?.let { err -> + Text(err, color = Color(0xFFE5484D), fontSize = 12.sp, modifier = Modifier.fillMaxWidth().padding(horizontal = 6.dp)) + } + + val composerShape = RoundedCornerShape(26.dp) + val canSend = inputText.trim().isNotEmpty() && !sending + val showExpandEditorButton = inputText.length > 80 || inputText.contains('\n') Row( + modifier = Modifier.fillMaxWidth() + .shadow( + elevation = if (c.isDark) 8.dp else 4.dp, + shape = composerShape, + ambientColor = Color.Black.copy(alpha = if (c.isDark) 0.22f else 0.05f), + spotColor = Color.Black.copy(alpha = if (c.isDark) 0.28f else 0.08f), + ) + .clip(composerShape).background(c.card).border(0.75.dp, c.stroke, composerShape) + .padding(start = 10.dp, end = 7.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(8.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), ) { if (item.isGroup) { - Box { + Box(modifier = Modifier.padding(bottom = 2.dp)) { Surface( onClick = { showDelayMenu = true }, shape = RoundedCornerShape(50), - color = if (delaySeconds > 0) Color(0xFFF97316).copy(alpha = 0.14f) else c.bgElevated, + color = if (delaySeconds > 0) Color(0xFFF97316).copy(alpha = 0.14f) else c.textPrimary.copy(alpha = 0.06f), ) { - Row( - modifier = Modifier.padding(horizontal = 9.dp, vertical = 9.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - ) { - Icon( - Icons.Outlined.Schedule, - contentDescription = "定时发送", - tint = if (delaySeconds > 0) Color(0xFFF97316) else c.textSecondary, - modifier = Modifier.size(16.dp), - ) + Row(modifier = Modifier.padding(horizontal = 9.dp, vertical = 7.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { + Icon(Icons.Outlined.Schedule, contentDescription = "定时发送", tint = if (delaySeconds > 0) Color(0xFFF97316) else c.textSecondary, modifier = Modifier.size(16.dp)) if (delaySeconds > 0) { - Text( - text = "${delaySeconds}s", - color = Color(0xFFF97316), - fontSize = 11.sp, - fontWeight = FontWeight.Bold, - ) + Text("${delaySeconds}s", style = TextStyle(color = Color(0xFFF97316), fontSize = 11.sp, fontWeight = FontWeight.Bold, fontFeatureSettings = "tnum")) } } } - DropdownMenu( - expanded = showDelayMenu, - onDismissRequest = { showDelayMenu = false }, - ) { - listOf( - 0 to "立即发送", - 30 to "30 秒后", - 60 to "1 分钟后", - 300 to "5 分钟后", - 900 to "15 分钟后", - ).forEach { (sec, label) -> - DropdownMenuItem( - text = { Text(label) }, - trailingIcon = { - if (delaySeconds == sec) { - Icon(Icons.Outlined.Check, contentDescription = null, modifier = Modifier.size(16.dp)) - } - }, - onClick = { - delaySeconds = sec - showDelayMenu = false - }, - ) + VibexDropdownMenu(expanded = showDelayMenu, onDismissRequest = { showDelayMenu = false }) { + listOf(0 to "立即发送", 30 to "30 秒后", 60 to "1 分钟后", 300 to "5 分钟后", 900 to "15 分钟后").forEach { (sec, label) -> + VibexDropdownMenuItem(text = label, selected = delaySeconds == sec, onClick = { delaySeconds = sec; showDelayMenu = false }) } } } } - Box( - modifier = Modifier - .weight(1f) - .clip(RoundedCornerShape(18.dp)) - .background(c.bgElevated) - .border(0.5.dp, c.stroke, RoundedCornerShape(18.dp)) - .padding(horizontal = 12.dp, vertical = 9.dp), - ) { + Box(modifier = Modifier.weight(1f).heightIn(max = 132.dp).padding(horizontal = 4.dp, vertical = 8.dp)) { if (inputText.isEmpty()) { - Text( - text = if (item.isGroup) "发送消息到 ${item.displayName}…" else "发送消息给 ${item.displayName}…", - color = c.textSecondary, - fontSize = 14.sp, - ) + Text(if (item.isGroup) "发送消息到 ${item.displayName}…" else "发送消息给 ${item.displayName}…", color = c.textTertiary, fontSize = 15.sp) } BasicTextField( - value = inputText, - onValueChange = { inputText = it }, - textStyle = TextStyle(color = c.textPrimary, fontSize = 14.sp), + value = inputValue, + onValueChange = { + if (it.text != inputValue.text) { + sendError = null + pendingOperationId = null + } + inputValue = it + }, + textStyle = TextStyle(color = c.textPrimary, fontSize = 15.sp, lineHeight = 20.sp), cursorBrush = SolidColor(c.accent), - maxLines = 4, + maxLines = 6, modifier = Modifier.fillMaxWidth(), ) } - val canSend = inputText.trim().isNotEmpty() && !sending - IconButton( - onClick = ::sendMessage, - enabled = canSend, - modifier = Modifier - .size(34.dp) - .clip(CircleShape) - .background(if (canSend) Color(0xFF2563EB) else c.textSecondary.copy(alpha = 0.25f)), + if (showExpandEditorButton) { + IconButton(onClick = { showExpandedComposer = true }, modifier = Modifier.padding(bottom = 2.dp).size(32.dp)) { + Icon(Icons.Outlined.OpenInFull, contentDescription = "展开编辑", tint = c.textSecondary, modifier = Modifier.size(16.dp)) + } + } + + Box( + modifier = Modifier.size(36.dp).clip(CircleShape) + .background(if (canSend) c.textPrimary else c.textPrimary.copy(alpha = if (c.isDark) 0.16f else 0.11f)) + .clickable(enabled = canSend, onClick = ::sendMessage), + contentAlignment = Alignment.Center, ) { - Icon( - Icons.Outlined.ArrowUpward, - contentDescription = "发送", - tint = Color.White, - modifier = Modifier.size(18.dp), - ) + Icon(Icons.Outlined.ArrowUpward, contentDescription = "发送", tint = if (canSend) c.bg else c.textTertiary, modifier = Modifier.size(18.dp)) } } } } + conv.readerMessage?.let { targetMsg -> + CollabFullMessageReaderSheet( + message = targetMsg, + avatarConfig = memberAvatarConfig(targetMsg.envelope.sender, targetMsg.envelope.isSystem), + knownCardsById = cardsById, + onDismiss = { conv.readerMessage = null }, + ) + } + + if (showExpandedComposer) { + CollabExpandedComposerSheet( + title = item.displayName, + isGroup = item.isGroup, + leadMemberId = spaceSummary?.leadMemberId, + agentMembers = agentMembers, + selectedTargets = selectedTargets, + replyingTo = replyingTo, + inputValue = inputValue, + sending = sending, + onInputChange = { + if (it.text != inputValue.text) { + sendError = null + pendingOperationId = null + } + inputValue = it + }, + onToggleTarget = ::toggleTarget, + onClearReply = { replyingTo = null }, + onSend = ::sendMessage, + onDismiss = { showExpandedComposer = false }, + ) + } + if (showDetailSheet) { CollaborationDetailSheet( state = state, @@ -2082,7 +2019,7 @@ private fun CollaborationChatView( directAssistants = directAssistants, onDismiss = { showDetailSheet = false }, onMutated = { - loadChatState(silent = true) + conv.refreshNow(refreshMembers = item.isGroup) onMutated() }, onOpenConversation = { convId -> @@ -2102,10 +2039,14 @@ private fun CollaborationChatView( private fun CollabMessageRow( message: CollabSpaceMessage, repliedMessage: CollabSpaceMessage?, + knownCardsById: Map, + isExpanded: Boolean, isGroup: Boolean, leadMemberId: String?, avatarConfig: CollabBotAvatarConfig, agentMembers: List, + onToggleExpand: () -> Unit, + onOpenFullReader: () -> Unit, onAvatarTap: () -> Unit, onReact: (String) -> Unit, onReply: () -> Unit, @@ -2142,7 +2083,7 @@ private fun CollabMessageRow( } Column( - modifier = Modifier.widthIn(max = 290.dp), + modifier = Modifier.widthIn(max = if (message.isFromUser) 292.dp else 324.dp), horizontalAlignment = if (message.isFromUser) Alignment.End else Alignment.Start, verticalArrangement = Arrangement.spacedBy(4.dp), ) { @@ -2207,7 +2148,7 @@ private fun CollabMessageRow( ) { Icon(Icons.AutoMirrored.Outlined.Reply, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(11.dp)) Text( - text = "${repliedMessage.envelope.displaySender}:${repliedMessage.envelope.content}", + text = "${repliedMessage.envelope.displaySender}:${collabMessagePreviewText(repliedMessage.envelope.content)}", color = c.textSecondary, fontSize = 11.sp, maxLines = 1, @@ -2217,29 +2158,28 @@ private fun CollabMessageRow( } // Message Bubble with Context Menu + val bubbleBg = if (message.isFromUser) Color(0xFF2563EB) else c.card Box { Surface( shape = RoundedCornerShape(16.dp), - color = if (message.isFromUser) Color(0xFF2563EB) else c.card, + color = bubbleBg, border = if (message.isFromUser) null else BorderStroke(0.5.dp, c.stroke), modifier = Modifier.combinedClickable( onClick = {}, onLongClick = { showMenu = true }, ), ) { - val displayContent = message.envelope.content.ifEmpty { - if (message.streaming) "思考中…" else "" - } - Text( - text = displayContent, - color = if (message.isFromUser) Color.White else c.textPrimary, - fontSize = 14.sp, - lineHeight = 20.sp, - modifier = Modifier.padding(horizontal = 13.dp, vertical = 9.dp), + CollabRichBubbleContent( + message = message, + knownCardsById = knownCardsById, + bubbleBackground = bubbleBg, + isExpanded = isExpanded, + onToggleExpand = onToggleExpand, + onOpenFullReader = onOpenFullReader, ) } - DropdownMenu( + VibexDropdownMenu( expanded = showMenu, onDismissRequest = { showMenu = false }, ) { @@ -2258,43 +2198,51 @@ private fun CollabMessageRow( ) } } - HorizontalDivider() - DropdownMenuItem( - text = { Text("回复") }, - leadingIcon = { Icon(Icons.AutoMirrored.Outlined.Reply, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownDivider() + VibexDropdownMenuItem( + text = "全屏阅读", + leadingIcon = Icons.Outlined.OpenInFull, + onClick = { + showMenu = false + onOpenFullReader() + }, + ) + VibexDropdownMenuItem( + text = "回复", + leadingIcon = Icons.AutoMirrored.Outlined.Reply, onClick = { showMenu = false onReply() }, ) - DropdownMenuItem( - text = { Text("复制内容") }, - leadingIcon = { Icon(Icons.Outlined.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "复制内容", + leadingIcon = Icons.Outlined.ContentCopy, onClick = { showMenu = false onCopy() }, ) - DropdownMenuItem( - text = { Text("加入空间收藏") }, - leadingIcon = { Icon(Icons.Outlined.BookmarkBorder, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "加入空间收藏", + leadingIcon = Icons.Outlined.BookmarkBorder, onClick = { showMenu = false onCollect() }, ) - DropdownMenuItem( - text = { Text("提炼到空间记忆") }, - leadingIcon = { Icon(Icons.Outlined.Psychology, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "提炼到空间记忆", + leadingIcon = Icons.Outlined.Psychology, onClick = { showMenu = false onDistill() }, ) if (!message.isFromUser && !message.envelope.isSystem) { - DropdownMenuItem( - text = { Text("打开该助手会话") }, - leadingIcon = { Icon(Icons.Outlined.Terminal, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "打开该助手会话", + leadingIcon = Icons.Outlined.Terminal, onClick = { showMenu = false onAvatarTap() @@ -2649,13 +2597,13 @@ private fun CollaborationDetailSheet( IconButton(onClick = { showMemberMenu = true }, modifier = Modifier.size(28.dp)) { Icon(Icons.Outlined.MoreHoriz, contentDescription = null, tint = c.textSecondary, modifier = Modifier.size(18.dp)) } - DropdownMenu( + VibexDropdownMenu( expanded = showMemberMenu, onDismissRequest = { showMemberMenu = false }, ) { - DropdownMenuItem( - text = { Text("查看本群会话") }, - leadingIcon = { Icon(Icons.Outlined.Terminal, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = "查看本群会话", + leadingIcon = Icons.Outlined.Terminal, onClick = { showMemberMenu = false scope.launch { @@ -2668,9 +2616,9 @@ private fun CollaborationDetailSheet( }, ) val isLead = leadMemberId == member.resolvedIdentityId - DropdownMenuItem( - text = { Text(if (isLead) "取消群负责人" else "设为群负责人") }, - leadingIcon = { Icon(Icons.Outlined.Star, contentDescription = null, modifier = Modifier.size(18.dp)) }, + VibexDropdownMenuItem( + text = if (isLead) "取消群负责人" else "设为群负责人", + leadingIcon = Icons.Outlined.Star, onClick = { showMemberMenu = false val nextLead = if (isLead) null else member.resolvedIdentityId @@ -2686,10 +2634,11 @@ private fun CollaborationDetailSheet( } }, ) - HorizontalDivider() - DropdownMenuItem( - text = { Text("移出本群", color = c.danger) }, - leadingIcon = { Icon(Icons.Outlined.PersonRemove, contentDescription = null, tint = c.danger, modifier = Modifier.size(18.dp)) }, + VibexDropdownDivider() + VibexDropdownMenuItem( + text = "移出本群", + leadingIcon = Icons.Outlined.PersonRemove, + tint = c.danger, onClick = { showMemberMenu = false scope.launch { @@ -3723,7 +3672,7 @@ private fun RolesAndTeamsSheet( } } -private fun formatCollabRelativeTime(iso: String): String { +internal fun formatCollabRelativeTime(iso: String): String { val trimmed = iso.trim() if (trimmed.isEmpty()) return "" val millis = runCatching { Instant.parse(trimmed).toEpochMilli() }.getOrNull() diff --git a/app/src/main/java/dev/vibex/companion/app/ui/CompanionApp.kt b/app/src/main/java/dev/vibex/companion/app/ui/CompanionApp.kt index c235b11..f5f8fe3 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/CompanionApp.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/CompanionApp.kt @@ -1,75 +1,117 @@ package dev.vibex.companion.app.ui +import android.widget.Toast +import android.Manifest +import android.content.pm.PackageManager import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.content.ContextCompat +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.ui.platform.LocalContext +import dev.vibex.companion.app.update.AppUpdateManager import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ContentTransform +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.outlined.ChatBubbleOutline -import androidx.compose.material.icons.outlined.GridView -import androidx.compose.material.icons.outlined.Groups -import androidx.compose.material.icons.outlined.Settings -import androidx.compose.material.icons.rounded.ChatBubble +import androidx.compose.material.icons.rounded.CheckCircle import androidx.compose.material.icons.rounded.Computer -import androidx.compose.material.icons.rounded.GridView -import androidx.compose.material.icons.rounded.Groups import androidx.compose.material.icons.rounded.KeyOff -import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.AlertDialog -import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import com.journeyapps.barcodescanner.ScanContract -import com.journeyapps.barcodescanner.ScanOptions import dev.vibex.companion.ConnectionState import dev.vibex.companion.NoticeSeverity +import dev.vibex.companion.app.CloudNodePreference import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.ConnectedSasNotice +import dev.vibex.companion.app.DesktopConnectTarget import dev.vibex.companion.app.Route import dev.vibex.companion.app.UiState +import dev.vibex.companion.app.ui.theme.LocalAppLanguage +import dev.vibex.companion.app.ui.theme.LocalConfirmHighRiskApproval +import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.app.ui.theme.l @Composable fun CompanionApp(state: UiState, model: CompanionModel) { - SplashGate { CompanionShell(state, model) } + CompositionLocalProvider( + LocalAppLanguage provides state.language, + LocalConfirmHighRiskApproval provides state.confirmHighRiskApproval, + ) { + SplashGate { CompanionShell(state, model) } + } } @Composable private fun CompanionShell(state: UiState, model: CompanionModel) { - val scan = rememberLauncherForActivityResult(ScanContract()) { result -> - result.contents?.let(model::pairFromRaw) + val context = LocalContext.current + var showQrScanner by remember { mutableStateOf(false) } + val cameraPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { granted -> + if (granted) { + showQrScanner = true + } else { + model.go(Route.ManualPair) + } } val launchScanner = { - scan.launch(ScanOptions().setDesiredBarcodeFormats(ScanOptions.QR_CODE).setPrompt("对准桌面端二维码即可自动识别连接")) + val granted = ContextCompat.checkSelfPermission( + context, + Manifest.permission.CAMERA, + ) == PackageManager.PERMISSION_GRANTED + if (granted) { + showQrScanner = true + } else { + cameraPermissionLauncher.launch(Manifest.permission.CAMERA) + } } - val fullscreen = state.route is Route.Timeline + + var inNestedCollabChat by remember { mutableStateOf(false) } + + val isTimeline = state.route is Route.Timeline + val isNewThread = state.route is Route.NewThread + val fullscreen = isTimeline || isNewThread val isPairModal = state.route is Route.ManualPair val settingsSub = (state.route as? Route.Settings)?.section != null val inCollabChat = state.route is Route.Collaboration && state.selectedThread != null - var isConversationsChromeHidden by remember { mutableStateOf(false) } - var isCollabChatOpen by remember { mutableStateOf(false) } - val isKeyboardVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0 BackHandler(enabled = fullscreen || isPairModal || settingsSub || inCollabChat || state.route is Route.Folders) { when { @@ -82,8 +124,23 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { } val colors = VibexTheme.colors + val updateManager = remember(context) { AppUpdateManager.getInstance(context) } + val updateState by updateManager.state.collectAsState() + + LaunchedEffect(updateState.statusToast) { + val toastMsg = updateState.statusToast ?: return@LaunchedEffect + Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show() + updateManager.consumeStatusToast() + } + + AppUpdateDialog( + state = updateState, + onConfirmUpdate = { updateManager.startDownloadAndInstall() }, + onDismiss = { updateManager.dismissDialog() }, + ) + state.pendingCloudFallbackOrigin?.let { - val hostName = state.pendingCloudFallbackHostName ?: "VibeX 桌面端" + val hostName = state.pendingCloudFallbackHostName ?: "Dimo 桌面端" AlertDialog( onDismissRequest = { model.cancelSwitchToCloudFallback() }, containerColor = colors.card, @@ -97,7 +154,7 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { }, text = { Text( - "当前与电脑「$hostName」的局域网直连已断开,但检测到可通过「VibeX 云服务 · Beta」继续连接。是否切换至云服务?", + "当前与电脑「$hostName」的局域网直连已断开,但检测到可通过「Dimo 云中继」继续连接。是否切换至云服务?", fontSize = 14.sp, color = colors.textSecondary, ) @@ -140,45 +197,53 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { }, dismissButton = { TextButton(onClick = { model.cancelReplaceMobileDevice() }) { - Text("取消", color = colors.textSecondary) + Text(l("取消", "Cancel"), color = colors.textSecondary) } }, ) } - // The tab shell keeps showing the page it was on while a conversation or the pairing - // sheet slides over it, so the page underneath never changes mid-transition. + if (state.pendingQrNodeChoiceRaw != null) { + AlertDialog( + onDismissRequest = { model.cancelPendingNodeChoice() }, + containerColor = colors.card, + title = { + Text( + l("选择连接节点", "Select Connection Node"), + fontSize = 16.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + }, + text = { + Text( + l( + "你已配置自建云节点(${state.customRelayOrigin}),请选择本次扫码使用的远程通道:", + "You have a custom cloud node configured (${state.customRelayOrigin}). Choose which remote node to use:", + ), + fontSize = 14.sp, + color = colors.textSecondary, + ) + }, + confirmButton = { + TextButton(onClick = { model.confirmPendingNodeChoice(CloudNodePreference.CustomNode) }) { + Text(l("自建云节点", "Custom Node"), fontWeight = FontWeight.SemiBold, color = colors.accent) + } + }, + dismissButton = { + TextButton(onClick = { model.confirmPendingNodeChoice(CloudNodePreference.OfficialCloud) }) { + Text(l("官方云服务", "Official Cloud"), color = colors.textPrimary) + } + }, + ) + } + + // The tab shell keeps showing the page it was on while a conversation, new-thread page, or + // pairing sheet slides over it, so the page underneath never changes mid-transition. val tabRouteHolder = remember { TabRouteHolder() } if (!fullscreen && !isPairModal) tabRouteHolder.route = state.route val tabRoute = tabRouteHolder.route - val tabs = listOf( - LiquidTab( - "对话", - Icons.Outlined.ChatBubbleOutline, - Icons.Rounded.ChatBubble, - tabRoute is Route.Conversations || tabRoute is Route.Folders, - ) { model.go(Route.Conversations) }, - LiquidTab( - "看板", - Icons.Outlined.GridView, - Icons.Rounded.GridView, - tabRoute is Route.Status, - ) { model.go(Route.Status) }, - LiquidTab( - "协作空间", - Icons.Outlined.Groups, - Icons.Rounded.Groups, - tabRoute is Route.Collaboration, - ) { model.go(Route.Collaboration) }, - LiquidTab( - "设置", - Icons.Outlined.Settings, - Icons.Rounded.Settings, - tabRoute is Route.Settings, - ) { model.go(Route.Settings()) }, - ) - val hasServer = state.profiles.isNotEmpty() val authExpired = state.connection == ConnectionState.AuthRequired val manualConnectNeeded = hasServer && !state.autoConnect && state.connection == ConnectionState.Offline @@ -189,6 +254,18 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { toast.conversationId != activeOpenConvId } val hostNotices: @Composable () -> Unit = { + AnimatedVisibility( + visible = state.connectedSasNotice != null, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut(), + ) { + state.connectedSasNotice?.let { notice -> + ConnectedSasCapsule( + notice = notice, + onDismiss = model::dismissConnectedSasNotice, + ) + } + } CompanionToastOverlay( toast = inlineToast, actionBusy = state.attentionActionBusy, @@ -208,6 +285,7 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { state.error?.let { HostBanner(it, hostBannerSeverity(it)) { model.dismissNotice() } } state.notice?.let { HostBanner(it, NoticeSeverity.Info) { model.dismissNotice() } } } + val requiresServer: @Composable (@Composable () -> Unit) -> Unit = { content -> if (showConnectGate) { DesktopEmptyState(state = state, model = model, authExpired = authExpired) @@ -220,6 +298,7 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { Route.ManualPair -> ShellLayer.Pairing else -> if (state.showsLogin) ShellLayer.Login else when (route) { is Route.Timeline -> ShellLayer.Conversation(route.conversationId) + Route.NewThread -> ShellLayer.NewThread else -> ShellLayer.Tabs } } @@ -236,6 +315,9 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { ) } + val shouldShowFloatingDock = !settingsSub && + !(tabRoute is Route.Collaboration && (state.selectedThread != null || inNestedCollabChat)) + GlowBackground { AnimatedContent( targetState = layer, @@ -250,95 +332,169 @@ private fun CompanionShell(state: UiState, model: CompanionModel) { state.error?.let { HostBanner(it, hostBannerSeverity(it)) { model.dismissNotice() } } } } + ShellLayer.Pairing -> PairingCodeScreen( state = state, model = model, onScan = launchScanner, onDismiss = { model.go(Route.Conversations) }, ) + + ShellLayer.NewThread -> Box( + Modifier + .fillMaxSize() + .background(colors.bg) + .statusBarsPadding(), + ) { + NewThreadScreen(state = state, model = model) + Column( + Modifier.align(Alignment.TopCenter), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + hostNotices() + } + } + is ShellLayer.Conversation -> Box( Modifier .fillMaxSize() .background(colors.bg) .statusBarsPadding(), ) { - TimelinePane(state, model, shownLayer.conversationId) - Column(Modifier.align(Alignment.TopCenter)) { + TimelinePane( + state = state, + model = model, + conversationId = shownLayer.conversationId, + onBack = { model.go(Route.Conversations) }, + ) + Column( + Modifier.align(Alignment.TopCenter), + horizontalAlignment = Alignment.CenterHorizontally, + ) { hostNotices() } } - ShellLayer.Tabs -> { - val pageCoversBottomBar = inCollabChat || - (tabRoute is Route.Collaboration && isCollabChatOpen) || - (tabRoute is Route.Conversations && isConversationsChromeHidden) - val showFloatingNavBar = !isKeyboardVisible && !pageCoversBottomBar - - Box(Modifier.fillMaxSize().background(colors.bg)) { - Column( - Modifier - .fillMaxSize() - .statusBarsPadding() - .navigationBarsPadding() - .padding(bottom = if (showFloatingNavBar) 66.dp else 0.dp), - ) { - AnimatedContent( - targetState = tabRoute, - transitionSpec = { tabTransition(initialState, targetState) }, - modifier = Modifier.fillMaxSize(), - label = "tabRoute", - ) { route -> - Box(Modifier.fillMaxSize().background(colors.bg)) { - when (route) { - is Route.Settings -> SettingsScreen( - state = state, - model = model, - section = route.section, - onOpen = { model.go(Route.Settings(it)) }, - onBack = { model.go(Route.Settings()) }, - onScan = launchScanner, - onManualPair = { model.go(Route.ManualPair) }, - ) - Route.Folders -> requiresServer { FoldersScreen(state, model) } - Route.Status -> requiresServer { StatusScreen(state, model) } - Route.Collaboration -> requiresServer { - CollaborationScreen( - state = state, - model = model, - onChatOpenChange = { isCollabChatOpen = it }, - ) - } - else -> requiresServer { - ConversationList( - state = state, - model = model, - onChromeHiddenChange = { isConversationsChromeHidden = it }, - ) - } - } + + ShellLayer.Tabs -> Box(Modifier.fillMaxSize().background(colors.bg)) { + AnimatedContent( + targetState = tabRoute, + transitionSpec = { tabTransition(initialState, targetState) }, + modifier = Modifier + .fillMaxSize() + .statusBarsPadding() + .navigationBarsPadding(), + label = "tabRoute", + ) { route -> + Box(Modifier.fillMaxSize().background(colors.bg)) { + when (route) { + is Route.Settings -> SettingsScreen( + state = state, + model = model, + section = route.section, + onOpen = { model.go(Route.Settings(it)) }, + onBack = { model.go(Route.Settings()) }, + onScan = launchScanner, + onManualPair = { model.go(Route.ManualPair) }, + ) + Route.Folders -> requiresServer { FoldersScreen(state, model) } + Route.Status -> requiresServer { StatusScreen(state, model) } + Route.Collaboration -> requiresServer { + CollaborationScreen( + state = state, + model = model, + onActiveChatChanged = { inNestedCollabChat = it }, + ) } + else -> requiresServer { ConversationList(state, model) } } } - Column( - Modifier - .align(Alignment.TopCenter) - .statusBarsPadding(), - ) { - hostNotices() - } - if (!isKeyboardVisible) { - AnimatedVisibility( - visible = !pageCoversBottomBar, - enter = NavMotion.bottomBarEnter, - exit = NavMotion.bottomBarExit, - modifier = Modifier.align(Alignment.BottomCenter), - ) { - LiquidNavBar(tabs = tabs) - } - } + } + + AnimatedVisibility( + visible = shouldShowFloatingDock, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier + .align(Alignment.BottomCenter) + .navigationBarsPadding(), + ) { + FloatingWorkspaceCapsuleDock( + selected = tabRoute.destination, + collabUnreadCount = state.collabUnreadCount, + onSelect = { dest -> model.navigate(dest) }, + onNewThread = { model.openNewChatLanding() }, + ) + } + + Column( + Modifier + .align(Alignment.TopCenter) + .statusBarsPadding(), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + hostNotices() } } } } + if (showQrScanner) { + QrScannerOverlay( + onCode = { raw -> + showQrScanner = false + model.pairFromRaw(raw) + }, + onManualInput = { + showQrScanner = false + model.go(Route.ManualPair) + }, + onDismiss = { showQrScanner = false }, + ) + } + } +} + +@Composable +private fun ConnectedSasCapsule( + notice: ConnectedSasNotice, + onDismiss: () -> Unit, +) { + val colors = VibexTheme.colors + Row( + modifier = Modifier + .padding(horizontal = 16.dp, vertical = 6.dp) + .shadow(10.dp, CircleShape, ambientColor = Color.Black.copy(alpha = 0.14f)) + .clip(CircleShape) + .background(colors.card) + .border(0.75.dp, colors.pass.copy(alpha = 0.42f), CircleShape) + .clickable(onClick = onDismiss) + .padding(horizontal = 14.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + imageVector = Icons.Rounded.CheckCircle, + contentDescription = null, + tint = colors.pass, + modifier = Modifier.size(16.dp), + ) + Text( + text = "已连接 ${notice.hostName}", + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = "连接码 ${notice.sasCode}", + style = TextStyle( + fontSize = 12.5.sp, + fontWeight = FontWeight.Bold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.accent, + ), + ) } } @@ -357,6 +513,10 @@ private sealed interface ShellLayer { override val elevation = 0f } + data object NewThread : ShellLayer { + override val elevation = 1f + } + data class Conversation(val conversationId: String) : ShellLayer { override val elevation = 1f } @@ -387,19 +547,43 @@ private fun tabTransition(from: Route, to: Route): ContentTransform { } @Composable -private fun DesktopEmptyState(state: UiState, model: CompanionModel, authExpired: Boolean) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - EmptyState( - icon = if (authExpired) Icons.Rounded.KeyOff else Icons.Rounded.Computer, - title = if (authExpired) "连接凭据已失效" else "未连接电脑", - action = "连接电脑", - onAction = { - when { - state.accountSignedIn -> model.openDesktopConnect() - state.profiles.isNotEmpty() && !authExpired -> model.connectSelected() - else -> model.go(Route.ManualPair) - } - }, - ) +private fun DesktopEmptyState( + state: UiState, + model: CompanionModel, + authExpired: Boolean, +) { + Box( + Modifier + .fillMaxSize() + .padding(bottom = BOTTOM_DOCK_CLEARANCE), + contentAlignment = Alignment.Center, + ) { + if (state.isAutoConnectingInBackground || (state.accountSignedIn && (state.accountLoading || state.accountSyncingHosts))) { + LoadingState( + state.autoConnectingHostName?.let { "正在连接 $it…" } ?: "正在同步你的电脑…", + ) + } else { + EmptyState( + icon = if (authExpired) Icons.Rounded.KeyOff else Icons.Rounded.Computer, + title = if (authExpired) "连接凭据已失效" else "未连接电脑", + action = "连接电脑", + onAction = { + when { + state.accountSignedIn && state.accountDesktops.size == 1 -> { + model.connectDesktopTarget(DesktopConnectTarget.Account(state.accountDesktops.single())) + } + state.accountSignedIn || state.discoveredHosts.any { !it.isCloudService } -> { + model.openDesktopConnect() + } + state.profiles.isNotEmpty() && !authExpired -> { + model.connectSelected() + } + else -> { + model.go(Route.ManualPair) + } + } + }, + ) + } } } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/Components.kt b/app/src/main/java/dev/vibex/companion/app/ui/Components.kt index e886161..753ee0a 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/Components.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/Components.kt @@ -1,5 +1,6 @@ package dev.vibex.companion.app.ui +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.combinedClickable @@ -31,9 +32,12 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Check import androidx.compose.material.icons.rounded.Folder import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.DropdownMenu import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator @@ -67,6 +71,7 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.vibex.companion.ConnectionState @@ -118,7 +123,7 @@ fun CompanionRefresh( @Composable fun BrandMark(size: Dp = 72.dp) { val res = if (VibexTheme.colors.isDark) R.drawable.logo_dark else R.drawable.logo_light - Image(painterResource(res), "VibeX", Modifier.size(size)) + Image(painterResource(res), "Dimo", Modifier.size(size)) } @Composable @@ -501,6 +506,102 @@ fun connectionLabel(connection: ConnectionState): String = when (connection) { } +@Composable +fun VibexDropdownMenu( + expanded: Boolean, + onDismissRequest: () -> Unit, + modifier: Modifier = Modifier, + offset: DpOffset = DpOffset(0.dp, 6.dp), + content: @Composable ColumnScope.() -> Unit, +) { + val colors = VibexTheme.colors + DropdownMenu( + expanded = expanded, + onDismissRequest = onDismissRequest, + offset = offset, + shape = RoundedCornerShape(16.dp), + containerColor = colors.card, + tonalElevation = 0.dp, + shadowElevation = 12.dp, + border = BorderStroke(0.75.dp, colors.stroke), + modifier = modifier.widthIn(min = 188.dp, max = 280.dp), + content = content, + ) +} + +@Composable +fun VibexDropdownMenuItem( + text: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + leadingIcon: ImageVector? = null, + leadingDotColor: Color? = null, + selected: Boolean = false, + tint: Color? = null, + enabled: Boolean = true, +) { + val colors = VibexTheme.colors + val contentColor = when { + !enabled -> colors.textTertiary + selected -> colors.accent + tint != null -> tint + else -> colors.textPrimary + } + Row( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 6.dp, vertical = 1.dp) + .clip(RoundedCornerShape(10.dp)) + .background(if (selected) colors.accentDim else Color.Transparent) + .clickable(enabled = enabled, onClick = onClick) + .padding(horizontal = 10.dp, vertical = 9.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (leadingDotColor != null) { + Box( + modifier = Modifier + .size(12.dp) + .clip(CircleShape) + .background(leadingDotColor), + ) + } else if (leadingIcon != null) { + Icon( + imageVector = leadingIcon, + contentDescription = null, + tint = if (selected || tint != null || !enabled) contentColor else colors.textSecondary, + modifier = Modifier.size(17.dp), + ) + } + Text( + text = text, + fontSize = 14.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = contentColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (selected) { + Icon( + imageVector = Icons.Rounded.Check, + contentDescription = null, + tint = colors.accent, + modifier = Modifier.size(16.dp), + ) + } + } +} + +@Composable +fun VibexDropdownDivider() { + HorizontalDivider( + color = VibexTheme.colors.hairline, + thickness = 0.6.dp, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} + @Composable fun GlassMenu( expanded: Boolean, diff --git a/app/src/main/java/dev/vibex/companion/app/ui/ConversationScreens.kt b/app/src/main/java/dev/vibex/companion/app/ui/ConversationScreens.kt index 3129d68..272c97a 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/ConversationScreens.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/ConversationScreens.kt @@ -1,78 +1,58 @@ package dev.vibex.companion.app.ui -import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut -import androidx.compose.animation.slideInHorizontally -import androidx.compose.animation.slideOutHorizontally -import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectHorizontalDragGestures -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.ui.platform.LocalFocusManager -import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight import androidx.compose.material.icons.rounded.AccountTree -import androidx.compose.material.icons.rounded.ArrowUpward -import androidx.compose.material.icons.rounded.AutoAwesome -import androidx.compose.material.icons.rounded.Cancel +import androidx.compose.material.icons.rounded.Bolt +import androidx.compose.material.icons.rounded.ChatBubbleOutline import androidx.compose.material.icons.rounded.Check -import androidx.compose.material.icons.rounded.Code -import androidx.compose.material.icons.rounded.Description -import androidx.compose.material.icons.rounded.EditNote -import androidx.compose.material.icons.rounded.ExpandLess -import androidx.compose.material.icons.rounded.ExpandMore +import androidx.compose.material.icons.rounded.CheckCircle import androidx.compose.material.icons.rounded.Folder -import androidx.compose.material.icons.rounded.GridView -import androidx.compose.material.icons.rounded.Groups -import androidx.compose.material.icons.rounded.Menu -import androidx.compose.material.icons.rounded.Search -import androidx.compose.material.icons.rounded.Settings -import androidx.compose.material.icons.rounded.UnfoldMore +import androidx.compose.material.icons.rounded.Forum +import androidx.compose.material.icons.rounded.KeyboardArrowDown +import androidx.compose.material.icons.rounded.Layers +import androidx.compose.material.icons.rounded.PushPin +import androidx.compose.material.icons.rounded.RadioButtonUnchecked +import androidx.compose.material.icons.rounded.Verified +import androidx.compose.material.icons.rounded.Visibility +import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -80,849 +60,1213 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import androidx.compose.ui.zIndex import dev.vibex.companion.ConnectionState -import dev.vibex.companion.ConversationSummary -import dev.vibex.companion.SessionConfigChoice -import dev.vibex.companion.SessionConfigOption -import dev.vibex.companion.SessionMode -import dev.vibex.companion.WorkspaceEntry -import dev.vibex.companion.agentDisplayName +import dev.vibex.companion.KanbanSessionStatus +import dev.vibex.companion.KanbanSessionSummary import dev.vibex.companion.app.CompanionModel -import dev.vibex.companion.app.Route import dev.vibex.companion.app.UiState -import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme -import java.time.Duration +import dev.vibex.companion.isRecentlyActiveReadSession +import dev.vibex.companion.parseHostTimestampEpochMillis +import dev.vibex.companion.updatedEpochMs import java.time.Instant -import java.time.OffsetDateTime +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch -private data class StarterChip(val id: String, val label: String, val prompt: String) +private enum class SessionListOrganization(val label: String) { + StatusGrouped("状态分组"), + WorkspaceGrouped("工作区视图"), +} -private val starterSuggestions = listOf( - StarterChip("arch", "梳理项目架构", "梳理当前项目的整体架构、目录结构与核心模块职责"), - StarterChip("bug", "排查近期改动", "检查当前工作区最近的代码改动,排查潜在问题并给出修复方案"), - StarterChip("test", "补充单元测试", "为当前工作区最近修改的核心逻辑补充单元测试并运行验证"), -) +private val StatusOrange = Color(0xFFFF9500) +private val StatusPurple = Color(0xFFAF52DE) +private val StatusTeal = Color(0xFF30B0C7) +private val StatusBlue = Color(0xFF007AFF) +private val StatusGreen = Color(0xFF34C759) -@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) +/** + * 1:1 port of iOS `ConversationsView` Level-1 Session Hub (`ConversationsView.swift`). + * Features project filter menu, `UnifiedSearchBar`, `状态分组 / 工作区视图` toggle, + * 5 status groups (`进行中`, `待检查`, `近期对话` 24h window, `待开始`, collapsible `已完成历史会话`), + * and full long-press session management actions. + */ @Composable fun ConversationList( state: UiState, model: CompanionModel, - onChromeHiddenChange: (Boolean) -> Unit = {}, ) { val colors = VibexTheme.colors - val focusManager = LocalFocusManager.current - var isSidebarOpen by remember { mutableStateOf(false) } - var sidebarTab by remember { mutableStateOf("conversations") } - var sidebarSearch by remember { mutableStateOf("") } - var draft by remember { mutableStateOf("") } - var selectedAgentId by remember { mutableStateOf(null) } - var composerMenu by remember { mutableStateOf(null) } - var isComposerFocused by remember { mutableStateOf(false) } - val shouldHideBottomChrome = isSidebarOpen || composerMenu != null || isComposerFocused - LaunchedEffect(shouldHideBottomChrome) { - onChromeHiddenChange(shouldHideBottomChrome) - if (isSidebarOpen) { - composerMenu = null - focusManager.clearFocus() + val haptic = LocalHapticFeedback.current + val scope = rememberCoroutineScope() + + var organization by remember { mutableStateOf(SessionListOrganization.StatusGrouped) } + var searchQuery by remember { mutableStateOf("") } + var isCompletedShelfExpanded by remember { mutableStateOf(false) } + var kanbanSessions by remember { mutableStateOf>(emptyList()) } + var initialLoading by remember { mutableStateOf(true) } + var refreshing by remember { mutableStateOf(false) } + var removedIds by remember { mutableStateOf>(emptySet()) } + var projectMenuExpanded by remember { mutableStateOf(false) } + + var contextTarget by remember { mutableStateOf(null) } + var contextAnchor by remember { mutableStateOf(Offset.Zero) } + var renamingSession by remember { mutableStateOf(null) } + var renameDraft by remember { mutableStateOf("") } + var deletingSession by remember { mutableStateOf(null) } + + val projects = state.catalog?.projects.orEmpty() + val workspaces = state.catalog?.workspaces.orEmpty() + val selectedFilterProject = remember(projects, state.selectedProjectId) { + val pid = state.selectedProjectId ?: return@remember null + projects.find { it.id.equals(pid, ignoreCase = true) } + } + + suspend fun reloadKanban(silent: Boolean = false) { + if (!silent && kanbanSessions.isEmpty()) { + initialLoading = true + } + runCatching { + model.fetchKanbanSessions(state.selectedProjectId) + }.onSuccess { fetched -> + kanbanSessions = fetched } + initialLoading = false } - BackHandler(enabled = isSidebarOpen || composerMenu != null) { - if (isSidebarOpen) { - isSidebarOpen = false + + LaunchedEffect(state.selectedProjectId, state.connection, state.conversations.size) { + if (state.connection == ConnectionState.Online) { + reloadKanban(silent = kanbanSessions.isNotEmpty()) } else { - composerMenu = null + initialLoading = false } } - var landingModeId by remember { mutableStateOf("auto") } - var landingEffortValue by remember { mutableStateOf("medium") } - var selectedModelByAgent by remember { mutableStateOf>(emptyMap()) } - var customRelayModels by remember { mutableStateOf>(emptyList()) } - var showProjectSheet by remember { mutableStateOf(false) } - var showDiffSheet by remember { mutableStateOf(false) } - var showFileBrowserSheet by remember { mutableStateOf(false) } - var menuId by remember { mutableStateOf(null) } - var menuAnchor by remember { mutableStateOf(Offset.Zero) } - var expandedProjects by remember { mutableStateOf(setOf()) } - var workspaceEntries by remember { mutableStateOf>>(emptyMap()) } - val projects = state.catalog?.projects.orEmpty() - val workspaces = state.catalog?.workspaces.orEmpty() - val agents = state.catalog?.agents.orEmpty().let { list -> - list.filter { it.usable }.ifEmpty { list } + LaunchedEffect(state.selectedProjectId, state.connection) { + while (isActive) { + val hasRunning = kanbanSessions.any { it.isRunning || it.status == KanbanSessionStatus.InProgress } || + state.conversations.any { it.status.equals("inprogress", ignoreCase = true) || it.status.equals("running", ignoreCase = true) } + delay(if (hasRunning) 3_500L else 12_000L) + if (state.connection == ConnectionState.Online) { + reloadKanban(silent = true) + } + } } - val currentProject = projects.find { it.id == state.selectedProjectId } ?: projects.firstOrNull() - val currentWorkspace = workspaces.firstOrNull { it.projectId == currentProject?.id } ?: workspaces.firstOrNull() - val currentAgent = agents.find { it.id == selectedAgentId } - ?: agents.find { it.id == state.conversations.firstOrNull()?.agentId } - ?: agents.firstOrNull() - - LaunchedEffect(projects.size, state.selectedProjectId) { - if (state.selectedProjectId == null && projects.isNotEmpty()) { - model.selectProject(projects.first().id) + + fun projectNameForWorkspace(workspaceId: String): String? { + val ws = workspaces.find { it.id == workspaceId } ?: return null + return projects.find { it.id.equals(ws.projectId, ignoreCase = true) }?.name + } + + val mergedSessions = remember( + kanbanSessions, + state.conversations, + workspaces, + projects, + selectedFilterProject, + searchQuery, + removedIds, + ) { + val byId = LinkedHashMap() + for (s in kanbanSessions) { + if (!s.isArchived && s.id !in removedIds) { + byId[s.id] = s + } } + for (c in state.conversations) { + if (c.id !in removedIds && !byId.containsKey(c.id)) { + val branch = workspaces.find { it.id == c.workspaceId }?.branch + val converted = KanbanSessionSummary.fromConversationSummary(c, branch = branch) + if (!converted.isArchived) { + byId[c.id] = converted + } + } + } + val allowedWorkspaces: Set? = selectedFilterProject?.let { proj -> + workspaces.filter { it.projectId.equals(proj.id, ignoreCase = true) }.map { it.id }.toSet() + } + val q = searchQuery.trim().lowercase() + byId.values + .filter { item -> + if (allowedWorkspaces != null && allowedWorkspaces.isNotEmpty() && item.workspaceId !in allowedWorkspaces) { + return@filter false + } + if (q.isEmpty()) return@filter true + val projName = projectNameForWorkspace(item.workspaceId).orEmpty().lowercase() + item.resolvedTitle.lowercase().contains(q) || + item.workspaceDisplayLabel.lowercase().contains(q) || + item.agentDisplayLabel.lowercase().contains(q) || + item.model.orEmpty().lowercase().contains(q) || + projName.contains(q) + } + .sortedWith( + compareByDescending { it.isPinned } + .thenByDescending { it.updatedEpochMs ?: 0L }, + ) } val isOnline = state.connection == ConnectionState.Online - Box( - Modifier + Column( + modifier = Modifier .fillMaxSize() - .background(colors.bg) - .pointerInput(isSidebarOpen) { - var totalDx = 0f - var startX = 0f - detectHorizontalDragGestures( - onDragStart = { offset -> - startX = offset.x - totalDx = 0f - }, - onHorizontalDrag = { _, dragAmount -> - totalDx += dragAmount - }, - onDragEnd = { - if (!isSidebarOpen && startX < 96f && totalDx > 100f) { - isSidebarOpen = true - } else if (isSidebarOpen && totalDx < -100f) { - isSidebarOpen = false - } - }, - ) - }, + .background(colors.bg), ) { - // Main Calm AI Chat Landing View (1:1 with iOS ConversationsView.landingWorkspaceView) - Column( - Modifier - .fillMaxSize() - .imePadding(), + // Level-1 Navigation Bar: Project Filter | Centered "会话" | Connection Pill + Box( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 10.dp), ) { - // Top Bar: Sidebar Button | Connection Status | Diff/New Button - Row( - Modifier - .fillMaxWidth() - .padding(horizontal = 14.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Box( - Modifier - .size(36.dp) - .clip(CircleShape) - .background(colors.bgElevated) - .clickable { isSidebarOpen = true }, - contentAlignment = Alignment.Center, - ) { - Icon(Icons.Rounded.Menu, contentDescription = "打开侧边栏", tint = colors.textPrimary, modifier = Modifier.size(18.dp)) - } - - Spacer(Modifier.weight(1f)) - + Box(modifier = Modifier.align(Alignment.CenterStart)) { Row( + modifier = Modifier + .clip(RoundedCornerShape(10.dp)) + .clickable { projectMenuExpanded = true } + .padding(horizontal = 6.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp), ) { - Box( - Modifier - .size(6.5.dp) - .clip(CircleShape) - .background(if (isOnline) colors.pass else colors.hold), + Icon( + imageVector = if (selectedFilterProject == null) Icons.Rounded.Layers else Icons.Rounded.Folder, + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(15.dp), ) Text( - if (isOnline) "已连接" else connectionLabel(state.connection), - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - color = colors.textSecondary, + text = selectedFilterProject?.name ?: "全部项目", + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Icon( + imageVector = Icons.Rounded.KeyboardArrowDown, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(15.dp), ) } - Spacer(Modifier.weight(1f)) - - Box( - Modifier - .size(36.dp) - .clip(CircleShape) - .background(colors.bgElevated) - .clickable { - if (currentWorkspace != null) { - showDiffSheet = true - } - }, - contentAlignment = Alignment.Center, - ) { - Icon(Icons.Rounded.Code, contentDescription = "代码差异", tint = colors.textPrimary, modifier = Modifier.size(18.dp)) - } - } - - if (state.inbox.isNotEmpty()) { - Row( - Modifier - .padding(horizontal = 16.dp, vertical = 4.dp) - .fillMaxWidth() - .clip(RoundedCornerShape(12.dp)) - .background(colors.hold.copy(0.14f)) - .clickable { model.openConversation(state.inbox.first().conversationId) } - .padding(horizontal = 14.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), + VibexDropdownMenu( + expanded = projectMenuExpanded, + onDismissRequest = { projectMenuExpanded = false }, ) { - Text( - "${state.inbox.size} 条待你审批或回复", - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, - color = colors.hold, - modifier = Modifier.weight(1f), + VibexDropdownMenuItem( + text = "全部项目", + leadingIcon = Icons.Rounded.Layers, + selected = selectedFilterProject == null, + onClick = { + projectMenuExpanded = false + model.selectProjectInPlace(null) + }, ) - Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = colors.hold, modifier = Modifier.size(16.dp)) + if (projects.isNotEmpty()) { + VibexDropdownDivider() + projects.forEach { proj -> + val isSelected = selectedFilterProject?.id?.equals(proj.id, ignoreCase = true) == true + VibexDropdownMenuItem( + text = proj.name, + leadingIcon = Icons.Rounded.Folder, + selected = isSelected, + onClick = { + projectMenuExpanded = false + model.selectProjectInPlace(proj.id) + }, + ) + } + } } } - Spacer(Modifier.weight(1f)) + Text( + text = "会话", + fontSize = 17.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + modifier = Modifier.align(Alignment.Center), + ) - // Center Focal Area: VibeX Logo + "有什么可以帮你?" + Project Context Pill - Column( - Modifier - .fillMaxWidth() - .clickable( - interactionSource = remember { MutableInteractionSource() }, - indication = null, - ) { - if (composerMenu != null) composerMenu = null - focusManager.clearFocus() - } - .padding(horizontal = 24.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(14.dp), + Row( + modifier = Modifier + .align(Alignment.CenterEnd) + .clip(CircleShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, CircleShape) + .clickable { model.openDesktopConnect() } + .padding(horizontal = 10.dp, vertical = 5.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), ) { Box( - Modifier - .size(56.dp) - .shadow(10.dp, RoundedCornerShape(14.dp), ambientColor = Color.Black.copy(0.10f), spotColor = Color.Black.copy(0.14f)) - .clip(RoundedCornerShape(14.dp)) - .background(colors.bgElevated), - contentAlignment = Alignment.Center, - ) { - BrandMark(40.dp) - } + modifier = Modifier + .size(6.5.dp) + .clip(CircleShape) + .background(if (isOnline) colors.pass else colors.hold), + ) + Text( + text = if (isOnline) "已连接" else connectionLabel(state.connection), + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + ) + } + } + // Pending Approval / Question Banner + if (state.inbox.isNotEmpty()) { + Row( + modifier = Modifier + .padding(horizontal = 16.dp, vertical = 4.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(colors.hold.copy(alpha = 0.14f)) + .clickable { model.openConversation(state.inbox.first().conversationId) } + .padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { Text( - "有什么可以帮你?", - fontSize = 22.sp, - fontWeight = FontWeight.Bold, - color = colors.textPrimary, - textAlign = TextAlign.Center, + text = "${state.inbox.size} 条待你审批或回复", + style = TextStyle( + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + fontFeatureSettings = "tnum", + color = colors.hold, + ), + modifier = Modifier.weight(1f), + ) + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = colors.hold, + modifier = Modifier.size(16.dp), ) + } + } - // Project Context Pill (1:1 with iOS projectContextPill) + if (initialLoading && mergedSessions.isEmpty() && state.conversationsLoading) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center, + ) { Row( - Modifier - .clip(CircleShape) - .background(colors.bgElevated) - .border(0.6.dp, colors.stroke, CircleShape) - .clickable { showProjectSheet = true } - .padding(horizontal = 14.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - Icon(Icons.Rounded.Folder, null, tint = colors.textSecondary, modifier = Modifier.size(14.dp)) + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + color = colors.accent, + ) Text( - currentProject?.name ?: "选择项目", - fontSize = 13.5.sp, - fontWeight = FontWeight.Medium, - color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, + text = "正在同步会话…", + fontSize = 14.sp, + color = colors.textSecondary, ) - val branch = currentWorkspace?.branch?.ifBlank { "main" } ?: "main" - Text("·", color = colors.textTertiary, fontSize = 13.sp) - Icon(Icons.Rounded.AccountTree, null, tint = colors.textSecondary, modifier = Modifier.size(12.dp)) - Text(branch, fontSize = 12.5.sp, color = colors.textSecondary) - Icon(Icons.Rounded.UnfoldMore, null, tint = colors.textTertiary, modifier = Modifier.size(14.dp)) } } - - Spacer(Modifier.weight(1f)) - - // Quiet Starter Suggestion Chips (shown when draft is empty and composer menu is closed) - if (draft.isBlank() && composerMenu == null) { - Row( - Modifier - .fillMaxWidth() - .horizontalScroll(rememberScrollState()) - .padding(horizontal = 14.dp, vertical = 6.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - starterSuggestions.forEach { chip -> - Text( - chip.label, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = colors.textSecondary, - modifier = Modifier - .clip(CircleShape) - .background(colors.bgElevated) - .border(0.6.dp, colors.stroke, CircleShape) - .clickable { draft = chip.prompt } - .padding(horizontal = 13.dp, vertical = 7.5.dp), - ) + } else { + CompanionRefresh( + refreshing = refreshing, + onRefresh = { + scope.launch { + refreshing = true + model.refreshCurrent() + reloadKanban(silent = true) + refreshing = false } - } - } - - // 1:1 reuse of iOS PromptBar (`ConversationsView.swift` landingPromptBar) - val resolvedWsId = currentWorkspace?.id?.ifBlank { null } - ?: state.conversations.firstOrNull { it.workspaceId.isNotBlank() }?.workspaceId - val landingModes = remember(currentAgent) { - currentAgent?.sessionModes?.takeIf { it.isNotEmpty() } ?: listOf( - SessionMode("manual", "手动审批"), - SessionMode("accept_edits", "自动接受编辑"), - SessionMode("plan", "仅规划"), - SessionMode("auto", "自动"), - SessionMode("bypass", "跳过权限"), - ) - } - val currentAgentId = currentAgent?.id ?: "claude_code" - val baseModelOption = remember(currentAgent, currentAgentId) { - currentAgent?.sessionConfig?.firstOrNull { - val k = it.key.lowercase() - val c = it.category.lowercase() - c == "model" || k == "model" || k.contains("model") - } ?: dev.vibex.companion.fallbackModelOptionForAgent(currentAgentId) - } - val baseEffortOption = remember(currentAgent) { - currentAgent?.sessionConfig?.firstOrNull { - val k = it.key.lowercase() - val c = it.category.lowercase() - c.contains("thought") || c.contains("effort") || c.contains("reason") || - k.contains("thought") || k.contains("effort") || k.contains("thinking") || k.contains("reason") - } ?: SessionConfigOption( - key = "reasoning_effort", - label = "推理强度", - category = "thought_level", - value = "medium", - choices = listOf( - SessionConfigChoice("low", "低"), - SessionConfigChoice("medium", "中"), - SessionConfigChoice("high", "高"), - ), - ) - } - val activeModelValue = selectedModelByAgent[currentAgentId] - ?: baseModelOption.value.ifBlank { baseModelOption.choices.firstOrNull()?.value ?: "default" } - val landingConfigOptions = remember( - currentAgentId, - baseModelOption, - baseEffortOption, - activeModelValue, - landingEffortValue, - customRelayModels, + }, + modifier = Modifier.fillMaxSize(), ) { - val mergedChoices = buildList { - customRelayModels.forEach { custom -> - if (baseModelOption.choices.none { it.value == custom }) { - add(SessionConfigChoice(custom, "$custom (自定义/中转)")) - } + val (runningList, reviewList, recentReadList, todoList, doneList) = remember( + mergedSessions, + state.manuallyCompletedSessionIds, + ) { + val nowMs = System.currentTimeMillis() + val running = mergedSessions.filter { + it.status == KanbanSessionStatus.InProgress || + (it.isRunning && it.status != KanbanSessionStatus.InReview) } - addAll(baseModelOption.choices) - if (none { it.value == activeModelValue }) { - add(0, SessionConfigChoice(activeModelValue, activeModelValue)) + val runningIds = running.mapTo(HashSet()) { it.id } + val review = mergedSessions.filter { + it.status == KanbanSessionStatus.InReview && it.id !in runningIds } - } - listOf( - baseModelOption.copy( - value = activeModelValue, - choices = mergedChoices, - ), - baseEffortOption.copy( - value = landingEffortValue, - ), - ) - } - - PromptBar( - text = draft, - onTextChange = { draft = it }, - menu = composerMenu, - onMenuChange = { composerMenu = it }, - agentId = currentAgentId, - agent = currentAgent, - agents = agents, - showAgentSelector = true, - onSelectAgent = { nextAgentId -> - selectedAgentId = nextAgentId - }, - onAddCustomModel = { rawModel -> - val trimmed = rawModel.trim() - if (trimmed.isNotEmpty()) { - if (trimmed !in customRelayModels) { - customRelayModels = listOf(trimmed) + customRelayModels - } - selectedModelByAgent = selectedModelByAgent + (currentAgentId to trimmed) + val recentRead = mergedSessions.filter { + it.isRecentlyActiveReadSession(state.manuallyCompletedSessionIds, nowMs) } - }, - modes = landingModes, - currentModeId = landingModeId, - configOptions = landingConfigOptions, - isStreaming = false, - enabled = state.connection.allowsWrites && !resolvedWsId.isNullOrBlank(), - onSend = { - val text = draft.trim() - val wsId = resolvedWsId ?: return@PromptBar - if (text.isEmpty()) return@PromptBar - composerMenu = null - draft = "" - model.createConversation( - workspaceId = wsId, - agentId = currentAgentId, - title = text.take(36), - prompt = text, - modeId = landingModeId, - config = mapOf( - baseModelOption.key to activeModelValue, - baseEffortOption.key to landingEffortValue, - ), - ) - }, - onStop = {}, - onSelectMode = { modeId -> - landingModeId = modeId - }, - onSelectOption = { key, value -> - if (key == baseModelOption.key || key.lowercase().contains("model")) { - selectedModelByAgent = selectedModelByAgent + (currentAgentId to value) - } else { - landingEffortValue = value + val todo = mergedSessions.filter { + it.status == KanbanSessionStatus.Todo && !it.isRunning } - }, - onOpenFileBrowser = if (currentWorkspace != null) { - { showFileBrowserSheet = true } - } else { - null - }, - onFocusChange = { isComposerFocused = it }, - ) - } - - // Slide-Out Sidebar Scrim - AnimatedVisibility( - visible = isSidebarOpen, - enter = fadeIn(), - exit = fadeOut(), - modifier = Modifier.zIndex(1f), - ) { - Box( - Modifier - .fillMaxSize() - .background(Color.Black.copy(0.36f)) - .clickable { isSidebarOpen = false }, - ) - } - - // Slide-Out Sidebar Drawer (1:1 with iOS ConversationsView.sidebarDrawer) - AnimatedVisibility( - visible = isSidebarOpen, - enter = slideInHorizontally { -it }, - exit = slideOutHorizontally { -it }, - modifier = Modifier.zIndex(2f), - ) { - Column( - Modifier - .width(304.dp) - .fillMaxHeight() - .background(colors.bgElevated) - .clickable(enabled = false) {}, - ) { - // Sidebar Top Bar: Segmented Switcher (最近对话 | 项目文件) + New Chat Button - Row( - Modifier - .fillMaxWidth() - .padding(horizontal = 14.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - Modifier - .clip(CircleShape) - .background(colors.segmentedTrack) - .padding(3.dp), - horizontalArrangement = Arrangement.spacedBy(2.dp), - ) { - listOf("conversations" to "最近对话", "files" to "项目文件").forEach { (id, label) -> - val selected = sidebarTab == id - Text( - label, - fontSize = 13.sp, - fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, - color = if (selected) colors.textPrimary else colors.textSecondary, - modifier = Modifier - .then( - if (selected) Modifier.shadow(1.5.dp, CircleShape, ambientColor = Color.Black.copy(0.08f)) - else Modifier, - ) - .clip(CircleShape) - .background(if (selected) colors.segmentedThumb else Color.Transparent) - .clickable { sidebarTab = id } - .padding(horizontal = 12.dp, vertical = 6.dp), - ) - } + val done = mergedSessions.filter { + it.status == KanbanSessionStatus.Done && + !it.isRunning && + !it.isRecentlyActiveReadSession(state.manuallyCompletedSessionIds, nowMs) } + listOf(running, review, recentRead, todo, done) + } + val hasActive = runningList.isNotEmpty() || + reviewList.isNotEmpty() || + recentReadList.isNotEmpty() || + todoList.isNotEmpty() + val isSearching = searchQuery.trim().isNotEmpty() - Spacer(Modifier.weight(1f)) - - Box( - Modifier - .size(32.dp) - .clip(CircleShape) - .background(colors.bg) - .clickable { isSidebarOpen = false }, - contentAlignment = Alignment.Center, - ) { - Icon(Icons.Rounded.EditNote, contentDescription = "新对话", tint = colors.textPrimary, modifier = Modifier.size(18.dp)) + val workspaceGroups = remember(mergedSessions, organization, projects, workspaces) { + if (organization != SessionListOrganization.WorkspaceGrouped) { + emptyList() + } else { + mergedSessions + .groupBy { item -> + val proj = projectNameForWorkspace(item.workspaceId) ?: "其他项目" + val branch = item.workspaceDisplayLabel + if (branch.isEmpty()) proj else "$proj · $branch" + } + .entries + .sortedByDescending { entry -> entry.value.firstOrNull()?.updatedEpochMs ?: 0L } } } - // Sidebar Search Box - Row( - Modifier - .padding(horizontal = 14.dp) - .padding(bottom = 10.dp) - .fillMaxWidth() - .clip(RoundedCornerShape(10.dp)) - .background(colors.bg) - .padding(horizontal = 10.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues( + start = 16.dp, + end = 16.dp, + top = 6.dp, + bottom = BOTTOM_DOCK_CLEARANCE + 18.dp, + ), + verticalArrangement = Arrangement.spacedBy(14.dp), ) { - Icon(Icons.Rounded.Search, null, tint = colors.textSecondary, modifier = Modifier.size(15.dp)) - Box(Modifier.weight(1f)) { - if (sidebarSearch.isEmpty()) { - Text( - if (sidebarTab == "conversations") "搜索对话…" else "搜索项目…", - fontSize = 13.5.sp, - color = colors.textTertiary, + // Search + Segmented Organization Header + item(key = "header_controls") { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + UnifiedSearchBar( + query = searchQuery, + onQueryChange = { searchQuery = it }, + placeholder = "搜索会话、分支或模型…", ) - } - BasicTextField( - value = sidebarSearch, - onValueChange = { sidebarSearch = it }, - singleLine = true, - textStyle = TextStyle(color = colors.textPrimary, fontSize = 13.5.sp), - cursorBrush = SolidColor(colors.accent), - modifier = Modifier.fillMaxWidth(), - ) - } - if (sidebarSearch.isNotEmpty()) { - Icon( - Icons.Rounded.Cancel, - null, - tint = colors.textTertiary, - modifier = Modifier.size(15.dp).clickable { sidebarSearch = "" }, - ) - } - } - HorizontalDivider(color = colors.hairline) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(10.dp)) + .background(colors.segmentedTrack) + .padding(2.5.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), + ) { + SessionListOrganization.entries.forEach { mode -> + val selected = organization == mode + Text( + text = mode.label, + fontSize = 12.5.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = if (selected) colors.textPrimary else colors.textSecondary, + modifier = Modifier + .then( + if (selected) { + Modifier.shadow( + 1.5.dp, + RoundedCornerShape(8.dp), + ambientColor = Color.Black.copy(alpha = 0.08f), + ) + } else { + Modifier + }, + ) + .clip(RoundedCornerShape(8.dp)) + .background(if (selected) colors.segmentedThumb else Color.Transparent) + .clickable { organization = mode } + .padding(horizontal = 12.dp, vertical = 5.5.dp), + ) + } + } + + Spacer(modifier = Modifier.weight(1f)) - // Sidebar Body - if (sidebarTab == "conversations") { - val q = sidebarSearch.trim().lowercase() - val filtered = remember(state.conversations, q) { - state.conversations.filter { - q.isEmpty() || it.title.lowercase().contains(q) || it.agentId.lowercase().contains(q) - } - } - LazyColumn( - Modifier.weight(1f).fillMaxWidth(), - contentPadding = PaddingValues(vertical = 10.dp), - ) { - if (currentProject != null) { - item { Text( - currentProject.name, - fontSize = 11.5.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textSecondary, - modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + text = "${mergedSessions.size} 个会话", + style = TextStyle( + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), ) } } - if (filtered.isEmpty()) { - item { - Text( - "暂无对话记录", - fontSize = 13.sp, - color = colors.textSecondary, - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp), - ) - } - } else { - items(filtered, key = { it.id }) { item -> - val agent = catalogAgent(state, item.agentId) - val relTime = remember(item.updatedAt) { relativeTime(item.updatedAt) } + } + + if (mergedSessions.isEmpty()) { + item(key = "empty_sessions") { + EmptySessionsCard(isSearching = isSearching) + } + } else if (organization == SessionListOrganization.StatusGrouped) { + if (!hasActive && !isSearching) { + item(key = "calm_all_done_banner") { Row( - Modifier - .padding(horizontal = 8.dp, vertical = 2.dp) + modifier = Modifier .fillMaxWidth() - .clip(RoundedCornerShape(9.dp)) - .then( - longPressModifier( - onClick = { - isSidebarOpen = false - model.openConversation(item.id) - }, - onLongClick = { offset -> - menuAnchor = offset - menuId = item.id - }, - ), - ) - .padding(horizontal = 10.dp, vertical = 8.dp), + .clip(RoundedCornerShape(14.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(14.dp)) + .padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(9.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), ) { - AgentAvatar(item.agentId, size = 20.dp, iconSvg = agent?.iconSvg, displayName = agent?.displayName.orEmpty()) - Text( - item.title.ifBlank { "未命名对话" }, - fontSize = 13.5.sp, - color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), + Icon( + imageVector = Icons.Rounded.CheckCircle, + contentDescription = null, + tint = StatusGreen, + modifier = Modifier.size(17.dp), ) Text( - relTime, - fontSize = 10.5.sp, - color = colors.textTertiary, + text = "当前没有进行中或近期对话,点底部 + 新建会话", + fontSize = 13.sp, + color = colors.textSecondary, ) } } } - } - } else { - val q = sidebarSearch.trim().lowercase() - val filteredProjects = remember(projects, q) { - projects.filter { - q.isEmpty() || it.name.lowercase().contains(q) || it.path.lowercase().contains(q) + + if (runningList.isNotEmpty()) { + item(key = "sec_running") { + SessionSectionBlock( + title = "进行中", + tint = StatusOrange, + icon = Icons.Rounded.Bolt, + items = runningList, + state = state, + showStatusBadge = false, + projectNameForWorkspace = ::projectNameForWorkspace, + onTap = { session -> + openSession(session, model) { viewedId -> + kanbanSessions = kanbanSessions.map { + if (it.id == viewedId) it.copy(status = KanbanSessionStatus.Done) else it + } + } + }, + onLongPress = { session, offset -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + contextAnchor = offset + contextTarget = session + }, + ) + } } - } - LazyColumn( - Modifier.weight(1f).fillMaxWidth(), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 10.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - items(filteredProjects, key = { it.id }) { proj -> - val ws = workspaces.firstOrNull { it.projectId == proj.id } - val expanded = proj.id in expandedProjects - Column { - Row( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(8.dp)) - .clickable { - if (expanded) { - expandedProjects = expandedProjects - proj.id - } else { - expandedProjects = expandedProjects + proj.id - if (ws != null && !workspaceEntries.containsKey(ws.id)) { - model.loadWorkspaceEntries(ws.id) { entries -> - workspaceEntries = workspaceEntries + (ws.id to entries) - } - } + + if (reviewList.isNotEmpty()) { + item(key = "sec_review") { + SessionSectionBlock( + title = "待检查", + tint = StatusPurple, + icon = Icons.Rounded.Visibility, + items = reviewList, + state = state, + showStatusBadge = false, + projectNameForWorkspace = ::projectNameForWorkspace, + onTap = { session -> + openSession(session, model) { viewedId -> + kanbanSessions = kanbanSessions.map { + if (it.id == viewedId) it.copy(status = KanbanSessionStatus.Done) else it } } - .padding(horizontal = 8.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Icon( - if (expanded) Icons.Rounded.ExpandLess else Icons.Rounded.ExpandMore, - null, - tint = colors.textTertiary, - modifier = Modifier.size(16.dp), - ) - Icon(Icons.Rounded.Folder, null, tint = colors.accent, modifier = Modifier.size(16.dp)) - Text( - proj.name, - fontSize = 13.5.sp, - fontWeight = FontWeight.Medium, - color = colors.textPrimary, - modifier = Modifier.weight(1f), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (ws != null) { + }, + onLongPress = { session, offset -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + contextAnchor = offset + contextTarget = session + }, + ) + } + } + + if (recentReadList.isNotEmpty()) { + item(key = "sec_recent_read") { + SessionSectionBlock( + title = "近期对话", + tint = StatusTeal, + icon = Icons.Rounded.Forum, + items = recentReadList, + state = state, + showStatusBadge = false, + projectNameForWorkspace = ::projectNameForWorkspace, + onTap = { session -> + openSession(session, model) { viewedId -> + kanbanSessions = kanbanSessions.map { + if (it.id == viewedId) it.copy(status = KanbanSessionStatus.Done) else it + } + } + }, + onLongPress = { session, offset -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + contextAnchor = offset + contextTarget = session + }, + ) + } + } + + if (todoList.isNotEmpty()) { + item(key = "sec_todo") { + SessionSectionBlock( + title = "待开始", + tint = StatusBlue, + icon = Icons.Rounded.RadioButtonUnchecked, + items = todoList, + state = state, + showStatusBadge = false, + projectNameForWorkspace = ::projectNameForWorkspace, + onTap = { session -> + openSession(session, model) { viewedId -> + kanbanSessions = kanbanSessions.map { + if (it.id == viewedId) it.copy(status = KanbanSessionStatus.Done) else it + } + } + }, + onLongPress = { session, offset -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + contextAnchor = offset + contextTarget = session + }, + ) + } + } + + if (doneList.isNotEmpty()) { + item(key = "sec_done_shelf") { + val expanded = isSearching || isCompletedShelfExpanded + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(14.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(14.dp)) + .clickable { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + isCompletedShelfExpanded = !isCompletedShelfExpanded + } + .padding(horizontal = 14.dp, vertical = 11.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + imageVector = if (expanded) { + Icons.Rounded.KeyboardArrowDown + } else { + Icons.AutoMirrored.Rounded.KeyboardArrowRight + }, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(16.dp), + ) + Icon( + imageVector = Icons.Rounded.Verified, + contentDescription = null, + tint = StatusGreen.copy(alpha = 0.88f), + modifier = Modifier.size(15.dp), + ) Text( - "差异", - fontSize = 11.sp, - color = colors.accent, - modifier = Modifier - .clip(RoundedCornerShape(6.dp)) - .background(colors.accent.copy(0.12f)) - .clickable { - model.selectProject(proj.id) - isSidebarOpen = false - showDiffSheet = true - } - .padding(horizontal = 6.dp, vertical = 2.dp), + text = "已完成历史会话", + fontSize = 13.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + modifier = Modifier.weight(1f), ) - } - } - if (expanded && ws != null) { - val entries = workspaceEntries[ws.id].orEmpty() - Column(Modifier.padding(start = 28.dp)) { - entries.take(30).forEach { entry -> - Row( - Modifier.fillMaxWidth().padding(vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - Icon( - if (entry.directory) Icons.Rounded.Folder else Icons.Rounded.Description, - null, - tint = colors.textSecondary, - modifier = Modifier.size(14.dp), - ) - Text( - entry.name, - fontSize = 12.5.sp, + Box( + modifier = Modifier + .clip(CircleShape) + .background(colors.textPrimary.copy(alpha = 0.08f)) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) { + Text( + text = "${doneList.size}", + style = TextStyle( + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + fontFeatureSettings = "tnum", color = colors.textSecondary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) + ), + ) + } + } + + AnimatedVisibility( + visible = expanded, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut(), + ) { + SessionCardGroup( + items = doneList, + state = state, + showStatusBadge = false, + projectNameForWorkspace = ::projectNameForWorkspace, + onTap = { session -> + openSession(session, model) { viewedId -> + kanbanSessions = kanbanSessions.map { + if (it.id == viewedId) it.copy(status = KanbanSessionStatus.Done) else it } } + }, + onLongPress = { session, offset -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + contextAnchor = offset + contextTarget = session + }, + ) } } } } + } else { + workspaceGroups.forEach { (groupHeader, groupItems) -> + item(key = "ws_group_$groupHeader") { + SessionSectionBlock( + title = groupHeader, + tint = colors.textSecondary, + icon = Icons.Rounded.AccountTree, + items = groupItems, + state = state, + showStatusBadge = true, + projectNameForWorkspace = ::projectNameForWorkspace, + onTap = { session -> + openSession(session, model) { viewedId -> + kanbanSessions = kanbanSessions.map { + if (it.id == viewedId) it.copy(status = KanbanSessionStatus.Done) else it + } + } + }, + onLongPress = { session, offset -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + contextAnchor = offset + contextTarget = session + }, + ) + } + } } } } } + } - // Project Picker Bottom Sheet - if (showProjectSheet) { - ModalBottomSheet( - onDismissRequest = { showProjectSheet = false }, - containerColor = colors.bgElevated, - ) { - Column( - Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - "切换项目", - fontSize = 17.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, - modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp), - ) - projects.forEach { proj -> - val selected = proj.id == currentProject?.id - Row( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(12.dp)) - .background(if (selected) colors.accent.copy(0.12f) else colors.bg) - .clickable { - showProjectSheet = false - model.selectProject(proj.id) - } - .padding(horizontal = 14.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - Icon(Icons.Rounded.Folder, null, tint = if (selected) colors.accent else colors.textSecondary, modifier = Modifier.size(18.dp)) - Column(Modifier.weight(1f)) { - Text(proj.name, fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) - if (proj.path.isNotBlank()) { - Text(proj.path, fontSize = 11.sp, fontFamily = PlexMono, color = colors.textTertiary, maxLines = 1, overflow = TextOverflow.Ellipsis) + // Long-press Session Context Menu + val activeMenuSession = contextTarget + if (activeMenuSession != null && state.connection.allowsWrites) { + val isRecentRead = activeMenuSession.isRecentlyActiveReadSession(state.manuallyCompletedSessionIds) + val actions = buildList { + KanbanSessionStatus.activeColumns.forEach { targetStatus -> + val isCurrent = activeMenuSession.status == targetStatus && + !(targetStatus == KanbanSessionStatus.Done && isRecentRead) + if (!isCurrent) { + add( + ActionMenuItem("标为「${targetStatus.title}」") { + kanbanSessions = kanbanSessions.map { + if (it.id == activeMenuSession.id) { + it.copy( + status = targetStatus, + isRunning = if (targetStatus == KanbanSessionStatus.InProgress) it.isRunning else false, + ) + } else { + it } } - if (selected) { - Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(18.dp)) - } + model.setManualSessionStatus(activeMenuSession.id, targetStatus) + }, + ) + } + } + add( + ActionMenuItem(if (activeMenuSession.isPinned) "取消置顶" else "置顶会话") { + val nextPinned = !activeMenuSession.isPinned + kanbanSessions = kanbanSessions.map { + if (it.id == activeMenuSession.id) { + it.copy(pinnedAt = if (nextPinned) Instant.now().toString() else null) + } else { + it } } - Spacer(Modifier.height(16.dp)) - } + scope.launch { + runCatching { model.mutateKanbanSessionPinned(activeMenuSession.id, nextPinned) } + .onFailure { model.fail(it) } + } + }, + ) + add( + ActionMenuItem("重命名") { + renameDraft = activeMenuSession.name ?: activeMenuSession.resolvedTitle + renamingSession = activeMenuSession + }, + ) + if (activeMenuSession.isForkSupported) { + add( + ActionMenuItem("创建分支会话") { + scope.launch { + runCatching { model.mutateKanbanSessionFork(activeMenuSession.id) } + .onSuccess { forkedId -> + if (!forkedId.isNullOrBlank()) { + model.openConversation(forkedId) + } + } + .onFailure { model.fail(it) } + } + }, + ) } - } - - if (showDiffSheet && currentWorkspace != null) { - DiffListSheet( - workspaceId = currentWorkspace.id, - conversationId = state.conversations.firstOrNull()?.id.orEmpty(), - model = model, - onDismiss = { showDiffSheet = false }, + add( + ActionMenuItem("归档会话") { + removedIds = removedIds + activeMenuSession.id + model.archiveConversation(activeMenuSession.id) + }, ) - } - - if (showFileBrowserSheet && currentWorkspace != null) { - FileBrowserSheet( - workspaceId = currentWorkspace.id, - title = currentProject?.name ?: currentWorkspace.name.ifBlank { "文件" }, - model = model, - onDismiss = { showFileBrowserSheet = false }, + add( + ActionMenuItem("删除会话", danger = true) { + deletingSession = activeMenuSession + }, ) } - val menuItem = state.conversations.find { it.id == menuId } - if (menuItem != null && state.connection.allowsWrites) { - ActionMenu( - items = listOf( - ActionMenuItem(if (menuItem.pinned) "取消置顶" else "置顶") { model.pinConversation(menuItem.id, !menuItem.pinned) }, - ActionMenuItem("归档") { model.archiveConversation(menuItem.id) }, - ActionMenuItem("删除", danger = true) { model.deleteConversation(menuItem.id) }, + ActionMenu( + items = actions, + anchor = contextAnchor, + onDismiss = { contextTarget = null }, + ) + } + + // Rename Dialog + val activeRename = renamingSession + if (activeRename != null) { + AlertDialog( + onDismissRequest = { renamingSession = null }, + title = { Text("重命名会话") }, + text = { + OutlinedTextField( + value = renameDraft, + onValueChange = { renameDraft = it }, + singleLine = true, + placeholder = { Text("会话名称") }, + modifier = Modifier.fillMaxWidth(), + ) + }, + confirmButton = { + TextButton( + onClick = { + val trimmed = renameDraft.trim() + renamingSession = null + kanbanSessions = kanbanSessions.map { + if (it.id == activeRename.id) it.copy(name = trimmed.ifEmpty { null }) else it + } + scope.launch { + runCatching { model.mutateKanbanSessionRename(activeRename.id, trimmed.ifEmpty { null }) } + .onFailure { model.fail(it) } + } + }, + ) { + Text("保存") + } + }, + dismissButton = { + TextButton(onClick = { renamingSession = null }) { + Text("取消") + } + }, + ) + } + + // Delete Confirm Dialog + val activeDelete = deletingSession + if (activeDelete != null) { + AlertDialog( + onDismissRequest = { deletingSession = null }, + title = { Text("删除会话") }, + text = { Text("确定删除会话“${activeDelete.resolvedTitle}”吗?") }, + confirmButton = { + TextButton( + onClick = { + deletingSession = null + removedIds = removedIds + activeDelete.id + scope.launch { + runCatching { model.mutateKanbanSessionDelete(activeDelete.id) } + .onFailure { model.fail(it) } + } + }, + ) { + Text("删除", color = colors.danger) + } + }, + dismissButton = { + TextButton(onClick = { deletingSession = null }) { + Text("取消") + } + }, + ) + } +} + +private inline fun openSession( + session: KanbanSessionSummary, + model: CompanionModel, + onMarkViewedLocal: (String) -> Unit = {}, +) { + if (session.completesWhenViewed) { + onMarkViewedLocal(session.id) + model.markSessionViewed(session.id) + } + model.openConversation(session.id) +} + +@Composable +private fun EmptySessionsCard(isSearching: Boolean) { + val colors = VibexTheme.colors + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)) + .padding(horizontal = 20.dp, vertical = 42.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon( + imageVector = Icons.Rounded.ChatBubbleOutline, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(32.dp), + ) + Text( + text = if (isSearching) "没有找到匹配的会话" else "暂无会话记录", + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + ) + Text( + text = if (isSearching) "请尝试更换搜索关键词或切换项目筛选" else "点击底部胶囊栏中间的 + 发起新会话", + fontSize = 13.sp, + color = colors.textSecondary, + textAlign = TextAlign.Center, + ) + } +} + +@Composable +private fun SessionSectionBlock( + title: String, + tint: Color, + icon: ImageVector, + items: List, + state: UiState, + showStatusBadge: Boolean, + projectNameForWorkspace: (String) -> String?, + onTap: (KanbanSessionSummary) -> Unit, + onLongPress: (KanbanSessionSummary, Offset) -> Unit, +) { + val colors = VibexTheme.colors + Column(verticalArrangement = Arrangement.spacedBy(7.dp)) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = tint, + modifier = Modifier.size(14.dp), + ) + Text( + text = title, + fontSize = 12.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = "${items.size}", + style = TextStyle( + fontSize = 11.5.sp, + fontWeight = FontWeight.Medium, + fontFeatureSettings = "tnum", + color = colors.textTertiary, ), - anchor = menuAnchor, - onDismiss = { menuId = null }, ) + Spacer(modifier = Modifier.weight(1f)) } + + SessionCardGroup( + items = items, + state = state, + showStatusBadge = showStatusBadge, + projectNameForWorkspace = projectNameForWorkspace, + onTap = onTap, + onLongPress = onLongPress, + ) } } @Composable -private fun SidebarQuickNav(title: String, icon: ImageVector, modifier: Modifier = Modifier, onClick: () -> Unit) { +private fun SessionCardGroup( + items: List, + state: UiState, + showStatusBadge: Boolean, + projectNameForWorkspace: (String) -> String?, + onTap: (KanbanSessionSummary) -> Unit, + onLongPress: (KanbanSessionSummary, Offset) -> Unit, +) { val colors = VibexTheme.colors + val cardShape = RoundedCornerShape(16.dp) Column( - modifier - .clip(RoundedCornerShape(8.dp)) - .background(colors.bg) - .clickable(onClick = onClick) - .padding(vertical = 6.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier + .fillMaxWidth() + .clip(cardShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, cardShape), ) { - Icon(icon, null, tint = colors.textSecondary, modifier = Modifier.size(16.dp)) - Text(title, fontSize = 10.5.sp, fontWeight = FontWeight.Medium, color = colors.textSecondary, maxLines = 1) + items.forEachIndexed { idx, session -> + SessionRowItem( + session = session, + state = state, + showStatusBadge = showStatusBadge, + projectLabel = projectNameForWorkspace(session.workspaceId), + onTap = { onTap(session) }, + onLongPress = { offset -> onLongPress(session, offset) }, + ) + if (idx < items.lastIndex) { + HorizontalDivider( + modifier = Modifier.padding(start = 56.dp), + thickness = 0.5.dp, + color = colors.hairline, + ) + } + } } } -fun relativeTime(raw: String): String { - val parsed = parseInstant(raw) ?: return "" - val minutes = Duration.between(parsed, Instant.now()).toMinutes().coerceAtLeast(0) - return when { - minutes < 1 -> "刚刚" - minutes < 60 -> "${minutes}m" - minutes < 60 * 24 -> "${minutes / 60}h" - else -> "${minutes / (60 * 24)}d" +@Composable +private fun SessionRowItem( + session: KanbanSessionSummary, + state: UiState, + showStatusBadge: Boolean, + projectLabel: String?, + onTap: () -> Unit, + onLongPress: (Offset) -> Unit, +) { + val colors = VibexTheme.colors + val agentKey = session.effectiveAgentKey.ifBlank { "claude_code" } + val agent = catalogAgent(state, agentKey) + val branchLabel = session.workspaceDisplayLabel + val showProjectLabel = !projectLabel.isNullOrBlank() && state.selectedProjectId == null + val displayBranchLabel = remember(branchLabel, projectLabel, showProjectLabel) { + if (!showProjectLabel || projectLabel.isNullOrBlank()) { + branchLabel + } else { + val trimmed = branchLabel.trim() + val prefixDot = "$projectLabel · " + val prefixSlash = "$projectLabel/" + when { + trimmed.equals(projectLabel, ignoreCase = true) -> "" + trimmed.startsWith(prefixDot, ignoreCase = true) -> trimmed.substring(prefixDot.length).trim() + trimmed.startsWith(prefixSlash, ignoreCase = true) -> trimmed.substring(prefixSlash.length).trim() + else -> trimmed + } + } + } + val relTime = remember(session.updatedAt) { relativeTime(session.updatedAt) } + + Row( + modifier = Modifier + .fillMaxWidth() + .then(longPressModifier(onClick = onTap, onLongClick = onLongPress)) + .padding(horizontal = 14.dp, vertical = 11.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(11.dp), + ) { + Box(modifier = Modifier.size(32.dp)) { + Box( + modifier = Modifier + .fillMaxSize() + .clip(RoundedCornerShape(9.dp)) + .background(colors.textPrimary.copy(alpha = 0.06f)), + contentAlignment = Alignment.Center, + ) { + AgentAvatar( + agentId = agentKey, + size = 20.dp, + iconSvg = agent?.iconSvg, + displayName = agent?.displayName.orEmpty(), + ) + } + + val dotColor = when { + session.isRunning || session.status == KanbanSessionStatus.InProgress -> StatusOrange + session.status == KanbanSessionStatus.InReview -> StatusPurple + else -> null + } + if (dotColor != null) { + Box( + modifier = Modifier + .align(Alignment.BottomEnd) + .offset(x = 2.dp, y = 2.dp) + .size(9.dp) + .clip(CircleShape) + .background(colors.card) + .padding(1.5.dp) + .clip(CircleShape) + .background(dotColor), + ) + } + } + + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(3.5.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + if (session.isPinned) { + Icon( + imageVector = Icons.Rounded.PushPin, + contentDescription = "已置顶", + tint = StatusOrange, + modifier = Modifier.size(11.dp), + ) + } + Text( + text = session.resolvedTitle, + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + if (showProjectLabel) { + Text( + text = projectLabel.orEmpty(), + fontSize = 12.sp, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (displayBranchLabel.isNotEmpty()) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(2.dp), + ) { + Icon( + imageVector = Icons.Rounded.AccountTree, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(11.dp), + ) + Text( + text = displayBranchLabel, + fontSize = 12.sp, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + val modelLabel = session.model?.trim().orEmpty() + if (modelLabel.isNotEmpty()) { + Text( + text = "· $modelLabel", + fontSize = 12.sp, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + + Column( + horizontalAlignment = Alignment.End, + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (relTime.isNotEmpty()) { + Text( + text = relTime, + style = TextStyle( + fontSize = 11.sp, + fontFeatureSettings = "tnum", + color = colors.textTertiary, + ), + ) + } + if (showStatusBadge) { + val (badgeLabel, badgeColor) = sessionStatusBadge(session, state.manuallyCompletedSessionIds) + Box( + modifier = Modifier + .clip(CircleShape) + .background(badgeColor.copy(alpha = 0.13f)) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) { + Text( + text = badgeLabel, + fontSize = 10.sp, + fontWeight = FontWeight.SemiBold, + color = badgeColor, + ) + } + } + } } } -private fun parseInstant(raw: String): Instant? { - if (raw.isBlank()) return null - return runCatching { Instant.parse(raw) }.getOrNull() - ?: runCatching { OffsetDateTime.parse(raw).toInstant() }.getOrNull() +private fun sessionStatusBadge( + session: KanbanSessionSummary, + manuallyCompletedIds: Set, +): Pair { + if (session.isRunning || session.status == KanbanSessionStatus.InProgress) { + return "进行中" to StatusOrange + } + return when (session.status) { + KanbanSessionStatus.InReview -> "待检查" to StatusPurple + KanbanSessionStatus.Todo -> "待开始" to StatusBlue + KanbanSessionStatus.Done -> { + if (session.isRecentlyActiveReadSession(manuallyCompletedIds)) { + "近期对话" to StatusTeal + } else { + "已完成" to StatusGreen + } + } + KanbanSessionStatus.Archived -> "已归档" to Color.Gray + KanbanSessionStatus.InProgress -> "进行中" to StatusOrange + } +} + +fun relativeTime(raw: String): String { + val epochMs = parseHostTimestampEpochMillis(raw) ?: return "" + val minutes = ((System.currentTimeMillis() - epochMs).coerceAtLeast(0L)) / 60_000L + return when { + minutes < 1L -> "刚刚" + minutes < 60L -> "${minutes}m" + minutes < 60L * 24L -> "${minutes / 60L}h" + else -> "${minutes / (60L * 24L)}d" + } } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/DesktopConnectDialog.kt b/app/src/main/java/dev/vibex/companion/app/ui/DesktopConnectDialog.kt index 8e1de17..044edc0 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/DesktopConnectDialog.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/DesktopConnectDialog.kt @@ -10,36 +10,46 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.CheckCircle +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Cloud import androidx.compose.material.icons.rounded.Computer import androidx.compose.material.icons.rounded.Warning +import androidx.compose.material.icons.rounded.Wifi import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.vibex.companion.AccountDesktop +import dev.vibex.companion.DiscoveredLanHost import dev.vibex.companion.app.CompanionModel -import dev.vibex.companion.app.DesktopConnectRoute import dev.vibex.companion.app.DesktopConnectSheet import dev.vibex.companion.app.DesktopConnectStage import dev.vibex.companion.app.UiState import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme -/** 「发现你的电脑」: lists the account's desktops and connects one in a single tap. */ +/** + * 1:1 port of iOS `DesktopConnectSheet`: + * Same-account zero-click connection (LAN-first -> Cloud Relay) + LAN SAS fallback for unmatched hosts. + */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun DesktopConnectDialog( @@ -50,7 +60,15 @@ fun DesktopConnectDialog( ) { val colors = VibexTheme.colors val desktops = state.accountDesktops - val selected = desktops.firstOrNull { it.hostId == sheet.selectedHostId } + val selected = desktops.firstOrNull { it.hostId == sheet.selectedHostId } ?: desktops.firstOrNull() + val accountHostIds = remember(desktops) { desktops.map { it.hostId.lowercase() }.toSet() } + val unmatchedLanHosts = remember(state.discoveredHosts, accountHostIds) { + state.discoveredHosts.filter { host -> + val hId = host.hostId + !host.isCloudService && (hId == null || hId.lowercase() !in accountHostIds) + } + } + ModalBottomSheet( onDismissRequest = { model.dismissDesktopConnect() }, containerColor = colors.bgElevated, @@ -58,41 +76,96 @@ fun DesktopConnectDialog( Column( Modifier .fillMaxWidth() + .verticalScroll(rememberScrollState()) .padding(start = 20.dp, end = 20.dp, bottom = 24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp), ) { val stage = sheet.stage - val noDesktop = stage == DesktopConnectStage.Choosing && desktops.isEmpty() - if (!noDesktop) { - Text( - "发现你的电脑", - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - color = colors.textPrimary, - ) - } + val showEmptyAccountGuide = + stage == DesktopConnectStage.Choosing && desktops.isEmpty() && unmatchedLanHosts.isEmpty() && state.accountSignedIn + + if (!showEmptyAccountGuide) { + Text( + text = if (state.accountSignedIn) "连接你的电脑" else "当前 Wi-Fi 发现电脑", + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + } + when (stage) { - DesktopConnectStage.Syncing -> LoadingState("正在同步你的电脑") - DesktopConnectStage.Choosing -> if (noDesktop) { - NoDesktopGuide(onDownload = { model.openAccountSitePath("/download") }) - } else { - DesktopList(desktops, selected, onSelect = model::selectAccountDesktop) - selected?.let { RouteButtons(state, it, model) } + DesktopConnectStage.Syncing -> LoadingState("正在同步你的电脑…") + + DesktopConnectStage.Choosing -> { + if (showEmptyAccountGuide) { + NoDesktopGuide(onDownload = { model.openAccountSitePath("/download") }) + } else if (desktops.isEmpty() && unmatchedLanHosts.isEmpty()) { + Text( + text = "同一 Wi-Fi 下暂未发现运行中的 Dimo 电脑", + fontSize = 14.sp, + color = colors.textSecondary, + textAlign = TextAlign.Center, + modifier = Modifier.padding(vertical = 8.dp), + ) + } else { + if (desktops.isNotEmpty()) { + DesktopList( + desktops = desktops, + selected = selected, + model = model, + onSelect = model::selectAccountDesktop, + ) + selected?.let { SingleTapConnectArea(state = state, desktop = it, model = model) } + } + + if (unmatchedLanHosts.isNotEmpty()) { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (desktops.isNotEmpty()) { + Text( + text = "当前 Wi-Fi 其他电脑", + fontSize = 12.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + modifier = Modifier.padding(top = 4.dp, start = 2.dp), + ) + } + unmatchedLanHosts.forEach { host -> + LanDiscoveredHostRow( + host = host, + onClick = { model.connectLanHostInSheet(host) }, + ) + } + } + } + } } + is DesktopConnectStage.Connecting -> { - selected?.let { DesktopRow(it, isSelected = false, onClick = null) } - LoadingState("正在连接") + ConnectingTargetPreview(name = stage.target.displayName) + LoadingState("正在连接…") + } + + is DesktopConnectStage.AwaitingApproval -> { + ApprovalPromptCard(hostName = stage.hostName, sasCode = stage.sasCode) + } + + is DesktopConnectStage.Failed -> { + FailureState(stage.message, onRetry = model::retryDesktopConnect) } - is DesktopConnectStage.AwaitingApproval -> ApprovalPrompt(stage.sasCode) - is DesktopConnectStage.Failed -> FailureState(stage.message, onRetry = model::retryDesktopConnect) } + if (stage == DesktopConnectStage.Choosing || stage is DesktopConnectStage.Failed) { Text( - "使用连接码配对", + text = "扫码或输入 8 位连接码", fontSize = 13.sp, + fontWeight = FontWeight.Medium, color = colors.textTertiary, modifier = Modifier + .clip(RoundedCornerShape(8.dp)) .clickable(onClick = onPairWithCode) .padding(horizontal = 12.dp, vertical = 6.dp), ) @@ -102,20 +175,35 @@ fun DesktopConnectDialog( } @Composable -private fun DesktopList(desktops: List, selected: AccountDesktop?, onSelect: (String) -> Unit) { +private fun DesktopList( + desktops: List, + selected: AccountDesktop?, + model: CompanionModel, + onSelect: (String) -> Unit, +) { Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { desktops.forEach { desktop -> + val onSameWifi = model.lanOriginFor(desktop) != null + val isOnline = onSameWifi || desktop.cloudOnline DesktopRow( desktop = desktop, + onSameWifi = onSameWifi, isSelected = desktops.size > 1 && desktop.hostId == selected?.hostId, onClick = if (desktops.size > 1) ({ onSelect(desktop.hostId) }) else null, + onRemove = if (desktops.size > 1 && !isOnline) ({ model.removeAccountDesktop(desktop) }) else null, ) } } } @Composable -private fun DesktopRow(desktop: AccountDesktop, isSelected: Boolean, onClick: (() -> Unit)?) { +private fun DesktopRow( + desktop: AccountDesktop, + onSameWifi: Boolean, + isSelected: Boolean, + onClick: (() -> Unit)?, + onRemove: (() -> Unit)?, +) { val colors = VibexTheme.colors val shape = RoundedCornerShape(12.dp) Row( @@ -127,20 +215,56 @@ private fun DesktopRow(desktop: AccountDesktop, isSelected: Boolean, onClick: (( .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) .padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), ) { Icon(Icons.Rounded.Computer, null, tint = colors.accent, modifier = Modifier.size(22.dp)) Text( - desktop.hostName, + text = desktop.displayName, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) + if (onSameWifi) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(50)) + .background(colors.pass.copy(alpha = 0.14f)) + .padding(horizontal = 8.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon(Icons.Rounded.Wifi, null, tint = colors.pass, modifier = Modifier.size(11.dp)) + Text( + text = "局域网极速", + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + color = colors.pass, + ) + } + } else if (desktop.cloudOnline) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(50)) + .background(colors.pass.copy(alpha = 0.14f)) + .padding(horizontal = 8.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon(Icons.Rounded.Cloud, null, tint = colors.pass, modifier = Modifier.size(11.dp)) + Text( + text = "云端在线", + fontSize = 11.sp, + fontWeight = FontWeight.SemiBold, + color = colors.pass, + ) + } + } desktop.platformBadge?.let { Text( - it, + text = it, fontSize = 11.sp, fontWeight = FontWeight.Medium, color = colors.textSecondary, @@ -153,80 +277,187 @@ private fun DesktopRow(desktop: AccountDesktop, isSelected: Boolean, onClick: (( if (isSelected) { Icon(Icons.Rounded.CheckCircle, null, tint = colors.accent, modifier = Modifier.size(18.dp)) } + if (onRemove != null) { + Box( + modifier = Modifier + .size(24.dp) + .clip(CircleShape) + .clickable(onClick = onRemove), + contentAlignment = Alignment.Center, + ) { + Icon( + Icons.Rounded.Close, + contentDescription = "移除离线电脑", + tint = colors.textTertiary, + modifier = Modifier.size(15.dp), + ) + } + } } } @Composable -private fun RouteButtons(state: UiState, desktop: AccountDesktop, model: CompanionModel) { +private fun LanDiscoveredHostRow( + host: DiscoveredLanHost, + onClick: () -> Unit, +) { val colors = VibexTheme.colors - val cloudEnabled = state.accountOverview?.relayPermission != false - val lanEnabled = model.lanOriginFor(desktop) != null - Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { - RouteButton( - label = "使用云服务", - container = colors.accent, - content = colors.onAccent, - enabled = cloudEnabled, - modifier = Modifier.weight(1f), - ) { model.connectAccountDesktop(DesktopConnectRoute.Cloud) } - RouteButton( - label = "局域网", - container = colors.segmentedTrack, - content = colors.textPrimary, - enabled = lanEnabled, - modifier = Modifier.weight(1f), - ) { model.connectAccountDesktop(DesktopConnectRoute.Lan) } - } - if (!cloudEnabled) { - Text("账号未开通云服务", fontSize = 12.sp, color = colors.textTertiary) + val shape = RoundedCornerShape(12.dp) + Row( + modifier = Modifier + .fillMaxWidth() + .clip(shape) + .background(colors.card) + .border(0.75.dp, colors.stroke, shape) + .clickable(onClick = onClick) + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon(Icons.Rounded.Computer, null, tint = colors.textSecondary, modifier = Modifier.size(20.dp)) + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + text = host.displayName, + fontSize = 14.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = "对比连接码接入", + fontSize = 12.sp, + color = colors.textSecondary, + ) } + Text( + text = "连接", + fontSize = 12.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.accent, + modifier = Modifier + .clip(RoundedCornerShape(50)) + .background(colors.accent.copy(alpha = 0.14f)) + .padding(horizontal = 10.dp, vertical = 5.dp), + ) } } @Composable -private fun RouteButton( - label: String, - container: Color, - content: Color, - enabled: Boolean, - modifier: Modifier, - onClick: () -> Unit, +private fun SingleTapConnectArea( + state: UiState, + desktop: AccountDesktop, + model: CompanionModel, ) { - Box( - modifier - .alpha(if (enabled) 1f else 0.4f) - .clip(RoundedCornerShape(12.dp)) - .background(container) - .clickable(enabled = enabled, onClick = onClick) - .padding(vertical = 13.dp), - contentAlignment = Alignment.Center, + val colors = VibexTheme.colors + val lanEnabled = model.lanOriginFor(desktop) != null + val cloudEnabled = state.accountOverview?.canUseCloudRelay == true + val canConnect = lanEnabled || cloudEnabled + val hint = when { + lanEnabled -> "同一 Wi-Fi 自动走局域网直连" + cloudEnabled -> "当前通过 Dimo 云服务连接" + else -> "当前不在同一 Wi-Fi,且账号未开通云服务" + } + + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), ) { - Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = content) + Box( + modifier = Modifier + .fillMaxWidth() + .alpha(if (canConnect) 1f else 0.4f) + .clip(RoundedCornerShape(12.dp)) + .background(colors.accent) + .clickable(enabled = canConnect) { model.connectSelectedAccountDesktop() } + .padding(vertical = 13.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = "一键连接", + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + color = colors.onAccent, + ) + } + Text( + text = hint, + fontSize = 12.sp, + color = if (canConnect) colors.textSecondary else colors.danger, + textAlign = TextAlign.Center, + ) } } @Composable -private fun ApprovalPrompt(sasCode: String) { +private fun ConnectingTargetPreview(name: String) { val colors = VibexTheme.colors - Text("请在电脑上点击“连接”确认", fontSize = 14.sp, color = colors.textSecondary) - Text( - "核对码 $sasCode", - style = TextStyle( - fontSize = 24.sp, - fontWeight = FontWeight.Bold, - fontFamily = PlexMono, - fontFeatureSettings = "tnum", - color = colors.accent, - ), - ) - LoadingState("等待确认") + val shape = RoundedCornerShape(12.dp) + Row( + modifier = Modifier + .fillMaxWidth() + .clip(shape) + .background(colors.card) + .border(0.75.dp, colors.stroke, shape) + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon(Icons.Rounded.Computer, null, tint = colors.accent, modifier = Modifier.size(20.dp)) + Text( + text = name, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } +} + +@Composable +private fun ApprovalPromptCard(hostName: String, sasCode: String) { + val colors = VibexTheme.colors + val shape = RoundedCornerShape(16.dp) + Column( + modifier = Modifier + .fillMaxWidth() + .clip(shape) + .background(colors.card) + .border(0.75.dp, colors.stroke, shape) + .padding(horizontal = 18.dp, vertical = 18.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + text = "请在电脑「$hostName」上核对连接码并点击允许", + fontSize = 14.sp, + color = colors.textSecondary, + textAlign = TextAlign.Center, + ) + Text( + text = sasCode, + style = TextStyle( + fontSize = 30.sp, + fontWeight = FontWeight.Bold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + letterSpacing = 3.sp, + color = colors.accent, + ), + ) + LoadingState("等待电脑端确认…") + } } @Composable private fun FailureState(message: String, onRetry: () -> Unit) { val colors = VibexTheme.colors - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { Icon(Icons.Rounded.Warning, null, tint = colors.danger, modifier = Modifier.size(18.dp)) Text(message, fontSize = 14.sp, color = colors.danger, textAlign = TextAlign.Center) } @@ -237,10 +468,10 @@ private fun FailureState(message: String, onRetry: () -> Unit) { private fun NoDesktopGuide(onDownload: () -> Unit) { val colors = VibexTheme.colors Text( - "在电脑上安装 VibeX 并登录同一账号", + text = "在电脑上安装 Dimo 并登录同一账号,即可免输码连接", fontSize = 14.sp, color = colors.textSecondary, textAlign = TextAlign.Center, ) - PrimaryButton(label = "下载 VibeX", onClick = onDownload) + PrimaryButton(label = "下载 Dimo", onClick = onDownload) } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/FoldersScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/FoldersScreen.kt index 680607c..b646c08 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/FoldersScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/FoldersScreen.kt @@ -132,7 +132,7 @@ fun FoldersScreen(state: UiState, model: CompanionModel) { ) { item(key = "device_bar") { ConnectedDeviceBar( - name = host?.name ?: "VibeX Desktop", + name = host?.name ?: "Dimo 桌面端", detail = "已导入 ${allProjects.size} 个项目", statusColor = if (state.connection == ConnectionState.Online) colors.pass else colors.textTertiary, ) diff --git a/app/src/main/java/dev/vibex/companion/app/ui/LiquidNavBar.kt b/app/src/main/java/dev/vibex/companion/app/ui/LiquidNavBar.kt deleted file mode 100644 index 58f59e8..0000000 --- a/app/src/main/java/dev/vibex/companion/app/ui/LiquidNavBar.kt +++ /dev/null @@ -1,152 +0,0 @@ -package dev.vibex.companion.app.ui - -import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.core.spring -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.foundation.interaction.collectIsPressedAsState -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Icon -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.shadow -import androidx.compose.ui.graphics.Brush -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.hapticfeedback.HapticFeedbackType -import androidx.compose.ui.platform.LocalFocusManager -import androidx.compose.ui.platform.LocalHapticFeedback -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.role -import androidx.compose.ui.semantics.selected -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import dev.vibex.companion.app.ui.theme.VibexTheme - -data class LiquidTab( - val label: String, - val icon: ImageVector, - val selectedIcon: ImageVector, - val selected: Boolean, - val onClick: () -> Unit, -) - -@Composable -fun LiquidNavBar(tabs: List, modifier: Modifier = Modifier) { - val colors = VibexTheme.colors - val haptic = LocalHapticFeedback.current - val focusManager = LocalFocusManager.current - val dockBackground = if (colors.isDark) { - Color(0xFF1C1C1E).copy(alpha = 0.92f) - } else { - Color(0xFFFFFFFF).copy(alpha = 0.95f) - } - val specularBorder = Brush.verticalGradient( - colors = if (colors.isDark) { - listOf(Color.White.copy(alpha = 0.20f), Color.White.copy(alpha = 0.06f)) - } else { - listOf(Color.Black.copy(alpha = 0.08f), Color.Black.copy(alpha = 0.05f)) - }, - ) - - Box( - modifier = modifier - .fillMaxWidth() - .navigationBarsPadding() - .padding(horizontal = 22.dp, vertical = 6.dp), - ) { - Row( - Modifier - .fillMaxWidth() - .shadow( - elevation = if (colors.isDark) 14.dp else 10.dp, - shape = CircleShape, - ambientColor = Color.Black.copy(alpha = if (colors.isDark) 0.26f else 0.08f), - spotColor = Color.Black.copy(alpha = if (colors.isDark) 0.32f else 0.12f), - ) - .clip(CircleShape) - .background(dockBackground) - .border(0.6.dp, specularBorder, CircleShape) - .padding(horizontal = 5.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - tabs.forEach { tab -> - val tint = if (tab.selected) colors.accent else colors.textSecondary - val interactionSource = remember { MutableInteractionSource() } - val pressed by interactionSource.collectIsPressedAsState() - val scale by animateFloatAsState( - targetValue = if (pressed) 0.94f else 1f, - animationSpec = spring(stiffness = 600f), - label = "tabScale", - ) - val pillBg = if (tab.selected) { - if (colors.isDark) Color.White.copy(alpha = 0.10f) else colors.accent.copy(alpha = 0.10f) - } else { - Color.Transparent - } - Column( - Modifier - .weight(1f) - .graphicsLayer { - scaleX = scale - scaleY = scale - } - .clip(CircleShape) - .background(pillBg) - .semantics { - contentDescription = tab.label - role = Role.Tab - selected = tab.selected - } - .clickable( - interactionSource = interactionSource, - indication = null, - onClick = { - if (!tab.selected) { - haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) - } - focusManager.clearFocus() - tab.onClick() - }, - ) - .padding(vertical = 6.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically), - ) { - Icon( - if (tab.selected) tab.selectedIcon else tab.icon, - contentDescription = null, - tint = tint, - modifier = Modifier.size(19.dp), - ) - Text( - tab.label, - color = tint, - fontSize = 10.5.sp, - fontWeight = if (tab.selected) FontWeight.SemiBold else FontWeight.Medium, - ) - } - } - } - } -} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/LoginScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/LoginScreen.kt index 6414abf..0f3ed95 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/LoginScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/LoginScreen.kt @@ -106,6 +106,12 @@ fun LoginScreen(state: UiState, model: CompanionModel, onPairWithCode: () -> Uni Modifier .fillMaxSize() .background(colors.bg) + .clickable( + interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }, + indication = null, + ) { + focusManager.clearFocus() + } .statusBarsPadding() .navigationBarsPadding() .imePadding() @@ -129,7 +135,7 @@ fun LoginScreen(state: UiState, model: CompanionModel, onPairWithCode: () -> Uni Spacer(Modifier.height(14.dp)) Text("欢迎回来", fontSize = 24.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary) Spacer(Modifier.height(4.dp)) - Text("登录你的 VibeX 账号", fontSize = 14.sp, color = colors.textSecondary) + Text("登录你的 Dimo 账号", fontSize = 14.sp, color = colors.textSecondary) Spacer(Modifier.height(24.dp)) ModeSwitch(mode) { mode = it } Spacer(Modifier.height(16.dp)) diff --git a/app/src/main/java/dev/vibex/companion/app/ui/NavMotion.kt b/app/src/main/java/dev/vibex/companion/app/ui/NavMotion.kt index ba25f3d..2dcc50a 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/NavMotion.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/NavMotion.kt @@ -7,15 +7,12 @@ import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.snap import androidx.compose.animation.core.tween -import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut -import androidx.compose.animation.shrinkVertically import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically -import androidx.compose.ui.Alignment /** * Page transitions shared by every navigation level, so a push, a pop and a tab switch @@ -28,7 +25,6 @@ import androidx.compose.ui.Alignment internal object NavMotion { private const val SLIDE_MILLIS = 340 private const val FADE_MILLIS = 160 - private const val CHROME_MILLIS = 220 private const val UNDERLAY_ALPHA = 0.6f private val Decelerate = CubicBezierEasing(0.32f, 0.72f, 0f, 1f) @@ -75,9 +71,4 @@ internal object NavMotion { targetContentZIndex = zIndex, sizeTransform = null, ) - - val bottomBarEnter: EnterTransition = - expandVertically(tween(CHROME_MILLIS, easing = Decelerate), expandFrom = Alignment.Top) - val bottomBarExit: ExitTransition = - shrinkVertically(tween(CHROME_MILLIS, easing = Decelerate), shrinkTowards = Alignment.Top) } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/NewThreadScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/NewThreadScreen.kt new file mode 100644 index 0000000..66d83ff --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/NewThreadScreen.kt @@ -0,0 +1,718 @@ +package dev.vibex.companion.app.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight +import androidx.compose.material.icons.rounded.AccountTree +import androidx.compose.material.icons.rounded.Add +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Computer +import androidx.compose.material.icons.rounded.Folder +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.vibex.companion.CatalogAgent +import dev.vibex.companion.SessionConfigChoice +import dev.vibex.companion.SessionConfigOption +import dev.vibex.companion.SessionMode +import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.Route +import dev.vibex.companion.app.UiState +import dev.vibex.companion.app.ui.theme.PlexMono +import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.fallbackModelOptionForAgent + +private data class NewThreadStarterChip(val id: String, val label: String, val prompt: String) + +private val newThreadSuggestions = listOf( + NewThreadStarterChip("arch", "梳理项目架构", "梳理当前项目的整体架构、目录结构与核心模块职责"), + NewThreadStarterChip("bug", "排查近期改动", "检查当前工作区最近的代码改动,排查潜在问题并给出修复方案"), + NewThreadStarterChip("test", "补充单元测试", "为当前工作区最近修改的核心逻辑补充单元测试并运行验证"), +) + +/** + * 1:1 port of iOS Level-2 `新建会话` (`newThreadScreen` in `ConversationsView.swift`). + * Triggered by the centered `+` button in the Level-1 floating capsule dock, with top-right + * `WorkspaceDualToolsCapsule`, lightweight 2-row project/host/branch breadcrumbs above the + * unified `PromptBar`, and zero bottom dock interference. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun NewThreadScreen( + state: UiState, + model: CompanionModel, +) { + val colors = VibexTheme.colors + val focusManager = LocalFocusManager.current + + BackHandler { + model.go(Route.Conversations) + } + + val projects = state.catalog?.projects.orEmpty() + val workspaces = state.catalog?.workspaces.orEmpty() + val usableAgents = remember(state.catalog?.agents) { + val all = state.catalog?.agents.orEmpty() + all.filter { it.usable }.ifEmpty { all } + } + + var selectedProjectId by remember(state.selectedProjectId) { + mutableStateOf(state.selectedProjectId) + } + var selectedWorkspaceId by remember { mutableStateOf(null) } + var selectedAgentId by remember { mutableStateOf(null) } + var selectedModeId by remember { mutableStateOf("auto") } + var selectedEffortValue by remember { mutableStateOf("medium") } + var selectedModelByAgent by remember { mutableStateOf>(emptyMap()) } + + var isDraftEmpty by remember { mutableStateOf(true) } + var seedText by remember { mutableStateOf("") } + var seedVersion by remember { mutableIntStateOf(0) } + + var diffCount by remember { mutableIntStateOf(0) } + var diffAdditions by remember { mutableLongStateOf(0L) } + var diffDeletions by remember { mutableLongStateOf(0L) } + + var showProjectSheet by remember { mutableStateOf(false) } + var workspaceMenuExpanded by remember { mutableStateOf(false) } + var showNewWorktreeDialog by remember { mutableStateOf(false) } + var newWorktreeName by remember { mutableStateOf("") } + var newWorktreeBranch by remember { mutableStateOf("") } + var showDiffSheet by remember { mutableStateOf(false) } + var showFileBrowserSheet by remember { mutableStateOf(false) } + + val currentProject = remember(projects, selectedProjectId, state.selectedProjectId) { + val targetId = selectedProjectId ?: state.selectedProjectId + projects.find { targetId != null && it.id.equals(targetId, ignoreCase = true) } + ?: projects.firstOrNull { !it.path.endsWith("/.vibex") && !it.path.endsWith("/.dimo") } + ?: projects.firstOrNull() + } + + val projectWorkspaces = remember(workspaces, currentProject) { + if (currentProject == null) emptyList() + else workspaces.filter { it.projectId.equals(currentProject.id, ignoreCase = true) } + } + + val currentWorkspace = remember(projectWorkspaces, workspaces, selectedWorkspaceId) { + projectWorkspaces.find { it.id == selectedWorkspaceId } + ?: projectWorkspaces.firstOrNull() + ?: workspaces.firstOrNull() + } + + val currentAgent = remember(usableAgents, selectedAgentId, state.conversations) { + usableAgents.find { it.id == selectedAgentId } + ?: usableAgents.find { it.id == state.conversations.firstOrNull()?.agentId } + ?: usableAgents.firstOrNull() + } + val currentAgentId = currentAgent?.id ?: "claude_code" + + LaunchedEffect(currentWorkspace?.id) { + val wsId = currentWorkspace?.id + if (wsId.isNullOrBlank()) { + diffCount = 0 + diffAdditions = 0L + diffDeletions = 0L + } else { + model.fetchWorkspaceDiff(wsId) { result -> + val diffs = result.getOrNull().orEmpty() + diffCount = diffs.size + diffAdditions = diffs.sumOf { it.additions.toLong() } + diffDeletions = diffs.sumOf { it.deletions.toLong() } + } + } + } + + val landingModes = remember(currentAgent) { + currentAgent?.sessionModes?.takeIf { it.isNotEmpty() } ?: listOf( + SessionMode("manual", "手动审批"), + SessionMode("accept_edits", "自动接受编辑"), + SessionMode("plan", "仅规划"), + SessionMode("auto", "自动"), + SessionMode("bypass", "完全访问"), + ) + } + + val baseModelOption = remember(currentAgent, currentAgentId) { + currentAgent?.modelOptions?.firstOrNull() ?: fallbackModelOptionForAgent(currentAgentId) + } + + val baseEffortOption = remember(currentAgent) { + currentAgent?.otherOptions?.firstOrNull { + val k = it.key.lowercase() + val c = it.category.lowercase() + c == "thought_level" || k.contains("effort") || k.contains("reasoning") || k.contains("thinking") + } ?: SessionConfigOption( + key = "reasoning_effort", + label = "思考强度", + category = "thought_level", + value = "medium", + choices = listOf( + SessionConfigChoice("low", "低"), + SessionConfigChoice("medium", "中"), + SessionConfigChoice("high", "高"), + ), + ) + } + + val activeModelValue = selectedModelByAgent[currentAgentId] + ?: baseModelOption.value.ifBlank { baseModelOption.choices.firstOrNull()?.value ?: "default" } + + val landingConfigOptions = remember( + baseModelOption, + baseEffortOption, + activeModelValue, + selectedEffortValue, + ) { + val nextModelChoices = if (baseModelOption.choices.any { it.value == activeModelValue }) { + baseModelOption.choices + } else { + listOf(CatalogAgent.makeCustomChoice(activeModelValue)) + baseModelOption.choices + } + listOf( + baseModelOption.copy(value = activeModelValue, choices = nextModelChoices), + baseEffortOption.copy(value = selectedEffortValue), + ) + } + + val resolvedWsId = currentWorkspace?.id?.ifBlank { null } + ?: state.conversations.firstOrNull { it.workspaceId.isNotBlank() }?.workspaceId + + val activeHostName = remember(state.profiles, state.selectedHostId) { + state.profiles.find { it.hostId == state.selectedHostId }?.name?.ifBlank { null } ?: "Dimo 桌面端" + } + + val branchLabel = remember(currentWorkspace) { + currentWorkspace?.branch?.ifBlank { null } + ?: currentWorkspace?.name?.ifBlank { null } + ?: "main" + } + + Column( + modifier = Modifier + .fillMaxSize() + .background(colors.bg) + .navigationBarsPadding() + .imePadding(), + ) { + // Level-2 Header Bar: `<` | `新建会话` | `[ ⑂ | 📁 ]` + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + FloatingCircleBackButton( + onClick = { model.go(Route.Conversations) }, + ) + + Text( + text = "新建会话", + fontSize = 20.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + + Spacer(modifier = Modifier.weight(1f)) + + WorkspaceDualToolsCapsule( + diffCount = diffCount, + additionCount = diffAdditions, + deletionCount = diffDeletions, + enabled = currentWorkspace != null, + onOpenDiff = { showDiffSheet = true }, + onOpenFiles = { showFileBrowserSheet = true }, + ) + } + + // Calm Center Canvas — tap anywhere to dismiss keyboard + Column( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) { + focusManager.clearFocus() + } + .padding(horizontal = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box( + modifier = Modifier + .size(56.dp) + .shadow( + elevation = 8.dp, + shape = RoundedCornerShape(14.dp), + ambientColor = Color.Black.copy(alpha = 0.08f), + spotColor = Color.Black.copy(alpha = 0.12f), + ) + .clip(RoundedCornerShape(14.dp)) + .background(colors.card), + contentAlignment = Alignment.Center, + ) { + BrandMark(40.dp) + } + + Spacer(modifier = Modifier.height(14.dp)) + + Text( + text = "有什么可以帮你?", + fontSize = 21.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + textAlign = TextAlign.Center, + ) + } + + // Quiet Starter Suggestion Chips when composer is empty + if (isDraftEmpty) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 6.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + newThreadSuggestions.forEach { chip -> + Text( + text = chip.label, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + modifier = Modifier + .clip(CircleShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, CircleShape) + .clickable { + seedText = chip.prompt + seedVersion += 1 + } + .padding(horizontal = 13.dp, vertical = 7.5.dp), + ) + } + } + } + + // Lightweight 2-Row Context Breadcrumbs above Composer (1:1 with iOS `newThreadContextBreadcrumbs`) + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 18.dp) + .padding(top = 6.dp, bottom = 10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + // Row 1: `📁 ›` + `💻 ›` + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + focusManager.clearFocus() + showProjectSheet = true + } + .padding(vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Icon( + imageVector = Icons.Rounded.Folder, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(14.dp), + ) + Text( + text = currentProject?.name ?: "选择项目", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(14.dp), + ) + } + + Row( + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + focusManager.clearFocus() + model.openDesktopConnect() + } + .padding(vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Icon( + imageVector = Icons.Rounded.Computer, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(14.dp), + ) + Text( + text = activeHostName, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(14.dp), + ) + } + } + + // Row 2: `📁 当前检出` + `⑂ ›` + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Icon( + imageVector = Icons.Rounded.Folder, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(14.dp), + ) + Text( + text = "当前检出", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + ) + } + + Box { + Row( + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable(enabled = currentProject != null) { + focusManager.clearFocus() + workspaceMenuExpanded = true + } + .padding(vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + ) { + Icon( + imageVector = Icons.Rounded.AccountTree, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(14.dp), + ) + Text( + text = branchLabel, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(14.dp), + ) + } + + VibexDropdownMenu( + expanded = workspaceMenuExpanded, + onDismissRequest = { workspaceMenuExpanded = false }, + ) { + projectWorkspaces.forEach { ws -> + val label = ws.branch.ifBlank { ws.name.ifBlank { "默认工作区" } } + val isSelected = ws.id == currentWorkspace?.id + VibexDropdownMenuItem( + text = label, + leadingIcon = Icons.Rounded.AccountTree, + selected = isSelected, + onClick = { + workspaceMenuExpanded = false + selectedWorkspaceId = ws.id + }, + ) + } + if (currentProject != null && state.connection.allowsWrites) { + if (projectWorkspaces.isNotEmpty()) { + VibexDropdownDivider() + } + VibexDropdownMenuItem( + text = "新建工作树…", + leadingIcon = Icons.Rounded.Add, + onClick = { + workspaceMenuExpanded = false + newWorktreeName = "" + newWorktreeBranch = "" + showNewWorktreeDialog = true + }, + ) + } + } + } + } + } + + // Unified Floating Capsule Composer + PromptBar( + conversationKey = "new_thread", + externalDraftSeed = seedText, + externalSeedVersion = seedVersion, + onDraftEmptyChanged = { isDraftEmpty = it }, + agentId = currentAgentId, + agent = currentAgent, + agents = usableAgents, + allowCrossAgentSwitch = true, + modes = landingModes, + currentModeId = selectedModeId, + configOptions = landingConfigOptions, + modelPrefs = model.modelPrefs, + isStreaming = false, + enabled = state.connection.allowsWrites && !resolvedWsId.isNullOrBlank(), + onSubmit = { text -> + val wsId = resolvedWsId ?: return@PromptBar + model.createConversation( + workspaceId = wsId, + agentId = currentAgentId, + title = text.take(36), + prompt = text, + modeId = selectedModeId, + config = mapOf( + baseModelOption.key to activeModelValue, + baseEffortOption.key to selectedEffortValue, + ), + ) + }, + onStop = {}, + onSelectAgentAndModel = { nextAgentId, _, modelValue -> + selectedAgentId = nextAgentId + if (modelValue.isNotBlank()) { + selectedModelByAgent = selectedModelByAgent + (nextAgentId to modelValue) + } + }, + onSelectMode = { modeId -> + selectedModeId = modeId + }, + onSelectOption = { key, value -> + if (key == baseModelOption.key || key.lowercase().contains("model")) { + selectedModelByAgent = selectedModelByAgent + (currentAgentId to value) + } else { + selectedEffortValue = value + } + }, + onOpenFileBrowser = if (currentWorkspace != null) { + { showFileBrowserSheet = true } + } else { + null + }, + onRefreshCatalog = { model.loadCatalogSilent() }, + ) + } + + // Project Picker Bottom Sheet + if (showProjectSheet) { + ModalBottomSheet( + onDismissRequest = { showProjectSheet = false }, + containerColor = colors.bgElevated, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = "选择项目", + fontSize = 17.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp), + ) + projects.forEach { proj -> + val selected = proj.id.equals(currentProject?.id, ignoreCase = true) + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(if (selected) colors.accent.copy(alpha = 0.12f) else colors.bg) + .clickable { + showProjectSheet = false + selectedProjectId = proj.id + selectedWorkspaceId = null + model.selectProjectInPlace(proj.id) + } + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Icon( + imageVector = Icons.Rounded.Folder, + contentDescription = null, + tint = if (selected) colors.accent else colors.textSecondary, + modifier = Modifier.size(18.dp), + ) + Column(modifier = Modifier.weight(1f)) { + Text( + text = proj.name, + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + ) + if (proj.path.isNotBlank()) { + Text( + text = proj.path, + fontSize = 11.sp, + fontFamily = PlexMono, + color = colors.textTertiary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + if (selected) { + Icon( + imageVector = Icons.Rounded.Check, + contentDescription = null, + tint = colors.accent, + modifier = Modifier.size(18.dp), + ) + } + } + } + Spacer(modifier = Modifier.height(16.dp)) + } + } + } + + // New Worktree Dialog + val activeProjectForWorktree = currentProject + if (showNewWorktreeDialog && activeProjectForWorktree != null) { + AlertDialog( + onDismissRequest = { showNewWorktreeDialog = false }, + title = { Text("新建工作树") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + OutlinedTextField( + value = newWorktreeName, + onValueChange = { newWorktreeName = it }, + singleLine = true, + label = { Text("工作区名称") }, + placeholder = { Text("例如 feat-auth") }, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = newWorktreeBranch, + onValueChange = { newWorktreeBranch = it }, + singleLine = true, + label = { Text("分支名称(可选)") }, + placeholder = { Text("例如 feat/auth") }, + modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + TextButton( + enabled = newWorktreeName.trim().isNotEmpty(), + onClick = { + val name = newWorktreeName.trim() + val branch = newWorktreeBranch.trim().ifEmpty { null } + showNewWorktreeDialog = false + model.createWorkspace(activeProjectForWorktree.id, name, branch) { createdId -> + selectedWorkspaceId = createdId + } + }, + ) { + Text("创建") + } + }, + dismissButton = { + TextButton(onClick = { showNewWorktreeDialog = false }) { + Text("取消") + } + }, + ) + } + + if (showDiffSheet && currentWorkspace != null) { + DiffListSheet( + workspaceId = currentWorkspace.id, + conversationId = "", + model = model, + onDismiss = { showDiffSheet = false }, + ) + } + + if (showFileBrowserSheet && currentWorkspace != null) { + FileBrowserSheet( + workspaceId = currentWorkspace.id, + title = currentProject?.name ?: currentWorkspace.name.ifBlank { "项目文件" }, + model = model, + onDismiss = { showFileBrowserSheet = false }, + ) + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/PairingCodeScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/PairingCodeScreen.kt index 9d6025e..88429f4 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/PairingCodeScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/PairingCodeScreen.kt @@ -25,13 +25,17 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight import androidx.compose.material.icons.outlined.QrCodeScanner import androidx.compose.material.icons.rounded.Cancel +import androidx.compose.material.icons.rounded.Computer import androidx.compose.material.icons.rounded.ContentPaste import androidx.compose.material.icons.rounded.Warning +import androidx.compose.material.icons.rounded.Wifi import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -44,9 +48,11 @@ import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.LanSasInlineState import dev.vibex.companion.app.UiState import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme @@ -62,8 +68,16 @@ fun PairingCodeScreen( val clipboard = LocalClipboardManager.current var code by remember { mutableStateOf("") } val trimmedCode = code.trim() - val isInvitation = trimmedCode.startsWith("vibex-pairing:") || trimmedCode.startsWith("{") + val isInvitation = trimmedCode.startsWith("vibex-pairing:") || trimmedCode.startsWith("dimo-pairing:") || trimmedCode.startsWith("{") val canSubmit = !state.pairing && trimmedCode.isNotEmpty() + val lanHosts = remember(state.discoveredHosts) { state.discoveredHosts.filter { !it.isCloudService } } + + LaunchedEffect(Unit) { + model.discoverHosts() + } + DisposableEffect(Unit) { + onDispose { model.cancelLanHostInline() } + } val submit = { if (canSubmit) { @@ -95,10 +109,13 @@ fun PairingCodeScreen( color = colors.accent, modifier = Modifier .align(Alignment.CenterStart) - .clickable(enabled = !state.pairing, onClick = onDismiss), + .clickable(enabled = !state.pairing) { + model.cancelLanHostInline() + onDismiss() + }, ) Text( - "配对电脑", + "连接电脑", fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, @@ -108,13 +125,13 @@ fun PairingCodeScreen( Box(Modifier.align(Alignment.CenterEnd)) { if (state.pairing) { CircularProgressIndicator(Modifier.size(18.dp), color = colors.accent, strokeWidth = 2.dp) - } else { + } else if (canSubmit) { Text( - "配对", + "连接", fontSize = 16.sp, fontWeight = FontWeight.SemiBold, - color = if (canSubmit) colors.accent else colors.textTertiary, - modifier = Modifier.clickable(enabled = canSubmit, onClick = submit), + color = colors.accent, + modifier = Modifier.clickable(onClick = submit), ) } } @@ -128,33 +145,162 @@ fun PairingCodeScreen( .padding(horizontal = 16.dp, vertical = 16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { + val inlineSas = state.lanSasState + if (inlineSas != null) { + val shape = RoundedCornerShape(14.dp) + Column( + modifier = Modifier + .fillMaxWidth() + .clip(shape) + .background(colors.card) + .border(0.75.dp, colors.accent.copy(alpha = 0.40f), shape) + .padding(horizontal = 16.dp, vertical = 16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + when (inlineSas) { + is LanSasInlineState.Connecting -> { + LoadingState("正在请求连接 ${inlineSas.host.displayName}…") + Text( + text = "取消", + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { model.cancelLanHostInline() } + .padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + is LanSasInlineState.AwaitingApproval -> { + Text( + text = "请在电脑「${inlineSas.hostName}」上核对连接码并点击允许", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + textAlign = TextAlign.Center, + ) + Text( + text = inlineSas.sasCode, + style = TextStyle( + fontSize = 30.sp, + fontWeight = FontWeight.Bold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + letterSpacing = 3.sp, + color = colors.accent, + ), + ) + Text( + text = "核对一致后,在电脑端点击「允许连接」即可接入", + fontSize = 12.sp, + color = colors.textSecondary, + textAlign = TextAlign.Center, + ) + Text( + text = "取消等待", + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = colors.danger, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { model.cancelLanHostInline() } + .padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + } + } + } else if (lanHosts.isNotEmpty()) { + val shape = RoundedCornerShape(14.dp) + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.padding(horizontal = 4.dp), + ) { + Icon(Icons.Rounded.Wifi, null, tint = colors.pass, modifier = Modifier.size(14.dp)) + Text( + text = "当前 Wi-Fi 发现电脑(免输码,对比连接码即连)", + fontSize = 12.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + ) + } + Column( + modifier = Modifier + .fillMaxWidth() + .clip(shape) + .background(colors.card) + .border(0.75.dp, colors.stroke, shape), + ) { + lanHosts.forEachIndexed { idx, host -> + if (idx > 0) { + HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 48.dp)) + } + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(enabled = !state.pairing) { model.connectLanHostInline(host) } + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Icon(Icons.Rounded.Computer, null, tint = colors.accent, modifier = Modifier.size(20.dp)) + Text( + text = host.displayName, + fontSize = 14.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Text( + text = "点击连接", + fontSize = 12.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.accent, + modifier = Modifier + .clip(CircleShape) + .background(colors.accent.copy(alpha = 0.14f)) + .padding(horizontal = 10.dp, vertical = 5.dp), + ) + } + } + } + } + } + Column( Modifier .fillMaxWidth() - .clip(RoundedCornerShape(12.dp)) + .clip(RoundedCornerShape(14.dp)) .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(12.dp)), + .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)), ) { Row( Modifier .fillMaxWidth() .clickable(enabled = !state.pairing, onClick = onScan) - .padding(horizontal = 14.dp, vertical = 12.dp), + .padding(horizontal = 14.dp, vertical = 13.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Box( Modifier - .size(38.dp) + .size(40.dp) .clip(RoundedCornerShape(10.dp)) .background(colors.accent.copy(0.14f)), contentAlignment = Alignment.Center, ) { - Icon(Icons.Outlined.QrCodeScanner, null, tint = colors.accent, modifier = Modifier.size(20.dp)) + Icon(Icons.Outlined.QrCodeScanner, null, tint = colors.accent, modifier = Modifier.size(21.dp)) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text("扫码配对", fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary) - Text("扫描桌面端二维码自动配对", fontSize = 12.sp, color = colors.textSecondary) + Text("扫码连接", fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary) + Text("扫描桌面端二维码自动配对连接", fontSize = 12.sp, color = colors.textSecondary) } Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = colors.textTertiary, modifier = Modifier.size(18.dp)) } @@ -183,6 +329,7 @@ fun PairingCodeScreen( color = colors.textPrimary, fontSize = 14.sp, fontFamily = PlexMono, + fontFeatureSettings = "tnum", ), cursorBrush = SolidColor(colors.accent), modifier = Modifier.fillMaxWidth(), @@ -197,26 +344,38 @@ fun PairingCodeScreen( .size(18.dp) .clickable { code = "" }, ) - } - Row( - Modifier - .clip(CircleShape) - .background(colors.accent.copy(0.14f)) - .clickable { - val pasted = clipboard.getText()?.text.orEmpty().trim() - if (pasted.isNotEmpty()) { - code = pasted - if (pasted.startsWith("vibex-pairing:") || pasted.startsWith("{")) { - model.pairFromRaw(pasted) + Text( + text = "连接", + fontSize = 12.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.onAccent, + modifier = Modifier + .clip(CircleShape) + .background(colors.accent) + .clickable(enabled = canSubmit, onClick = submit) + .padding(horizontal = 11.dp, vertical = 5.dp), + ) + } else { + Row( + Modifier + .clip(CircleShape) + .background(colors.accent.copy(0.14f)) + .clickable { + val pasted = clipboard.getText()?.text.orEmpty().trim() + if (pasted.isNotEmpty()) { + code = pasted + if (pasted.startsWith("vibex-pairing:") || pasted.startsWith("dimo-pairing:") || pasted.startsWith("{")) { + model.pairFromRaw(pasted) + } } } - } - .padding(horizontal = 10.dp, vertical = 5.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - Icon(Icons.Rounded.ContentPaste, null, tint = colors.accent, modifier = Modifier.size(13.dp)) - Text("粘贴", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.accent) + .padding(horizontal = 10.dp, vertical = 5.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon(Icons.Rounded.ContentPaste, null, tint = colors.accent, modifier = Modifier.size(13.dp)) + Text("粘贴", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.accent) + } } } } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/PromptBar.kt b/app/src/main/java/dev/vibex/companion/app/ui/PromptBar.kt index 3748c0c..2cb9612 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/PromptBar.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/PromptBar.kt @@ -1,1439 +1,714 @@ package dev.vibex.companion.app.ui +import android.Manifest +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Bundle +import android.speech.RecognitionListener +import android.speech.RecognizerIntent +import android.speech.SpeechRecognizer +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.PickVisualMediaRequest +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.core.spring -import androidx.compose.animation.expandVertically +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut -import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectHorizontalDragGestures -import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField -import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add -import androidx.compose.material.icons.rounded.AutoAwesome -import androidx.compose.material.icons.rounded.Check -import androidx.compose.material.icons.rounded.ChevronLeft -import androidx.compose.material.icons.rounded.CreateNewFolder +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Compress +import androidx.compose.material.icons.rounded.Folder +import androidx.compose.material.icons.rounded.GraphicEq import androidx.compose.material.icons.rounded.KeyboardArrowDown -import androidx.compose.material.icons.rounded.PhotoCamera +import androidx.compose.material.icons.rounded.Mic import androidx.compose.material.icons.rounded.PhotoLibrary -import androidx.compose.material.icons.rounded.VerifiedUser -import androidx.compose.material3.AlertDialog +import androidx.compose.material.icons.rounded.Tune +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon -import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.rotate +import androidx.compose.ui.draw.scale import androidx.compose.ui.draw.shadow -import androidx.compose.ui.focus.onFocusChanged -import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.core.content.ContextCompat +import coil.compose.AsyncImage import dev.vibex.companion.CatalogAgent -import dev.vibex.companion.SessionConfigChoice import dev.vibex.companion.SessionConfigOption import dev.vibex.companion.SessionMode -import dev.vibex.companion.agentDisplayName -import dev.vibex.companion.bundledAgentAsset +import dev.vibex.companion.app.data.ModelPreferencesStore import dev.vibex.companion.app.ui.theme.VibexTheme -import kotlin.math.roundToInt +import java.util.Locale +import java.util.UUID +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch enum class ComposerMenu { Plus, Agent, Model, Effort } -private enum class PlusPanel { Grid, Agent, Model, Mode, Permission } +private data class AttachedMediaChip( + val id: String = UUID.randomUUID().toString(), + val uriString: String, + val label: String, +) -private val SparkColor = Color(red = 0.62f, green = 0.30f, blue = 0.96f) -private val WarningOrange = Color(0xFFFF9500) - -private val SessionConfigOption.currentLabel: String - get() = choices.firstOrNull { it.value == value }?.label ?: value.ifBlank { label } - -private fun findModelOption(options: List): SessionConfigOption? = - options.firstOrNull { opt -> - val k = opt.key.lowercase() - val c = opt.category.lowercase() - c == "model" || k == "model" || k.contains("model") - } - -private fun findEffortOption(options: List): SessionConfigOption? = - options.firstOrNull { opt -> - val k = opt.key.lowercase() - val c = opt.category.lowercase() - c.contains("thought") || c.contains("effort") || c.contains("reason") || - k.contains("thought") || k.contains("effort") || k.contains("thinking") || k.contains("reason") - } - -private fun findPermissionOption(options: List): SessionConfigOption? = - options.firstOrNull { opt -> - val k = opt.key.lowercase() - val c = opt.category.lowercase() - c.contains("permission") || c.contains("approval") || c.contains("sandbox") || - k.contains("permission") || k.contains("approval") || k.contains("sandbox") || k.contains("ask") - } +private val SparkColor = Color(red = 0.70f, green = 0.62f, blue = 1.0f) +private val AlertOrange = Color(0xFFFF9500) +private val RecordingRed = Color(0xFFFF3B30) /** * 1:1 port of iOS `PromptBar` (`PromptBar.swift`). + * Unified single-capsule floating composer (`[ + | Multiline BasicTextField | AgentIcon ⌄ | Mic | 36dp Circular ↑/■ ]`) + * with composer-local zero-lag text editing, live speech dictation (`SpeechRecognizer`), + * and `ThreadSettingsSheet` (`会话设置`) modal integration. */ @Composable fun PromptBar( - text: String, - onTextChange: (String) -> Unit, - menu: ComposerMenu?, - onMenuChange: (ComposerMenu?) -> Unit, + conversationKey: String = "default", + externalDraftSeed: String = "", + externalSeedVersion: Int = 0, + onDraftEmptyChanged: ((Boolean) -> Unit)? = null, agentId: String, agent: CatalogAgent? = null, agents: List = emptyList(), - showAgentSelector: Boolean = false, - onSelectAgent: ((String) -> Unit)? = null, - onAddCustomModel: ((String) -> Unit)? = null, + allowCrossAgentSwitch: Boolean = false, modes: List, currentModeId: String, configOptions: List, + modelPrefs: ModelPreferencesStore, isStreaming: Boolean, + hasAlert: Boolean = false, enabled: Boolean = true, - onSend: () -> Unit, + placeholder: String = "发消息或提问…", + onSubmit: (String) -> Unit, onStop: () -> Unit, + onSelectAgentAndModel: (agentId: String, modelKey: String, modelValue: String) -> Unit, onSelectMode: (String) -> Unit, - onSelectOption: (String, String) -> Unit, + onSelectOption: (key: String, value: String) -> Unit, onOpenFileBrowser: (() -> Unit)? = null, - onFocusChange: (Boolean) -> Unit = {}, + onCompact: (() -> Unit)? = null, + onRefreshCatalog: (() -> Unit)? = null, + openSettingsTrigger: Int = 0, modifier: Modifier = Modifier, ) { val colors = VibexTheme.colors + val context = LocalContext.current val focusManager = LocalFocusManager.current - var plusPanel by remember { mutableStateOf(PlusPanel.Grid) } - var showCustomModelDialog by remember { mutableStateOf(false) } - var customModelDraft by remember { mutableStateOf("") } + val haptic = LocalHapticFeedback.current + val scope = rememberCoroutineScope() + + // Composer-local text buffer avoids round-tripping every keystroke through ViewModel StateFlow + var localText by remember(conversationKey) { mutableStateOf(externalDraftSeed) } + var lastAppliedSeedVersion by remember(conversationKey) { mutableIntStateOf(0) } + var attachedMedia by remember(conversationKey) { mutableStateOf>(emptyList()) } + var plusMenuExpanded by remember { mutableStateOf(false) } + var showThreadSettingsSheet by remember { mutableStateOf(false) } + + LaunchedEffect(externalDraftSeed, externalSeedVersion) { + if (externalSeedVersion > lastAppliedSeedVersion) { + lastAppliedSeedVersion = externalSeedVersion + localText = externalDraftSeed + onDraftEmptyChanged?.invoke(localText.isBlank() && attachedMedia.isEmpty()) + } + } - val modelOption = remember(configOptions) { findModelOption(configOptions) } - val effortOption = remember(configOptions) { findEffortOption(configOptions) } - val permissionOption = remember(configOptions) { findPermissionOption(configOptions) } + var lastSettingsTrigger by remember { mutableIntStateOf(openSettingsTrigger) } + LaunchedEffect(openSettingsTrigger) { + if (openSettingsTrigger != lastSettingsTrigger) { + lastSettingsTrigger = openSettingsTrigger + focusManager.clearFocus() + onRefreshCatalog?.invoke() + showThreadSettingsSheet = true + } + } - val agentLabel = remember(agent, agentId) { - agent?.displayName?.takeIf { it.isNotBlank() } - ?: agentDisplayName(agentId, "") + // Photo picker for up to 4 images + val photoPicker = rememberLauncherForActivityResult( + contract = ActivityResultContracts.PickMultipleVisualMedia(4), + ) { uris -> + if (uris.isNotEmpty()) { + val added = uris.mapIndexed { idx, uri -> + AttachedMediaChip( + uriString = uri.toString(), + label = "image-${attachedMedia.size + idx + 1}.jpg", + ) + } + attachedMedia = (attachedMedia + added).take(4) + onDraftEmptyChanged?.invoke(localText.isBlank() && attachedMedia.isEmpty()) + } } - val modelName = remember(modelOption, agent, agentId) { - modelOption?.currentLabel?.takeIf { it.isNotBlank() } - ?: "默认模型" + // Live Speech Dictation State (`SpeechRecognizer`) + var isRecording by remember { mutableStateOf(false) } + var dictationError by remember { mutableStateOf(null) } + var dictationPrefix by remember { mutableStateOf("") } + var speechRecognizer by remember { mutableStateOf(null) } + + fun showTempDictationError(msg: String) { + dictationError = msg + scope.launch { + delay(2_800L) + if (dictationError == msg) dictationError = null + } } - val effortAtMax = remember(effortOption) { - effortOption != null && - effortOption.choices.size > 1 && - effortOption.choices.last().value == effortOption.value + fun stopDictation() { + runCatching { + speechRecognizer?.stopListening() + speechRecognizer?.cancel() + speechRecognizer?.destroy() + } + speechRecognizer = null + isRecording = false } - val currentModeName = remember(modes, currentModeId) { - modes.firstOrNull { it.id == currentModeId }?.name - ?: modes.firstOrNull()?.name - ?: "默认" + fun startDictationNow() { + stopDictation() + if (!SpeechRecognizer.isRecognitionAvailable(context)) { + showTempDictationError("当前设备暂不支持实时语音转写") + return + } + val trimmedPrefix = localText.trim() + dictationPrefix = if (trimmedPrefix.isEmpty()) "" else "$localText " + dictationError = null + + val recognizer = runCatching { SpeechRecognizer.createSpeechRecognizer(context) }.getOrNull() + if (recognizer == null) { + showTempDictationError("无法初始化语音识别服务") + return + } + recognizer.setRecognitionListener( + object : RecognitionListener { + override fun onReadyForSpeech(params: Bundle?) { + isRecording = true + } + + override fun onBeginningOfSpeech() = Unit + override fun onRmsChanged(rmsdB: Float) = Unit + override fun onBufferReceived(buffer: ByteArray?) = Unit + override fun onEndOfSpeech() = Unit + + override fun onPartialResults(partialResults: Bundle?) { + val spoken = partialResults + ?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) + ?.firstOrNull() + ?.trim() + .orEmpty() + if (spoken.isNotEmpty()) { + localText = dictationPrefix + spoken + onDraftEmptyChanged?.invoke(false) + } + } + + override fun onResults(results: Bundle?) { + val spoken = results + ?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) + ?.firstOrNull() + ?.trim() + .orEmpty() + if (spoken.isNotEmpty()) { + localText = dictationPrefix + spoken + onDraftEmptyChanged?.invoke(false) + } + stopDictation() + } + + override fun onError(error: Int) { + val wasRecording = isRecording + stopDictation() + if (error != SpeechRecognizer.ERROR_CLIENT && + error != SpeechRecognizer.ERROR_NO_MATCH && + error != SpeechRecognizer.ERROR_SPEECH_TIMEOUT && + !wasRecording + ) { + showTempDictationError("语音转写暂不可用,请检查麦克风或语音服务") + } + } + + override fun onEvent(eventType: Int, params: Bundle?) = Unit + }, + ) + val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { + putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) + putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true) + putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault().toLanguageTag()) + } + runCatching { + speechRecognizer = recognizer + isRecording = true + recognizer.startListening(intent) + }.onFailure { + stopDictation() + showTempDictationError("无法启动麦克风录音") + } } - val currentPermissionLabel = remember(permissionOption, modes, currentModeId) { - if (permissionOption != null) return@remember permissionOption.currentLabel - val mode = modes.firstOrNull { it.id == currentModeId } ?: return@remember "默认" - val lower = "${mode.id} ${mode.name}".lowercase() - if (lower.contains("auto") || lower.contains("bypass") || lower.contains("yolo") || lower.contains("full")) { - mode.name + val micPermissionLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission(), + ) { granted -> + if (granted) { + startDictationNow() } else { - "默认" + showTempDictationError("请在系统设置中允许麦克风权限") } } - val isNonDefaultPermission = remember(permissionOption, currentModeId) { - if (permissionOption != null) { - val v = permissionOption.value.lowercase() - return@remember v.contains("auto") || v.contains("bypass") || v.contains("never") || v.contains("full") || v.contains("yolo") + DisposableEffect(Unit) { + onDispose { stopDictation() } + } + + val effortOption = remember(configOptions) { findSettingsEffortOption(configOptions) } + val effortAtMax = remember(effortOption) { + effortOption != null && + effortOption.choices.size > 1 && + effortOption.choices.last().value == effortOption.value + } + + val canSend = enabled && (localText.trim().isNotEmpty() || attachedMedia.isNotEmpty()) + val armed = isStreaming || canSend + val capsuleShape = RoundedCornerShape(26.dp) + + fun performSend() { + if (isRecording) stopDictation() + var composed = localText.trim() + if (attachedMedia.isNotEmpty()) { + val tags = attachedMedia.joinToString(" ") { "#${it.label}" } + val marker = "[图片附件 ×${attachedMedia.size} $tags]" + composed = if (composed.isEmpty()) marker else "$composed\n$marker" } - val m = currentModeId.lowercase() - m.contains("auto") || m.contains("bypass") || m.contains("yolo") || m.contains("full") + if (composed.isEmpty() || !enabled) return + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + localText = "" + attachedMedia = emptyList() + onDraftEmptyChanged?.invoke(true) + onSubmit(composed) } - val canSend = enabled && text.trim().isNotEmpty() - val dockShape = RoundedCornerShape(22.dp) + Column( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 14.dp) + .padding(bottom = 8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + AnimatedVisibility( + visible = dictationError != null, + enter = fadeIn(), + exit = fadeOut(), + ) { + dictationError?.let { msg -> + Text( + text = msg, + fontSize = 12.sp, + color = colors.textSecondary, + modifier = Modifier.padding(horizontal = 8.dp), + ) + } + } - Box(modifier = modifier.fillMaxWidth()) { Column( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - // Menus above dock (never overlap the input dock) - AnimatedVisibility( - visible = menu == ComposerMenu.Agent && showAgentSelector && agents.isNotEmpty(), - enter = expandVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeIn(), - exit = shrinkVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeOut(), - ) { - MenuList( - title = "选择 AI Agent", - choices = agents.map { a -> - SessionConfigChoice( - value = a.id, - label = agentDisplayName(a.id, a.displayName), - ) - }, - selected = agentId, - leading = { choice -> - val rowAgent = agents.find { it.id.equals(choice.value, ignoreCase = true) } - AgentAvatar( - agentId = choice.value, - size = 16.dp, - iconSvg = rowAgent?.iconSvg, - displayName = rowAgent?.displayName?.ifBlank { choice.label } ?: choice.label, + .shadow( + elevation = if (colors.isDark) 10.dp else 6.dp, + shape = capsuleShape, + ambientColor = Color.Black.copy(alpha = if (colors.isDark) 0.24f else 0.06f), + spotColor = Color.Black.copy(alpha = if (colors.isDark) 0.30f else 0.09f), + ) + .clip(capsuleShape) + .background(colors.card) + .then( + if (effortAtMax) { + Modifier.background( + Brush.radialGradient( + colors = listOf( + SparkColor.copy(alpha = 0.22f), + Color.Transparent, + ), + center = Offset(80f, 180f), + radius = 420f, + ), ) - }, - onSelect = { value -> - onSelectAgent?.invoke(value) - onMenuChange(null) + } else { + Modifier }, ) - } - - AnimatedVisibility( - visible = menu == ComposerMenu.Model && modelOption != null && (modelOption.choices.isNotEmpty() || onAddCustomModel != null), - enter = expandVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeIn(), - exit = shrinkVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeOut(), - ) { - if (modelOption != null) { - MenuList( - title = modelOption.label, - choices = modelOption.choices, - selected = modelOption.value, - leading = { choice -> - val rowAgent = agents.find { it.id.equals(choice.value, ignoreCase = true) } - val rowAgentId = rowAgent?.id - ?: choice.value.takeIf { bundledAgentAsset(it, false) != null } - ?: choice.label.takeIf { bundledAgentAsset(it, false) != null } - ?: agentId - val rowSvg = when { - rowAgent != null -> rowAgent.iconSvg - rowAgentId.equals(agentId, ignoreCase = true) -> agent?.iconSvg - else -> null - } - AgentAvatar( - agentId = rowAgentId, - size = 16.dp, - iconSvg = rowSvg, - displayName = rowAgent?.displayName?.ifBlank { choice.label } ?: choice.label, + .border( + width = 0.75.dp, + color = if (effortAtMax) SparkColor.copy(alpha = 0.36f) else colors.stroke, + shape = capsuleShape, + ) + .padding(start = 10.dp, end = 8.dp, top = 8.dp, bottom = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (attachedMedia.isNotEmpty()) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 4.dp, vertical = 2.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + attachedMedia.forEach { item -> + Box(modifier = Modifier.size(54.dp)) { + AsyncImage( + model = item.uriString, + contentDescription = item.label, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(54.dp) + .clip(RoundedCornerShape(12.dp)) + .border(0.6.dp, colors.stroke, RoundedCornerShape(12.dp)), ) - }, - onSelect = { value -> - onSelectOption(modelOption.key, value) - onMenuChange(null) - }, - onAddCustomModel = if (onAddCustomModel != null) { - { - onMenuChange(null) - customModelDraft = "" - showCustomModelDialog = true + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = 3.dp, y = (-3).dp) + .size(18.dp) + .clip(CircleShape) + .background(Color.Black.copy(alpha = 0.68f)) + .clickable { + attachedMedia = attachedMedia.filterNot { it.id == item.id } + onDraftEmptyChanged?.invoke(localText.isBlank() && attachedMedia.isEmpty()) + }, + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.Close, + contentDescription = "移除图片", + tint = Color.White, + modifier = Modifier.size(12.dp), + ) } - } else { - null - }, - ) - } - } - - AnimatedVisibility( - visible = menu == ComposerMenu.Effort && effortOption != null && effortOption.choices.size > 1, - enter = expandVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeIn(), - exit = shrinkVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeOut(), - ) { - if (effortOption != null) { - EffortMenu( - option = effortOption, - onSelect = { value -> - onSelectOption(effortOption.key, value) - onMenuChange(null) - }, - modifier = Modifier.width(280.dp), - ) + } + } } } - // Unified Dock + Expandable Bottom Drawer (1:1 with iOS PromptBar.dockSurface) - Box( - modifier = Modifier - .fillMaxWidth() - .shadow( - elevation = if (colors.isDark) 10.dp else 6.dp, - shape = dockShape, - ambientColor = Color.Black.copy(alpha = if (colors.isDark) 0.22f else 0.05f), - spotColor = Color.Black.copy(alpha = if (colors.isDark) 0.28f else 0.08f), - ) - .clip(dockShape) - .background(colors.card) - .then( - if (effortAtMax) { - Modifier.background( - Brush.radialGradient( - colors = listOf( - SparkColor.copy(alpha = 0.22f), - SparkColor.copy(alpha = 0.06f), - Color.Transparent, - ), - center = Offset(900f, 0f), - radius = 520f, - ), - ) - } else { - Modifier - }, - ) - .border( - width = 0.75.dp, - color = if (effortAtMax) SparkColor.copy(alpha = 0.38f) else colors.stroke, - shape = dockShape, - ), + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(6.dp), ) { - Column(modifier = Modifier.fillMaxWidth()) { - // Multiline Input + // 1. `+` Attachment & Quick Options Menu + Box { Box( modifier = Modifier - .fillMaxWidth() - .padding(start = 14.dp, end = 14.dp, top = 11.dp, bottom = 6.dp), + .size(width = 34.dp, height = 36.dp) + .clip(CircleShape) + .clickable { + focusManager.clearFocus() + plusMenuExpanded = true + }, + contentAlignment = Alignment.Center, ) { - if (text.isEmpty()) { - Text( - text = "发消息", - fontSize = 15.sp, - color = colors.textTertiary, + Icon( + imageVector = Icons.Rounded.Add, + contentDescription = "添加附件或选项", + tint = colors.textPrimary.copy(alpha = 0.82f), + modifier = Modifier.size(20.dp), + ) + if (hasAlert) { + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = (-3).dp, y = 4.dp) + .size(7.dp) + .clip(CircleShape) + .background(AlertOrange), ) } - BasicTextField( - value = text, - onValueChange = { next -> - if (menu != null) onMenuChange(null) - onTextChange(next) - }, - enabled = enabled, - maxLines = 5, - textStyle = TextStyle( - fontSize = 15.sp, - lineHeight = 20.sp, - color = colors.textPrimary, - ), - cursorBrush = SolidColor(colors.accent), - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 24.dp) - .onFocusChanged { focusState -> - onFocusChange(focusState.isFocused) - if (focusState.isFocused && menu != null) { - onMenuChange(null) - } - }, - ) } - // Bottom Tool Row - Row( - modifier = Modifier - .fillMaxWidth() - .padding(start = 10.dp, end = 10.dp, bottom = 9.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalAlignment = Alignment.CenterVertically, + VibexDropdownMenu( + expanded = plusMenuExpanded, + onDismissRequest = { plusMenuExpanded = false }, ) { - ToolButton( - open = menu == ComposerMenu.Plus, - hasAlert = isNonDefaultPermission, + VibexDropdownMenuItem( + text = "照片图库", + leadingIcon = Icons.Rounded.PhotoLibrary, onClick = { - focusManager.clearFocus() - plusPanel = PlusPanel.Grid - onMenuChange(if (menu == ComposerMenu.Plus) null else ComposerMenu.Plus) + plusMenuExpanded = false + photoPicker.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly), + ) }, ) - - Row( - modifier = Modifier - .weight(1f) - .horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(5.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - // 1. Optional AI Agent Pill (shown on New Conversation Landing) - if (showAgentSelector && agents.isNotEmpty()) { - PickPill( - label = agentLabel, - open = menu == ComposerMenu.Agent, - enabled = agents.size > 1, - leading = { - AgentAvatar( - agentId = agentId, - size = 14.dp, - iconSvg = agent?.iconSvg, - displayName = agentLabel, - ) - }, - onClick = { - focusManager.clearFocus() - onMenuChange(if (menu == ComposerMenu.Agent) null else ComposerMenu.Agent) - }, - ) - } - - // 2. Model Pill - PickPill( - label = modelName, - open = menu == ComposerMenu.Model, - enabled = (modelOption?.choices?.size ?: 0) >= 1 || onAddCustomModel != null, - leading = { - if (showAgentSelector) { - Icon( - imageVector = Icons.Rounded.AutoAwesome, - contentDescription = null, - tint = colors.textSecondary, - modifier = Modifier.size(12.dp), - ) - } else { - AgentAvatar( - agentId = agentId, - size = 14.dp, - iconSvg = agent?.iconSvg, - displayName = agent?.displayName.orEmpty(), - ) - } + if (onOpenFileBrowser != null) { + VibexDropdownMenuItem( + text = "浏览项目文件", + leadingIcon = Icons.Rounded.Folder, + onClick = { + plusMenuExpanded = false + onOpenFileBrowser() }, + ) + } + if (onCompact != null) { + VibexDropdownMenuItem( + text = "压缩上下文 (/compact)", + leadingIcon = Icons.Rounded.Compress, onClick = { - focusManager.clearFocus() - onMenuChange(if (menu == ComposerMenu.Model) null else ComposerMenu.Model) + plusMenuExpanded = false + onCompact() }, ) - - // 3. Effort Pill - if (effortOption != null) { - PickPill( - label = effortOption.currentLabel, - open = menu == ComposerMenu.Effort, - enabled = effortOption.choices.size > 1, - tint = if (effortAtMax) SparkColor else null, - leading = { - Icon( - imageVector = Icons.Rounded.AutoAwesome, - contentDescription = null, - tint = if (effortAtMax) SparkColor else colors.textSecondary, - modifier = Modifier.size(12.dp), - ) - }, - onClick = { - focusManager.clearFocus() - onMenuChange(if (menu == ComposerMenu.Effort) null else ComposerMenu.Effort) - }, - ) - } } - - SendButton( - ready = canSend, - busy = isStreaming, + VibexDropdownDivider() + VibexDropdownMenuItem( + text = "会话与模型设置", + leadingIcon = Icons.Rounded.Tune, onClick = { - onMenuChange(null) - if (isStreaming) onStop() else if (canSend) onSend() + plusMenuExpanded = false + onRefreshCatalog?.invoke() + showThreadSettingsSheet = true }, ) } - - // Integrated Plus Drawer inside the same rounded dock surface - AnimatedVisibility( - visible = menu == ComposerMenu.Plus, - enter = expandVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeIn(), - exit = shrinkVertically(animationSpec = spring(dampingRatio = 0.86f)) + fadeOut(), - ) { - Column(modifier = Modifier.fillMaxWidth()) { - HorizontalDivider(thickness = 0.6.dp, color = colors.stroke) - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 10.dp), - ) { - when (plusPanel) { - PlusPanel.Grid -> { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - PlusGridTile( - title = "文件", - subtitle = "浏览项目", - modifier = Modifier.weight(1f), - icon = { - Icon( - imageVector = Icons.Rounded.CreateNewFolder, - contentDescription = null, - tint = colors.textPrimary, - modifier = Modifier.size(20.dp), - ) - }, - onClick = { - onMenuChange(null) - onOpenFileBrowser?.invoke() - }, - ) - PlusGridTile( - title = "模型", - subtitle = modelName, - modifier = Modifier.weight(1f), - icon = { - AgentAvatar( - agentId = agentId, - size = 22.dp, - iconSvg = agent?.iconSvg, - displayName = agent?.displayName.orEmpty(), - ) - }, - onClick = { - if (modelOption != null && modelOption.choices.isNotEmpty()) { - plusPanel = PlusPanel.Model - } - }, - ) - PlusGridTile( - title = "模式", - subtitle = currentModeName, - modifier = Modifier.weight(1f), - icon = { BotModeGlyph(tint = colors.textPrimary) }, - onClick = { plusPanel = PlusPanel.Mode }, - ) - PlusGridTile( - title = "权限", - subtitle = currentPermissionLabel, - badge = isNonDefaultPermission, - modifier = Modifier.weight(1f), - icon = { - Icon( - imageVector = Icons.Rounded.VerifiedUser, - contentDescription = null, - tint = if (isNonDefaultPermission) WarningOrange else colors.textPrimary, - modifier = Modifier.size(20.dp), - ) - }, - onClick = { plusPanel = PlusPanel.Permission }, - ) - } - } - - PlusPanel.Agent -> { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - PlusSubpanelHeader(title = "选择 AI Agent") { plusPanel = PlusPanel.Grid } - DrawerChoiceList( - choices = agents.map { a -> - SessionConfigChoice(a.id, agentDisplayName(a.id, a.displayName)) - }, - selected = agentId, - onSelect = { id -> - onSelectAgent?.invoke(id) - onMenuChange(null) - }, - ) - } - } - - PlusPanel.Model -> { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - PlusSubpanelHeader(title = "选择模型") { plusPanel = PlusPanel.Grid } - if (modelOption != null && modelOption.choices.isNotEmpty()) { - DrawerChoiceList( - choices = modelOption.choices, - selected = modelOption.value, - leading = { choice -> - val rowAgent = agents.find { it.id.equals(choice.value, ignoreCase = true) } - val rowAgentId = rowAgent?.id - ?: choice.value.takeIf { bundledAgentAsset(it, false) != null } - ?: choice.label.takeIf { bundledAgentAsset(it, false) != null } - ?: agentId - val rowSvg = when { - rowAgent != null -> rowAgent.iconSvg - rowAgentId.equals(agentId, ignoreCase = true) -> agent?.iconSvg - else -> null - } - AgentAvatar( - agentId = rowAgentId, - size = 16.dp, - iconSvg = rowSvg, - displayName = rowAgent?.displayName?.ifBlank { choice.label } ?: choice.label, - ) - }, - onSelect = { v -> - onSelectOption(modelOption.key, v) - onMenuChange(null) - }, - onAddCustomModel = if (onAddCustomModel != null) { - { - onMenuChange(null) - customModelDraft = "" - showCustomModelDialog = true - } - } else { - null - }, - ) - } else { - PlusEmptyHint("当前 Agent 不支持切换模型") - } - } - } - - PlusPanel.Mode -> { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - PlusSubpanelHeader(title = "模式与推理") { plusPanel = PlusPanel.Grid } - if (modes.isNotEmpty()) { - DrawerChoiceList( - choices = modes.map { SessionConfigChoice(value = it.id, label = it.name) }, - selected = currentModeId.ifBlank { modes.first().id }, - onSelect = { id -> - onSelectMode(id) - onMenuChange(null) - }, - ) - } - if (effortOption != null && effortOption.choices.size > 1) { - EffortMenu( - option = effortOption, - onSelect = { v -> onSelectOption(effortOption.key, v) }, - modifier = Modifier.fillMaxWidth(), - ) - } - if (modes.isEmpty() && effortOption == null) { - PlusEmptyHint("当前会话无可用模式选项") - } - } - } - - PlusPanel.Permission -> { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - PlusSubpanelHeader(title = "权限设置") { plusPanel = PlusPanel.Grid } - when { - permissionOption != null && permissionOption.choices.isNotEmpty() -> { - DrawerChoiceList( - choices = permissionOption.choices, - selected = permissionOption.value, - onSelect = { v -> - onSelectOption(permissionOption.key, v) - onMenuChange(null) - }, - ) - } - modes.isNotEmpty() -> { - DrawerChoiceList( - choices = modes.map { SessionConfigChoice(value = it.id, label = it.name) }, - selected = currentModeId.ifBlank { modes.first().id }, - onSelect = { id -> - onSelectMode(id) - onMenuChange(null) - }, - ) - } - else -> PlusEmptyHint("当前会话使用默认工具确认权限") - } - } - } - } - } - } - } } - } - } - if (showCustomModelDialog) { - AlertDialog( - onDismissRequest = { showCustomModelDialog = false }, - title = { Text("自定义 / 中转模型") }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + + // 2. Multiline Text Input + Box( + modifier = Modifier + .weight(1f) + .heightIn(min = 36.dp) + .padding(vertical = 7.dp), + contentAlignment = Alignment.CenterStart, + ) { + if (localText.isEmpty()) { Text( - "输入桌面端中转服务或网关支持的模型 ID:", - fontSize = 13.sp, - color = colors.textSecondary, - ) - OutlinedTextField( - value = customModelDraft, - onValueChange = { customModelDraft = it }, - placeholder = { Text("例如 claude-opus-4-8 / deepseek-r1") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), + text = placeholder, + fontSize = 15.5.sp, + color = colors.textTertiary, + maxLines = 1, ) } - }, - confirmButton = { - TextButton( - onClick = { - val trimmed = customModelDraft.trim() - showCustomModelDialog = false - if (trimmed.isNotEmpty()) { - onAddCustomModel?.invoke(trimmed) - } + BasicTextField( + value = localText, + onValueChange = { next -> + localText = next + onDraftEmptyChanged?.invoke(next.isBlank() && attachedMedia.isEmpty()) }, - ) { - Text("使用该模型") - } - }, - dismissButton = { - TextButton(onClick = { showCustomModelDialog = false }) { - Text("取消") - } - }, - ) - } - } -} - -@Composable -private fun PlusGridTile( - title: String, - subtitle: String, - modifier: Modifier = Modifier, - badge: Boolean = false, - icon: @Composable () -> Unit, - onClick: () -> Unit, -) { - val colors = VibexTheme.colors - val tileShape = RoundedCornerShape(14.dp) - val boxShape = RoundedCornerShape(14.dp) - - Column( - modifier = modifier - .clip(tileShape) - .background(colors.bg.copy(alpha = 0.65f)) - .clickable(onClick = onClick) - .padding(vertical = 10.dp, horizontal = 4.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(5.dp), - ) { - Box( - modifier = Modifier - .size(46.dp) - .clip(boxShape) - .background(colors.bg), - contentAlignment = Alignment.Center, - ) { - icon() - if (badge) { - Box( - modifier = Modifier - .align(Alignment.TopEnd) - .offset(x = (-4).dp, y = 4.dp) - .size(8.dp) - .clip(CircleShape) - .background(WarningOrange), - ) - } - } - Text( - text = title, - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - color = colors.textPrimary, - maxLines = 1, - ) - Text( - text = subtitle, - fontSize = 10.sp, - color = colors.textSecondary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } -} - -/** - * 1:1 port of iOS `BotModeGlyph` (`PromptBar.swift`). - */ -@Composable -fun BotModeGlyph( - modifier: Modifier = Modifier, - tint: Color = VibexTheme.colors.textPrimary, -) { - Canvas(modifier = modifier.size(20.dp)) { - val w = size.width - val h = size.height - val stroke = 1.75.dp.toPx() - - // Antenna stem & tip - drawLine( - color = tint, - start = Offset(w * 0.5f, h * 0.14f), - end = Offset(w * 0.5f, h * 0.27f), - strokeWidth = stroke, - cap = StrokeCap.Round, - ) - drawCircle( - color = tint, - radius = w * 0.055f, - center = Offset(w * 0.5f, h * 0.11f), - ) - - // Side ears - drawLine( - color = tint, - start = Offset(w * 0.10f, h * 0.48f), - end = Offset(w * 0.18f, h * 0.48f), - strokeWidth = stroke, - cap = StrokeCap.Round, - ) - drawLine( - color = tint, - start = Offset(w * 0.82f, h * 0.48f), - end = Offset(w * 0.90f, h * 0.48f), - strokeWidth = stroke, - cap = StrokeCap.Round, - ) - - // Head rounded rect - drawRoundRect( - color = tint, - topLeft = Offset(w * 0.18f, h * 0.27f), - size = Size(w * 0.64f, h * 0.56f), - cornerRadius = CornerRadius(w * 0.18f, w * 0.18f), - style = Stroke(width = stroke), - ) - - // Eyes - drawCircle( - color = tint, - radius = w * 0.06f, - center = Offset(w * 0.37f, h * 0.51f), - ) - drawCircle( - color = tint, - radius = w * 0.06f, - center = Offset(w * 0.63f, h * 0.51f), - ) - - // Smile line - drawLine( - color = tint, - start = Offset(w * 0.39f, h * 0.67f), - end = Offset(w * 0.61f, h * 0.67f), - strokeWidth = stroke, - cap = StrokeCap.Round, - ) - } -} - -@Composable -private fun PlusSubpanelHeader( - title: String, - onBack: () -> Unit, -) { - val colors = VibexTheme.colors - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 4.dp, vertical = 2.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - modifier = Modifier - .clip(RoundedCornerShape(8.dp)) - .clickable(onClick = onBack) - .padding(horizontal = 4.dp, vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = Icons.Rounded.ChevronLeft, - contentDescription = null, - tint = colors.textSecondary, - modifier = Modifier.size(16.dp), - ) - Text( - text = "返回", - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = colors.textSecondary, - ) - } - Spacer(modifier = Modifier.weight(1f)) - Text( - text = title, - fontSize = 14.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, - ) - Spacer(modifier = Modifier.weight(1f)) - Spacer(modifier = Modifier.width(44.dp)) - } -} - -@Composable -private fun PlusEmptyHint(text: String) { - val colors = VibexTheme.colors - val shape = RoundedCornerShape(14.dp) - Box( - modifier = Modifier - .fillMaxWidth() - .clip(shape) - .background(colors.card) - .padding(vertical = 18.dp), - contentAlignment = Alignment.Center, - ) { - Text( - text = text, - fontSize = 13.sp, - color = colors.textSecondary, - ) - } -} - -@Composable -private fun ToolButton( - open: Boolean, - hasAlert: Boolean = false, - onClick: () -> Unit, -) { - val colors = VibexTheme.colors - val rotation by animateFloatAsState( - targetValue = if (open) 45f else 0f, - animationSpec = spring(dampingRatio = 0.8f), - label = "plusRotate", - ) - - Box( - modifier = Modifier - .size(30.dp) - .clip(CircleShape) - .background(colors.textPrimary.copy(alpha = if (open) 0.14f else 0.07f)) - .clickable(onClick = onClick), - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.Rounded.Add, - contentDescription = "更多选项", - tint = colors.textPrimary, - modifier = Modifier - .size(16.dp) - .rotate(rotation), - ) - if (hasAlert && !open) { - Box( - modifier = Modifier - .align(Alignment.TopEnd) - .size(7.dp) - .clip(CircleShape) - .background(WarningOrange), - ) - } - } -} - -@Composable -private fun PickPill( - label: String, - open: Boolean, - enabled: Boolean, - tint: Color? = null, - leading: @Composable () -> Unit, - onClick: () -> Unit, -) { - val colors = VibexTheme.colors - val rotation by animateFloatAsState( - targetValue = if (open) 180f else 0f, - animationSpec = spring(dampingRatio = 0.85f), - label = "pillChevron", - ) - - Row( - modifier = Modifier - .height(30.dp) - .clip(CircleShape) - .background( - when { - tint != null -> tint.copy(alpha = if (open) 0.20f else 0.12f) - else -> colors.textPrimary.copy(alpha = if (open) 0.14f else 0.07f) - }, - ) - .then( - if (tint != null) Modifier.border(0.6.dp, tint.copy(alpha = 0.35f), CircleShape) - else Modifier, - ) - .clickable(enabled = enabled, onClick = onClick) - .padding(horizontal = 8.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - leading() - Text( - text = label, - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - color = tint ?: colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.widthIn(max = 110.dp), - ) - if (enabled) { - Icon( - imageVector = Icons.Rounded.KeyboardArrowDown, - contentDescription = null, - tint = (tint ?: colors.textSecondary).copy(alpha = 0.85f), - modifier = Modifier - .size(13.dp) - .rotate(rotation), - ) - } - } -} - -@Composable -private fun SendButton( - ready: Boolean, - busy: Boolean, - onClick: () -> Unit, -) { - val colors = VibexTheme.colors - val active = ready || busy - Box( - modifier = Modifier - .size(30.dp) - .clip(CircleShape) - .background(if (active) colors.textPrimary else colors.textPrimary.copy(alpha = if (colors.isDark) 0.16f else 0.11f)) - .clickable(enabled = active, onClick = onClick), - contentAlignment = Alignment.Center, - ) { - SendGlyph(stop = busy, ready = ready) - } -} - -@Composable -private fun SendGlyph( - stop: Boolean, - ready: Boolean, -) { - val colors = VibexTheme.colors - val morph by animateFloatAsState( - targetValue = if (stop) 1f else 0f, - animationSpec = spring(dampingRatio = 0.78f, stiffness = Spring.StiffnessMediumLow), - label = "sendMorph", - ) - val fg = if (ready || stop) colors.bg else colors.textTertiary - - Canvas(modifier = Modifier.size(13.dp)) { - val w = size.width - val h = size.height - val cx = w / 2f - val cy = h / 2f - val m = morph.coerceIn(0f, 1f) - - if (m > 0.02f) { - val side = minOf(w, h) * (0.45f + 0.37f * m) - val corner = side * 0.24f - drawRoundRect( - color = fg.copy(alpha = m), - topLeft = Offset(cx - side / 2f, cy - side / 2f), - size = Size(side, side), - cornerRadius = CornerRadius(corner, corner), - ) - } - if (m < 0.98f) { - val k = 1f - m - val path = Path().apply { - moveTo(cx, cy + h * 0.40f * k) - lineTo(cx, cy - h * 0.38f * k) - moveTo(cx - w * 0.34f * k, cy - h * 0.04f * k) - lineTo(cx, cy - h * 0.38f * k) - lineTo(cx + w * 0.34f * k, cy - h * 0.04f * k) - } - drawPath( - path = path, - color = fg.copy(alpha = k), - style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round), - ) - } - } -} - -@Composable -private fun DrawerChoiceList( - choices: List, - selected: String, - leading: (@Composable (SessionConfigChoice) -> Unit)? = null, - onSelect: (String) -> Unit, - onAddCustomModel: (() -> Unit)? = null, -) { - val colors = VibexTheme.colors - val shape = RoundedCornerShape(14.dp) - Column( - modifier = Modifier - .fillMaxWidth() - .heightIn(max = 248.dp) - .clip(shape) - .background(colors.bg.copy(alpha = 0.65f)) - .verticalScroll(rememberScrollState()) - .padding(4.dp), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - choices.forEach { choice -> - val isSelected = choice.value == selected - val rowShape = RoundedCornerShape(10.dp) - Row( - modifier = Modifier - .fillMaxWidth() - .clip(rowShape) - .background(if (isSelected) colors.accent.copy(alpha = 0.12f) else Color.Transparent) - .clickable { onSelect(choice.value) } - .padding(horizontal = 12.dp, vertical = 9.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - leading?.invoke(choice) - Text( - text = choice.label, - fontSize = 14.sp, - fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal, - color = if (isSelected) colors.accent else colors.textPrimary, - modifier = Modifier.weight(1f), - ) - if (isSelected) { - Icon( - imageVector = Icons.Rounded.Check, - contentDescription = null, - tint = colors.accent, - modifier = Modifier.size(16.dp), + enabled = enabled, + maxLines = 5, + textStyle = TextStyle( + fontSize = 15.5.sp, + lineHeight = 21.sp, + color = colors.textPrimary, + ), + cursorBrush = SolidColor(colors.accent), + modifier = Modifier.fillMaxWidth(), ) } - } - } - if (onAddCustomModel != null) { - HorizontalDivider(thickness = 0.5.dp, color = colors.stroke, modifier = Modifier.padding(vertical = 2.dp)) - Row( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(10.dp)) - .clickable { onAddCustomModel() } - .padding(horizontal = 12.dp, vertical = 9.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = Icons.Rounded.Add, - contentDescription = null, - tint = colors.accent, - modifier = Modifier.size(16.dp), - ) - Text( - text = "自定义 / 中转模型…", - fontSize = 14.sp, - fontWeight = FontWeight.Medium, - color = colors.accent, - modifier = Modifier.weight(1f), - ) - } - } - } -} -@Composable -private fun MenuList( - title: String, - choices: List, - selected: String, - leading: (@Composable (SessionConfigChoice) -> Unit)? = null, - onSelect: (String) -> Unit, - onAddCustomModel: (() -> Unit)? = null, -) { - val colors = VibexTheme.colors - val shape = RoundedCornerShape(18.dp) - - Column( - modifier = Modifier - .width(260.dp) - .shadow(20.dp, shape, ambientColor = Color.Black.copy(alpha = 0.14f), spotColor = Color.Black.copy(alpha = 0.14f)) - .clip(shape) - .background(colors.card) - .border(0.6.dp, colors.textPrimary.copy(alpha = 0.08f), shape), - ) { - Text( - text = title, - fontSize = 12.sp, - fontWeight = FontWeight.Medium, - color = colors.textSecondary, - modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp), - ) - HorizontalDivider(thickness = 0.5.dp, color = colors.stroke) - Column( - modifier = Modifier - .fillMaxWidth() - .heightIn(max = 280.dp) - .verticalScroll(rememberScrollState()) - .padding(6.dp), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - choices.forEach { choice -> - val isSelected = choice.value == selected - val rowShape = RoundedCornerShape(11.dp) + // 3. Thread Settings Trigger (`AgentIcon ⌄`) Row( modifier = Modifier - .fillMaxWidth() - .clip(rowShape) - .background(if (isSelected) colors.textPrimary.copy(alpha = 0.07f) else Color.Transparent) - .clickable { onSelect(choice.value) } - .padding(horizontal = 10.dp, vertical = 9.dp), - horizontalArrangement = Arrangement.spacedBy(9.dp), + .height(36.dp) + .clip(CircleShape) + .clickable { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + focusManager.clearFocus() + onRefreshCatalog?.invoke() + showThreadSettingsSheet = true + } + .padding(horizontal = 7.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), ) { - leading?.invoke(choice) - Text( - text = choice.label, - fontSize = 14.sp, - fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal, - color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), + AgentAvatar( + agentId = agentId, + size = 17.dp, + iconSvg = agent?.iconSvg, + displayName = agent?.displayName.orEmpty(), + ) + Icon( + imageVector = Icons.Rounded.KeyboardArrowDown, + contentDescription = "会话设置", + tint = colors.textSecondary, + modifier = Modifier.size(13.dp), ) - if (isSelected) { - Icon( - imageVector = Icons.Rounded.Check, - contentDescription = null, - tint = colors.textPrimary, - modifier = Modifier.size(15.dp), - ) - } } - } - if (onAddCustomModel != null) { - HorizontalDivider(thickness = 0.5.dp, color = colors.stroke, modifier = Modifier.padding(vertical = 2.dp)) - Row( + + // 4. Live Speech Dictation Button (`Mic` / Pulsing Waveform) + val pulseTransition = rememberInfiniteTransition(label = "micPulse") + val micScale by pulseTransition.animateFloat( + initialValue = 1f, + targetValue = if (isRecording) 1.14f else 1f, + animationSpec = infiniteRepeatable( + animation = tween(durationMillis = 560), + repeatMode = RepeatMode.Reverse, + ), + label = "micScale", + ) + Box( modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(11.dp)) - .clickable { onAddCustomModel() } - .padding(horizontal = 10.dp, vertical = 9.dp), - horizontalArrangement = Arrangement.spacedBy(9.dp), - verticalAlignment = Alignment.CenterVertically, + .size(width = 32.dp, height = 36.dp) + .clip(CircleShape) + .clickable { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + if (isRecording) { + stopDictation() + } else { + val granted = ContextCompat.checkSelfPermission( + context, + Manifest.permission.RECORD_AUDIO, + ) == PackageManager.PERMISSION_GRANTED + if (granted) startDictationNow() + else micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO) + } + }, + contentAlignment = Alignment.Center, ) { Icon( - imageVector = Icons.Rounded.Add, - contentDescription = null, - tint = colors.accent, - modifier = Modifier.size(16.dp), - ) - Text( - text = "自定义 / 中转模型…", - fontSize = 13.5.sp, - fontWeight = FontWeight.Medium, - color = colors.accent, - modifier = Modifier.weight(1f), + imageVector = if (isRecording) Icons.Rounded.GraphicEq else Icons.Rounded.Mic, + contentDescription = if (isRecording) "停止语音输入" else "语音输入", + tint = if (isRecording) RecordingRed else colors.textPrimary.copy(alpha = 0.75f), + modifier = Modifier + .size(if (isRecording) 20.dp else 18.dp) + .scale(if (isRecording) micScale else 1f), ) } + + // 5. Circular Monochrome Send / Stop Button (`36dp`) + CircularSendStopButton( + armed = armed, + running = isStreaming, + onClick = { + if (isStreaming) onStop() else performSend() + }, + ) } } } -} - -@Composable -private fun EffortMenu( - option: SessionConfigOption, - onSelect: (String) -> Unit, - modifier: Modifier = Modifier, -) { - val colors = VibexTheme.colors - val choices = option.choices - val selectedIndex = remember(choices, option.value) { - choices.indexOfFirst { it.value == option.value }.coerceAtLeast(0) - } - var liveIndex by remember(selectedIndex) { mutableIntStateOf(selectedIndex) } - val safeLiveIndex = liveIndex.coerceIn(0, (choices.size - 1).coerceAtLeast(0)) - val current = choices.getOrNull(safeLiveIndex) - val atMax = choices.size > 1 && safeLiveIndex == choices.lastIndex - - val shape = RoundedCornerShape(22.dp) - - Column( - modifier = modifier - .shadow(20.dp, shape, ambientColor = Color.Black.copy(alpha = 0.14f), spotColor = Color.Black.copy(alpha = 0.14f)) - .clip(shape) - .background(colors.card) - .border(0.6.dp, colors.textPrimary.copy(alpha = 0.08f), shape) - .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(7.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = Icons.Rounded.AutoAwesome, - contentDescription = null, - tint = if (atMax) SparkColor else colors.textSecondary, - modifier = Modifier.size(14.dp), - ) - Text( - text = "推理强度", - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = colors.textSecondary, - ) - Spacer(modifier = Modifier.weight(1f)) - Text( - text = current?.label ?: option.currentLabel, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, - color = if (atMax) SparkColor else colors.textPrimary, - ) - } - EffortSlider( - steps = choices.size, - index = safeLiveIndex, - atMax = atMax, - onIndexChange = { next -> - liveIndex = next - }, - onCommit = { next -> - liveIndex = next - choices.getOrNull(next)?.let { choice -> - onSelect(choice.value) - } - }, + if (showThreadSettingsSheet) { + ThreadSettingsSheet( + agentId = agentId, + agent = agent, + agents = agents, + allowCrossAgentSwitch = allowCrossAgentSwitch, + modes = modes, + currentModeId = currentModeId, + configOptions = configOptions, + modelPrefs = modelPrefs, + onSelectAgentAndModel = onSelectAgentAndModel, + onSelectMode = onSelectMode, + onSelectOption = onSelectOption, + onRefreshCatalog = onRefreshCatalog, + onDismiss = { showThreadSettingsSheet = false }, ) } } @Composable -private fun EffortSlider( - steps: Int, - index: Int, - atMax: Boolean, - onIndexChange: (Int) -> Unit, - onCommit: (Int) -> Unit, +private fun CircularSendStopButton( + armed: Boolean, + running: Boolean, + onClick: () -> Unit, ) { val colors = VibexTheme.colors - var widthPx by remember { mutableIntStateOf(1) } - val trackHeight = 38.dp - val padPx = 19f - val count = maxOf(steps, 2) - val span = (widthPx.toFloat() - padPx * 2f).coerceAtLeast(1f) - val progress = index.toFloat() / (count - 1).toFloat() - val fillWidthPx = padPx + span * progress - - fun nearestStep(x: Float): Int { - val ratio = ((x - padPx) / span).coerceIn(0f, 1f) - return (ratio * (count - 1)).roundToInt().coerceIn(0, count - 1) - } + val morph by animateFloatAsState( + targetValue = if (running) 1f else 0f, + animationSpec = tween(durationMillis = 220), + label = "sendMorph", + ) + val bg = if (armed) colors.textPrimary else colors.textPrimary.copy(alpha = 0.08f) + val fg = if (armed) colors.bg else colors.textPrimary.copy(alpha = 0.36f) Box( modifier = Modifier - .fillMaxWidth() - .height(trackHeight) - .onSizeChanged { widthPx = it.width.coerceAtLeast(1) } + .size(36.dp) .clip(CircleShape) - .background(colors.textPrimary.copy(alpha = 0.07f)) - .pointerInput(count) { - detectTapGestures { offset -> - val next = nearestStep(offset.x) - onCommit(next) - } - } - .pointerInput(count) { - var lastIdx = index - detectHorizontalDragGestures( - onDragStart = { offset -> - lastIdx = nearestStep(offset.x) - onIndexChange(lastIdx) - }, - onHorizontalDrag = { change, _ -> - change.consume() - lastIdx = nearestStep(change.position.x) - onIndexChange(lastIdx) - }, - onDragEnd = { onCommit(lastIdx) }, - ) - }, + .background(bg) + .clickable(enabled = armed, onClick = onClick), + contentAlignment = Alignment.Center, ) { - Canvas(modifier = Modifier.fillMaxSize()) { - val h = size.height - val fillColor = if (atMax) SparkColor.copy(alpha = 0.24f) else colors.textPrimary.copy(alpha = 0.14f) - drawRoundRect( - color = fillColor, - topLeft = Offset.Zero, - size = Size((fillWidthPx + padPx).coerceAtMost(size.width), h), - cornerRadius = CornerRadius(h / 2f, h / 2f), + Canvas(modifier = Modifier.size(15.dp)) { + val scale = size.width / 24f + val arrow = arrayOf( + 12f to 4.5f, + 18.5f to 11f, + 14.25f to 11f, + 14.25f to 19.5f, + 9.75f to 19.5f, + 9.75f to 11f, + 5.5f to 11f, ) - - for (step in 0 until count) { - val x = padPx + span * (step.toFloat() / (count - 1).toFloat()) - val dotColor = if (step <= index) { - if (atMax) SparkColor else colors.textPrimary.copy(alpha = 0.55f) - } else { - colors.textPrimary.copy(alpha = 0.22f) + val square = arrayOf( + 12f to 6f, + 18f to 6f, + 18f to 12f, + 18f to 18f, + 6f to 18f, + 6f to 12f, + 6f to 6f, + ) + val path = Path().apply { + for (i in arrow.indices) { + val (ax, ay) = arrow[i] + val (bx, by) = square[i] + val px = (ax + (bx - ax) * morph) * scale + val py = (ay + (by - ay) * morph) * scale + if (i == 0) moveTo(px, py) else lineTo(px, py) } - drawCircle( - color = dotColor, - radius = 2.5.dp.toPx(), - center = Offset(x, h / 2f), - ) + close() } - - // Thumb - val thumbRadius = 13.dp.toPx() - drawCircle( - color = if (atMax) SparkColor else colors.textPrimary, - radius = thumbRadius, - center = Offset(fillWidthPx, h / 2f), - ) - drawCircle( - color = Color.White, - radius = 4.dp.toPx(), - center = Offset(fillWidthPx, h / 2f), + drawPath(path = path, color = fg) + drawPath( + path = path, + color = fg, + style = Stroke(width = 1.3f * scale, join = StrokeJoin.Round), ) } } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/QrScannerOverlay.kt b/app/src/main/java/dev/vibex/companion/app/ui/QrScannerOverlay.kt new file mode 100644 index 0000000..da69d00 --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/QrScannerOverlay.kt @@ -0,0 +1,250 @@ +package dev.vibex.companion.app.ui + +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.FlashlightOff +import androidx.compose.material.icons.rounded.FlashlightOn +import androidx.compose.material.icons.rounded.Keyboard +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import com.google.zxing.BarcodeFormat +import com.journeyapps.barcodescanner.DecoratedBarcodeView +import com.journeyapps.barcodescanner.DefaultDecoderFactory +import dev.vibex.companion.app.ui.theme.VibexTheme + +/** + * 1:1 port of the updated iOS squircle QRScannerView: + * Frosted card container + centered 248dp squircle live camera preview + caption + quick controls. + */ +@Composable +fun QrScannerOverlay( + onCode: (String) -> Unit, + onManualInput: () -> Unit, + onDismiss: () -> Unit, +) { + val colors = VibexTheme.colors + val lifecycleOwner = LocalLifecycleOwner.current + val haptic = LocalHapticFeedback.current + var torchOn by remember { mutableStateOf(false) } + var handled by remember { mutableStateOf(false) } + var barcodeViewRef by remember { mutableStateOf(null) } + + BackHandler(onBack = onDismiss) + + DisposableEffect(lifecycleOwner, barcodeViewRef) { + val view = barcodeViewRef + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> view?.resume() + Lifecycle.Event.ON_PAUSE -> view?.pause() + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { + view?.resume() + } + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + view?.pause() + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .background( + Brush.verticalGradient( + colors = if (colors.isDark) { + listOf(Color(0xFF101014), Color(0xFF18181E)) + } else { + listOf(Color(0xFFF2F2F7), Color(0xFFE5E6EC)) + }, + ), + ) + .statusBarsPadding() + .navigationBarsPadding(), + ) { + // Top Close Button + Box( + modifier = Modifier + .align(Alignment.TopStart) + .padding(16.dp) + .size(40.dp) + .clip(CircleShape) + .background(colors.card.copy(alpha = 0.9f)) + .border(0.75.dp, colors.stroke, CircleShape) + .clickable(onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.Close, + contentDescription = "关闭", + tint = colors.textPrimary, + modifier = Modifier.size(20.dp), + ) + } + + // Centered Frosted Card with Squircle Viewfinder + Column( + modifier = Modifier + .align(Alignment.Center) + .padding(horizontal = 16.dp) + .fillMaxWidth() + .shadow( + elevation = 16.dp, + shape = RoundedCornerShape(28.dp), + ambientColor = Color.Black.copy(alpha = 0.10f), + ) + .clip(RoundedCornerShape(28.dp)) + .background(colors.card.copy(alpha = if (colors.isDark) 0.88f else 0.92f)) + .border(0.75.dp, colors.stroke, RoundedCornerShape(28.dp)) + .padding(horizontal = 20.dp, vertical = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(22.dp), + ) { + val squircleShape = RoundedCornerShape(44.dp) + Box( + modifier = Modifier + .size(248.dp) + .shadow(14.dp, squircleShape, ambientColor = Color.Black.copy(alpha = 0.18f)) + .clip(squircleShape) + .background(Color.Black) + .border( + width = 1.8.dp, + color = colors.textPrimary.copy(alpha = 0.82f), + shape = squircleShape, + ), + ) { + AndroidView( + factory = { ctx -> + DecoratedBarcodeView(ctx).apply { + layoutParams = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ) + statusView.visibility = android.view.View.GONE + viewFinder.visibility = android.view.View.GONE + barcodeView.decoderFactory = DefaultDecoderFactory(listOf(BarcodeFormat.QR_CODE)) + decodeContinuous { result -> + val text = result?.text?.trim().orEmpty() + if (text.isNotEmpty() && !handled) { + handled = true + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + onCode(text) + } + } + barcodeViewRef = this + } + }, + update = { view -> + if (torchOn) view.setTorchOn() else view.setTorchOff() + }, + modifier = Modifier.fillMaxSize(), + ) + } + + Text( + text = "请扫描桌面端「远程连接」中的配对二维码", + fontSize = 15.5.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary.copy(alpha = 0.85f), + textAlign = TextAlign.Center, + modifier = Modifier.padding(horizontal = 12.dp), + ) + } + + // Bottom Controls (Manual Pairing + Torch) + Row( + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(bottom = 28.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Row( + modifier = Modifier + .height(48.dp) + .clip(CircleShape) + .background(colors.card.copy(alpha = 0.94f)) + .border(0.75.dp, colors.stroke, CircleShape) + .clickable(onClick = onManualInput) + .padding(horizontal = 20.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + imageVector = Icons.Rounded.Keyboard, + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(17.dp), + ) + Text( + text = "使用连接码配对", + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + ) + } + + Box( + modifier = Modifier + .size(48.dp) + .clip(CircleShape) + .background(if (torchOn) Color(0xFFFFD60A) else colors.card.copy(alpha = 0.94f)) + .border(0.75.dp, colors.stroke, CircleShape) + .clickable { torchOn = !torchOn }, + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = if (torchOn) Icons.Rounded.FlashlightOn else Icons.Rounded.FlashlightOff, + contentDescription = "手电筒", + tint = if (torchOn) Color.Black else colors.textPrimary, + modifier = Modifier.size(20.dp), + ) + } + } + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/SearchCard.kt b/app/src/main/java/dev/vibex/companion/app/ui/SearchCard.kt index aec786d..a633dc8 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/SearchCard.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/SearchCard.kt @@ -1,5 +1,10 @@ package dev.vibex.companion.app.ui +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkHorizontally import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -15,6 +20,8 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Cancel import androidx.compose.material.icons.rounded.ChevronRight @@ -24,20 +31,130 @@ import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme +/** + * 1:1 port of iOS `UnifiedSearchBar` (`SearchCard.swift`). + * Focus-aware 40dp search capsule with clear button and animated `取消` action. + */ +@Composable +fun UnifiedSearchBar( + query: String, + onQueryChange: (String) -> Unit, + placeholder: String, + modifier: Modifier = Modifier, +) { + val colors = VibexTheme.colors + val focusManager = LocalFocusManager.current + var isFocused by remember { mutableStateOf(false) } + val shape = RoundedCornerShape(12.dp) + val showCancel = isFocused || query.isNotEmpty() + + Row( + modifier = modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + modifier = Modifier + .weight(1f) + .height(40.dp) + .clip(shape) + .background(colors.card) + .border( + width = if (isFocused) 1.dp else 0.6.dp, + color = if (isFocused) colors.accent.copy(alpha = 0.45f) else colors.stroke, + shape = shape, + ) + .padding(horizontal = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + imageVector = Icons.Rounded.Search, + contentDescription = null, + tint = if (isFocused) colors.accent else colors.textSecondary, + modifier = Modifier.size(16.dp), + ) + Box(modifier = Modifier.weight(1f)) { + if (query.isEmpty()) { + Text( + text = placeholder, + fontSize = 14.sp, + color = colors.textTertiary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + BasicTextField( + value = query, + onValueChange = onQueryChange, + singleLine = true, + textStyle = TextStyle( + fontSize = 14.sp, + color = colors.textPrimary, + ), + cursorBrush = SolidColor(colors.accent), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { focusManager.clearFocus() }), + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { isFocused = it.isFocused }, + ) + } + if (query.isNotEmpty()) { + Icon( + imageVector = Icons.Rounded.Cancel, + contentDescription = "清除", + tint = colors.textTertiary, + modifier = Modifier + .size(16.dp) + .clickable { onQueryChange("") }, + ) + } + } + + AnimatedVisibility( + visible = showCancel, + enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(), + exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut(), + ) { + Text( + text = "取消", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.accent, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + onQueryChange("") + focusManager.clearFocus() + } + .padding(horizontal = 4.dp, vertical = 6.dp), + ) + } + } +} + /** * 1:1 port of iOS `ConnectedDeviceBar` (`SearchCard.swift`). */ diff --git a/app/src/main/java/dev/vibex/companion/app/ui/SettingsScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/SettingsScreen.kt index b6cddb4..fadc828 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/SettingsScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/SettingsScreen.kt @@ -1,6 +1,7 @@ package dev.vibex.companion.app.ui import android.os.Build +import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -13,6 +14,11 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width @@ -28,6 +34,7 @@ import androidx.compose.material.icons.outlined.QrCodeScanner import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.AutoAwesome import androidx.compose.material.icons.rounded.Cancel +import androidx.compose.material.icons.rounded.Cloud import androidx.compose.material.icons.rounded.Computer import androidx.compose.material.icons.rounded.Contrast import androidx.compose.material.icons.rounded.DeleteOutline @@ -35,9 +42,12 @@ import androidx.compose.material.icons.rounded.Dns import androidx.compose.material.icons.rounded.Extension import androidx.compose.material.icons.rounded.Groups import androidx.compose.material.icons.rounded.Info +import androidx.compose.material.icons.rounded.Language import androidx.compose.material.icons.rounded.LaptopMac import androidx.compose.material.icons.rounded.NotificationsActive +import androidx.compose.material.icons.rounded.NotificationsOff import androidx.compose.material.icons.rounded.Search +import androidx.compose.material.icons.rounded.Shield import androidx.compose.material.icons.rounded.Verified import androidx.compose.material3.AlertDialog import androidx.compose.material3.HorizontalDivider @@ -48,6 +58,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf @@ -62,6 +73,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign @@ -73,6 +85,7 @@ import dev.vibex.companion.ExtensionCatalogItem import dev.vibex.companion.SubagentRoleItem import dev.vibex.companion.agentDisplayName import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.R import dev.vibex.companion.app.SettingsSection import dev.vibex.companion.app.UiState import dev.vibex.companion.app.data.CollapseDisplay @@ -81,9 +94,12 @@ import dev.vibex.companion.app.data.MessageStreamDisplay import dev.vibex.companion.app.data.ThinkingDisplay import dev.vibex.companion.app.data.VibeXAccountRepository import dev.vibex.companion.app.monitor.CompanionMonitorService +import dev.vibex.companion.app.ui.theme.AppLanguage import dev.vibex.companion.app.ui.theme.Appearance import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.app.ui.theme.l +import dev.vibex.companion.app.update.AppUpdateManager @Composable fun SettingsScreen( @@ -97,13 +113,13 @@ fun SettingsScreen( ) { when (section) { null -> SettingsIndex(state, model, onOpen) - SettingsSection.Profile -> SettingsPage("个人资料", onBack) { ProfileSettings(state) } - SettingsSection.Account -> SettingsPage("VibeX 账号", onBack) { AccountSettings(state, model, onOpen) } - SettingsSection.Connection -> SettingsPage("已配对的电脑", onBack) { ConnectionSettings(state, model, onScan, onManualPair) } - SettingsSection.Extensions -> SettingsPage("技能与扩展", onBack) { ExtensionsSettings(state, model) } - SettingsSection.Font -> SettingsPage("字体", onBack) { FontSettings(state, model) } - SettingsSection.Notification -> SettingsPage("通知", onBack) { NotificationSettings(state, model) } - SettingsSection.About -> SettingsPage("关于 VibeX", onBack) { AboutSettings(state) } + SettingsSection.Profile -> SettingsPage(l("个人资料", "Profile"), onBack) { ProfileSettings(state) } + SettingsSection.Account -> SettingsPage(l("Dimo 账号", "Dimo Account"), onBack) { AccountSettings(state, model, onOpen) } + SettingsSection.Connection -> SettingsPage(l("已配对的电脑", "Paired Computers"), onBack) { ConnectionSettings(state, model, onScan, onManualPair) } + SettingsSection.Extensions -> SettingsPage(l("技能与扩展", "Skills & Extensions"), onBack) { ExtensionsSettings(state, model) } + SettingsSection.Font -> SettingsPage(l("字体", "Font"), onBack) { FontSettings(state, model) } + SettingsSection.Notification -> SettingsPage(l("通知", "Notifications"), onBack) { NotificationSettings(state, model) } + SettingsSection.About -> SettingsPage(l("关于 Dimo", "About Dimo"), onBack) { AboutSettings(state) } } } @@ -116,22 +132,31 @@ private fun SettingsIndex( val colors = VibexTheme.colors val selected = state.profiles.find { it.hostId == state.selectedHostId } ?: state.profiles.firstOrNull() val isOnline = state.connection == ConnectionState.Online - val versionStr = state.hostVersion.takeIf { it.isNotBlank() }?.let { "v$it" } ?: "v0.4.5" LazyColumn( Modifier.fillMaxSize().background(colors.bg), - contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), + contentPadding = PaddingValues( + start = 16.dp, + end = 16.dp, + top = 12.dp, + bottom = BOTTOM_DOCK_CLEARANCE + 16.dp, + ), verticalArrangement = Arrangement.spacedBy(14.dp), ) { item { - Text( - "设置", - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - color = colors.textPrimary, - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), - ) + Box( + Modifier + .fillMaxWidth() + .padding(vertical = 4.dp), + contentAlignment = Alignment.Center, + ) { + Text( + l("设置", "Settings"), + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + } } // 1. VibeX Account Card (Single top Personal Center) @@ -150,7 +175,7 @@ private fun SettingsIndex( Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { Text( - if (state.accountSignedIn && accountUser != null) accountUser.resolvedDisplayName else "VibeX 账号", + if (state.accountSignedIn && accountUser != null) accountUser.resolvedDisplayName else l("Dimo 账号", "Dimo Account"), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary, @@ -170,17 +195,22 @@ private fun SettingsIndex( ) } else { Text( - "未登录", - fontSize = 12.sp, - color = colors.textTertiary, + l("去登录", "Sign In"), + fontSize = 11.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.accent, + modifier = Modifier + .clip(CircleShape) + .background(colors.accentDim) + .padding(horizontal = 8.dp, vertical = 2.dp), ) } } Text( if (state.accountSignedIn && accountUser != null && accountUser.email.isNotBlank()) { - "${accountUser.email} · 个人中心与云端同步" + "${accountUser.email} · ${l("个人中心与云端同步", "Profile & Cloud Sync")}" } else { - "登录以跨端同步电脑、查看订阅与模型额度" + l("跨端同步电脑与模型额度", "Sync desktops & model credits") }, fontSize = 12.5.sp, color = colors.textSecondary, @@ -207,17 +237,17 @@ private fun SettingsIndex( .substringBefore(":") .ifBlank { "127.0.0.1" } if (isCloudActive) { - "VibeX 云服务 · Beta" + l("Dimo 云中继 · Beta", "Dimo Cloud Relay · Beta") } else { - "局域网直连 · $hostAddr" + "${l("局域网直连", "Direct LAN")} · $hostAddr" } } else { - "扫码或输入连接码" + l("扫码或输入连接码", "Scan QR or enter pairing code") } IosSettingsRow( icon = Icons.Rounded.Computer, tint = Color(0xFF007AFF), - title = "已配对的电脑", + title = l("已配对的电脑", "Paired Computers"), subtitle = hostSub, trailing = { val badgeColor = when (state.connection) { @@ -227,10 +257,10 @@ private fun SettingsIndex( else -> colors.textTertiary } val badgeText = when { - selected == null -> "未连接" + selected == null -> l("未连接", "Offline") state.connection == ConnectionState.Online -> { val rtt = state.realtimeRttMs?.let { " · ${it}ms" }.orEmpty() - "已连接$rtt" + "${l("已连接", "Connected")}$rtt" } else -> connectionLabel(state.connection) } @@ -255,14 +285,14 @@ private fun SettingsIndex( IosSettingsRow( icon = Icons.Rounded.AutoAwesome, tint = Color(0xFFAF52DE), - title = "技能与扩展", - subtitle = "技能 · MCP · 插件", + title = l("技能与扩展", "Skills & Extensions"), + subtitle = l("技能 · MCP · 插件", "Skills · MCP · Plugins"), onClick = { onOpen(SettingsSection.Extensions) }, ) } } - // 3. Theme, Font, Notifications Card (1:1 with iOS screenshot) + // 3. Theme, Language, Font, Notifications Card item { IosSettingsCard { // Inline Theme Segmented Row @@ -275,7 +305,7 @@ private fun SettingsIndex( ) { ColoredIconBadge(Icons.Rounded.Contrast, Color(0xFF5856D6)) Text( - "主题", + l("主题", "Theme"), fontSize = 15.5.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary, @@ -289,9 +319,9 @@ private fun SettingsIndex( horizontalArrangement = Arrangement.spacedBy(2.dp), ) { listOf( - Appearance.System to "跟随系统", - Appearance.Light to "浅色", - Appearance.Dark to "深色", + Appearance.System to l("自动", "Auto"), + Appearance.Light to l("浅色", "Light"), + Appearance.Dark to l("深色", "Dark"), ).forEach { (mode, label) -> val active = state.appearance == mode Text( @@ -313,6 +343,53 @@ private fun SettingsIndex( } } HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) + // Inline Language Segmented Row + Row( + Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + ColoredIconBadge(Icons.Rounded.Language, Color(0xFF007AFF)) + Text( + l("语言", "Language"), + fontSize = 15.5.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + Row( + Modifier + .clip(RoundedCornerShape(9.dp)) + .background(colors.segmentedTrack) + .padding(3.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), + ) { + listOf( + AppLanguage.ZhHans to "简体中文", + AppLanguage.En to "English", + ).forEach { (lang, label) -> + val active = state.language == lang + Text( + label, + fontSize = 12.5.sp, + fontWeight = if (active) FontWeight.SemiBold else FontWeight.Medium, + color = if (active) colors.textPrimary else colors.textSecondary, + modifier = Modifier + .then( + if (active) Modifier.shadow(2.dp, RoundedCornerShape(7.dp), ambientColor = Color.Black.copy(0.08f)) + else Modifier, + ) + .clip(RoundedCornerShape(7.dp)) + .background(if (active) colors.segmentedThumb else Color.Transparent) + .clickable { model.setLanguage(lang) } + .padding(horizontal = 10.dp, vertical = 5.dp), + ) + } + } + } + HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) // Font Row Row( Modifier @@ -332,10 +409,10 @@ private fun SettingsIndex( Text("AA", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFFFF9500)) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text("字体", fontSize = 15.5.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) - Text("字号大小与字体样式", fontSize = 12.sp, color = colors.textSecondary) + Text(l("字体", "Font"), fontSize = 15.5.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) + Text(l("字号大小与字体样式", "Text size & style"), fontSize = 12.sp, color = colors.textSecondary) } - Text("系统默认 · 标准", fontSize = 13.sp, color = colors.textSecondary) + Text(l("系统默认 · 标准", "System · Standard"), fontSize = 13.sp, color = colors.textSecondary) Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = colors.textTertiary, modifier = Modifier.size(18.dp)) } HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) @@ -343,11 +420,11 @@ private fun SettingsIndex( IosSettingsRow( icon = Icons.Rounded.NotificationsActive, tint = Color(0xFFFF3B30), - title = "通知", - subtitle = "任务完成、审批与协作消息提醒", + title = l("通知", "Notifications"), + subtitle = l("任务完成、审批与协作消息提醒", "Task, approval & collaboration alerts"), trailing = { Text( - if (state.monitor) "持续监控已开启" else "系统通知已开启", + if (state.monitor) l("持续监控已开启", "Monitor On") else l("系统通知已开启", "System On"), fontSize = 13.sp, color = colors.textSecondary, ) @@ -357,40 +434,47 @@ private fun SettingsIndex( } } - // 4. About & Version Card (1:1 with iOS screenshot) + // 4. Cache & About Card (1:1 with iOS) item { + val context = LocalContext.current + val updateManager = remember(context) { AppUpdateManager.getInstance(context) } + val updateState by updateManager.state.collectAsState() + var cacheBytes by remember { mutableStateOf(computeAndroidCacheBytes(context)) } + var cacheCleared by remember { mutableStateOf(false) } IosSettingsCard { + IosSettingsRow( + icon = Icons.Rounded.DeleteOutline, + tint = Color(0xFFFF9500), + title = l("清理缓存", "Clear Cache"), + trailing = { + Text( + text = if (cacheCleared) l("已清理", "Cleared") else formatCacheSize(cacheBytes), + fontSize = 13.sp, + color = if (cacheCleared) Color(0xFF34C759) else colors.textSecondary, + ) + }, + onClick = { + clearAndroidCache(context) + cacheBytes = computeAndroidCacheBytes(context) + cacheCleared = true + }, + ) + HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) IosSettingsRow( icon = Icons.Rounded.Info, tint = Color(0xFF30B0C7), - title = "关于 VibeX", + title = l("关于 Dimo", "About Dimo"), trailing = { - Text("本地优先 AI 研发平台", fontSize = 13.sp, color = colors.textSecondary) + Text("v${updateState.currentVersionName}", fontSize = 13.sp, color = colors.textSecondary) }, onClick = { onOpen(SettingsSection.About) }, ) HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) - Row( - Modifier - .fillMaxWidth() - .padding(horizontal = 14.dp, vertical = 13.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - ColoredIconBadge(Icons.Rounded.Verified, Color(0xFF34C759)) - Text( - "当前版本", - fontSize = 15.5.sp, - fontWeight = FontWeight.Medium, - color = colors.textPrimary, - modifier = Modifier.weight(1f), - ) - Text( - "$versionStr (协议 v${state.hostProtocol.ifBlank { "1.0" }})", - fontSize = 13.sp, - color = colors.textSecondary, - ) - } + SettingsVersionUpdateRow( + state = updateState, + protocolVersion = state.hostProtocol, + onClick = { updateManager.openUpdateDialog() }, + ) } } item { Spacer(Modifier.height(12.dp)) } @@ -517,7 +601,8 @@ private fun LazyListScope.ProfileSettings(state: UiState) { val colors = VibexTheme.colors var userName by rememberSaveable { mutableStateOf("LTF") } var userHandle by rememberSaveable { mutableStateOf("@ltf") } - var userRole by rememberSaveable { mutableStateOf("VibeX Creator") } + var userRole by rememberSaveable { mutableStateOf("Dimo Creator") } + val displayedUserRole = if (userRole == "VibeX Creator") "Dimo Creator" else userRole var userBio by rememberSaveable { mutableStateOf("本地优先 AI 协同工作流与多智能体架构") } var avatarColorIdx by rememberSaveable { mutableIntStateOf(0) } val palette = listOf( @@ -539,7 +624,7 @@ private fun LazyListScope.ProfileSettings(state: UiState) { ) { BotAvatarBadge(color = palette[avatarColorIdx % palette.size], size = 72.dp) Text(userName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary) - Text("$userHandle · $userRole", fontSize = 13.sp, color = colors.textSecondary) + Text("$userHandle · $displayedUserRole", fontSize = 13.sp, color = colors.textSecondary) Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(top = 6.dp)) { palette.forEachIndexed { idx, swatch -> Box( @@ -563,7 +648,7 @@ private fun LazyListScope.ProfileSettings(state: UiState) { HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 16.dp)) ProfileFieldRow("标识 (Handle)", userHandle) { userHandle = it } HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 16.dp)) - ProfileFieldRow("头衔 / 角色", userRole) { userRole = it } + ProfileFieldRow("头衔 / 角色", displayedUserRole) { userRole = it } HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 16.dp)) ProfileFieldRow("个人简介", userBio) { userBio = it } } @@ -602,7 +687,7 @@ private fun LazyListScope.ConnectionSettings( var detailProfile by remember { mutableStateOf(null) } Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { - GroupLabel("连接偏好") + GroupLabel(l("连接偏好", "Connection Preferences")) IosSettingsCard { Row( Modifier @@ -611,8 +696,8 @@ private fun LazyListScope.ConnectionSettings( verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text("自动连接已配对电脑", fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) - Text("打开应用或断开后自动重连已配对电脑", fontSize = 12.sp, color = colors.textSecondary) + Text(l("自动连接已配对电脑", "Auto-Connect Paired Computers"), fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) + Text(l("打开应用或断开后自动重连已配对电脑", "Automatically reconnect when opening or resuming"), fontSize = 12.sp, color = colors.textSecondary) } Switch( checked = state.autoConnect, @@ -621,6 +706,72 @@ private fun LazyListScope.ConnectionSettings( } } + GroupLabel(l("自建云节点(可选)", "Custom Cloud Node (Optional)")) + IosSettingsCard { + var nodeDraft by rememberSaveable(state.customRelayOrigin) { mutableStateOf(state.customRelayOrigin) } + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + ColoredIconBadge(Icons.Rounded.Cloud, Color(0xFF007AFF)) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(l("自建节点地址", "Custom Node URL"), fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) + Text( + l("填写后,扫码时将询问使用官方云服务或自建节点", "When set, scanning QR will ask between official cloud and your node"), + fontSize = 12.sp, + color = colors.textSecondary, + ) + } + } + Box( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(colors.bg) + .border(0.6.dp, colors.hairline, RoundedCornerShape(10.dp)) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + if (nodeDraft.isEmpty()) { + Text("https://relay.example.com", fontSize = 13.5.sp, fontFamily = PlexMono, color = colors.textTertiary) + } + BasicTextField( + value = nodeDraft, + onValueChange = { nodeDraft = it }, + singleLine = true, + textStyle = TextStyle(fontSize = 13.5.sp, fontFamily = PlexMono, color = colors.textPrimary), + cursorBrush = SolidColor(colors.accent), + modifier = Modifier.fillMaxWidth(), + ) + } + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.End, + ) { + if (state.customRelayOrigin.isNotBlank() || nodeDraft.isNotBlank()) { + TextButton( + onClick = { + nodeDraft = "" + model.setCustomRelayOrigin("") + }, + ) { + Text(l("清除", "Clear"), color = colors.danger, fontSize = 13.sp) + } + } + TextButton( + onClick = { model.setCustomRelayOrigin(nodeDraft) }, + ) { + Text(l("保存节点", "Save Node"), color = colors.accent, fontWeight = FontWeight.SemiBold, fontSize = 13.sp) + } + } + } + } + GroupLabel("新增连接") IosSettingsCard { Row( @@ -689,11 +840,11 @@ private fun LazyListScope.ConnectionSettings( .substringBefore(":") .ifBlank { "127.0.0.1" } val displayName = if (isCloudOrigin) { - "VibeX 桌面端" - } else if (profile.name.startsWith("VibeX (")) { - profile.name + "Dimo 桌面端" + } else if (profile.name.startsWith("VibeX (") || profile.name.startsWith("Dimo (")) { + profile.name.replaceFirst("VibeX (", "Dimo (") } else { - "VibeX ($hostAddr)" + "Dimo ($hostAddr)" } Row( Modifier @@ -1204,8 +1355,8 @@ private fun LazyListScope.NotificationSettings(state: UiState, model: CompanionM ) { ColoredIconBadge(Icons.Rounded.NotificationsActive, Color(0xFFFF3B30)) Column(Modifier.weight(1f).padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text("后台持续监控通知", fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) - Text("保持与桌面端长连接并推送审批与完成提醒", fontSize = 12.sp, color = colors.textSecondary) + Text(l("后台持续监控通知", "Background Monitor Notifications"), fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) + Text(l("保持与桌面端长连接并推送审批与完成提醒", "Keep connection alive & push approval/completion alerts"), fontSize = 12.sp, color = colors.textSecondary) } Switch( checked = state.monitor, @@ -1215,37 +1366,107 @@ private fun LazyListScope.NotificationSettings(state: UiState, model: CompanionM }, ) } + HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ColoredIconBadge(Icons.Rounded.NotificationsOff, Color(0xFF5856D6)) + Column(Modifier.weight(1f).padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(l("前台静默", "Mute Foreground Alerts"), fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) + Text(l("正在 App 内查看时,不重复弹系统横幅通知", "Suppress duplicate system banners while app is in foreground"), fontSize = 12.sp, color = colors.textSecondary) + } + Switch( + checked = state.muteForegroundNotifications, + onCheckedChange = { model.setMuteForegroundNotifications(it) }, + ) + } + HorizontalDivider(color = colors.hairline, modifier = Modifier.padding(start = 56.dp)) + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + ColoredIconBadge(Icons.Rounded.Shield, Color(0xFFFF9500)) + Column(Modifier.weight(1f).padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(l("高危审批保护", "High-Risk Approval Guard"), fontSize = 15.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary) + Text(l("遇到删除/强推/永久授权操作时弹出二次确认", "Require secondary confirmation for destructive or permanent approvals"), fontSize = 12.sp, color = colors.textSecondary) + } + Switch( + checked = state.confirmHighRiskApproval, + onCheckedChange = { model.setConfirmHighRiskApproval(it) }, + ) + } } } } private fun LazyListScope.AboutSettings(state: UiState) { item { + val context = LocalContext.current + val updateManager = remember(context) { AppUpdateManager.getInstance(context) } + val updateState by updateManager.state.collectAsState() val colors = VibexTheme.colors IosSettingsCard { Column( Modifier.fillMaxWidth().padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), ) { - BrandMark(56.dp) - Text("VibeX Companion", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary) + Image( + painter = painterResource(R.drawable.dimo_app_icon), + contentDescription = "Dimo", + modifier = Modifier + .size(68.dp) + .clip(RoundedCornerShape(16.dp)) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)), + ) + Text("Dimo", fontSize = 19.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary) Text( - "v${state.hostVersion.ifBlank { "0.4.5" }} (协议 v${state.hostProtocol.ifBlank { "1.0" }})", + "客户端 v${updateState.currentVersionName} (#${updateState.currentVersionCode})", fontSize = 13.sp, + fontFamily = PlexMono, color = colors.textSecondary, ) Text( - "本地优先 AI 协同工作流与多智能体研发平台移动伴侣端", + "Dimo 桌面端伴侣客户端", fontSize = 12.5.sp, color = colors.textTertiary, textAlign = TextAlign.Center, ) + Spacer(Modifier.height(4.dp)) + AboutUpdateActionButton( + state = updateState, + onClick = { updateManager.openUpdateDialog() }, + ) } } } } +private fun computeAndroidCacheBytes(context: android.content.Context): Long { + fun dirSize(dir: java.io.File?): Long { + if (dir == null || !dir.exists()) return 0L + return dir.walkTopDown().filter { it.isFile }.sumOf { it.length() } + } + return dirSize(context.cacheDir) + dirSize(context.externalCacheDir) +} + +private fun clearAndroidCache(context: android.content.Context) { + fun clearDir(dir: java.io.File?) { + dir?.listFiles()?.forEach { it.deleteRecursively() } + } + clearDir(context.cacheDir) + clearDir(context.externalCacheDir) +} + +private fun formatCacheSize(bytes: Long): String { + if (bytes <= 0L) return "0 KB" + val kb = bytes / 1024.0 + if (kb < 1024.0) return String.format(java.util.Locale.US, "%.0f KB", kb) + val mb = kb / 1024.0 + return String.format(java.util.Locale.US, "%.1f MB", mb) +} + @Composable private fun SettingChoice(title: String, options: List>, current: T, onSelect: (T) -> Unit) { val colors = VibexTheme.colors @@ -1331,25 +1552,23 @@ private fun LazyListScope.AccountSettings( ) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text( - user.resolvedDisplayName, - fontSize = 16.sp, - fontWeight = FontWeight.Bold, - color = colors.textPrimary, - ) - val isActive = overview.hasActiveCreditsOrTier - Text( - if (isActive) "已激活" else "免费版", - fontSize = 11.sp, - fontWeight = FontWeight.SemiBold, - color = if (isActive) colors.accent else colors.textSecondary, - modifier = Modifier - .clip(CircleShape) - .background(if (isActive) colors.accent.copy(alpha = 0.14f) else colors.segmentedTrack) - .padding(horizontal = 7.dp, vertical = 2.dp), - ) - } + Text( + user.resolvedDisplayName, + fontSize = AccountTokens.title, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + val isActive = overview.hasActiveCreditsOrTier + Text( + overview.planDisplayName, + fontSize = 11.5.sp, + fontWeight = FontWeight.SemiBold, + color = if (isActive) colors.accent else colors.textSecondary, + modifier = Modifier + .clip(CircleShape) + .background(if (isActive) colors.accent.copy(alpha = 0.14f) else colors.segmentedTrack) + .padding(horizontal = 8.dp, vertical = 3.dp), + ) if (user.email.isNotBlank()) { Text(user.email, fontSize = 12.5.sp, color = colors.textSecondary) } @@ -1362,8 +1581,18 @@ private fun LazyListScope.AccountSettings( ) } } - TextButton(onClick = { model.refreshAccount() }) { - Text("刷新", fontSize = 12.5.sp, color = colors.accent) + Column(horizontalAlignment = Alignment.End) { + AccountPrimaryButton( + text = l("升级", "Upgrade"), + description = l("升级或充值", "Upgrade or top up"), + onClick = { model.openAccountSitePath("/account/plan") }, + ) + TextButton( + onClick = { model.refreshAccount() }, + modifier = Modifier.heightIn(min = AccountTokens.minTouch), + ) { + Text(l("刷新", "Refresh"), fontSize = AccountTokens.caption, color = colors.accent, maxLines = 1, softWrap = false) + } } } } @@ -1375,7 +1604,7 @@ private fun LazyListScope.AccountSettings( ) { ColoredIconBadge(Icons.Rounded.Verified, Color(0xFF007AFF)) Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { - Text("登录 VibeX 账号", fontSize = 15.5.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary) + Text(l("登录 Dimo 账号", "Sign in to Dimo"), fontSize = 15.5.sp, fontWeight = FontWeight.Bold, color = colors.textPrimary) Text( "跨设备自动同步已配对电脑、查看订阅计划与模型路由额度", fontSize = 12.sp, @@ -1413,171 +1642,197 @@ private fun LazyListScope.AccountSettings( } } - // 2. Subscription & Credits Usage + // 2. Balance card if (state.accountSignedIn && overview != null) { - item { GroupLabel("订阅与额度") } + item { GroupLabel(l("订阅与额度", "Plan & credits")) } item { val colors = VibexTheme.colors - IosSettingsCard { + val empty = overview.balanceMicro <= 0L && overview.activeTotalMicro <= 0L + AccountCard { Column( - Modifier.fillMaxWidth().padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), + Modifier.fillMaxWidth().padding(AccountTokens.cardPadding), + verticalArrangement = Arrangement.spacedBy(AccountTokens.gap), ) { - Row( - Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - overview.planDisplayName, - fontSize = 15.5.sp, - fontWeight = FontWeight.Bold, - color = colors.textPrimary, - ) - val activeCount = overview.activeGrants.size - Text( - if (activeCount > 0) "${activeCount} 个额度包生效中" else "支持 Claude / OpenAI / Gemini 等多模型路由与云中继", - fontSize = 12.sp, - color = colors.textSecondary, - ) - } + Text(overview.planDisplayName, fontSize = AccountTokens.title, fontWeight = FontWeight.Bold, color = colors.textPrimary) + Text( + l("支持 Claude / OpenAI / Gemini 等多模型路由与云中继", "Multi-model routing (Claude / OpenAI / Gemini) and cloud relay"), + fontSize = AccountTokens.caption, + color = colors.textSecondary, + ) + HorizontalDivider(color = colors.hairline) + Text(l("可用模型路由余额", "Available routing balance"), fontSize = AccountTokens.caption, color = colors.textSecondary) + Text( + "$${VibeXAccountRepository.formatCredits(overview.balanceMicro)}", + fontSize = AccountTokens.display, + fontFamily = PlexMono, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + if (overview.activeTotalMicro > 0L) { Text( - "充值 / 订阅", - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, - color = colors.accent, - modifier = Modifier - .clip(RoundedCornerShape(8.dp)) - .background(colors.accent.copy(alpha = 0.12f)) - .clickable { model.openAccountSitePath("/account/plan") } - .padding(horizontal = 10.dp, vertical = 6.dp), + l( + "总额度 $${VibeXAccountRepository.formatCredits(overview.activeTotalMicro)} · 剩余 ${(overview.remainingRatio * 100).toInt()}% · ${overview.activeGrants.size} 个额度包生效中", + "Total $${VibeXAccountRepository.formatCredits(overview.activeTotalMicro)} · ${(overview.remainingRatio * 100).toInt()}% left · ${overview.activeGrants.size} active packs", + ), + fontSize = AccountTokens.caption, + color = colors.textSecondary, + ) + } else if (empty) { + Text( + l("余额为 0。充值或订阅后即可使用云端多模型路由与云中继。", "Balance is 0. Top up or subscribe to use cloud model routing and relay."), + fontSize = AccountTokens.caption, + color = colors.textSecondary, ) } - HorizontalDivider(color = colors.hairline) - Row( - Modifier.fillMaxWidth(), - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text("可用模型路由余额", fontSize = 12.sp, color = colors.textSecondary) - Text( - "$${VibeXAccountRepository.formatCredits(overview.balanceMicro)}", - fontSize = 22.sp, - fontFamily = PlexMono, - fontWeight = FontWeight.Bold, - color = colors.textPrimary, - ) - } - if (overview.activeTotalMicro > 0L) { - Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - "总额度 $${VibeXAccountRepository.formatCredits(overview.activeTotalMicro)}", - fontSize = 11.5.sp, - fontFamily = PlexMono, - color = colors.textTertiary, - ) - Text( - "剩余 ${(overview.remainingRatio * 100).toInt()}%", - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, - color = colors.accent, - ) - } - } - } + AccountPrimaryButton( + text = l("去充值", "Top up"), + description = l("打开充值与订阅页面", "Open top-up and plans page"), + modifier = Modifier.fillMaxWidth(), + onClick = { model.openAccountSitePath("/account/plan") }, + ) } } } - // 3. 30-Day Usage - item { GroupLabel("近 30 天模型路由用量") } + // 3. Usage card with mini bar chart + item { GroupLabel(l("模型路由用量", "Routing usage")) } item { val colors = VibexTheme.colors val rows = overview.usage30d.byModel val spent30d = rows.sumOf { it.costMicro } val reqs30d = rows.sumOf { it.requests } val tokens30d = rows.sumOf { it.tokens } - IosSettingsCard { + AccountCard { Column( - Modifier.fillMaxWidth().padding(16.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + Modifier.fillMaxWidth().padding(AccountTokens.cardPadding), + verticalArrangement = Arrangement.spacedBy(AccountTokens.gap), ) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - AccountMetricChip(Modifier.weight(1f), "30天消耗", "$${VibeXAccountRepository.formatCredits(spent30d)}") - AccountMetricChip(Modifier.weight(1f), "请求次数", reqs30d.toString()) - AccountMetricChip(Modifier.weight(1f), "总 Token", VibeXAccountRepository.formatCompact(tokens30d)) - } - if (rows.isNotEmpty()) { - HorizontalDivider(color = colors.hairline) - rows.take(6).forEach { row -> + if (rows.isEmpty()) { + Text( + l("近 30 天暂无模型路由调用记录", "No routing calls in the last 30 days"), + fontSize = AccountTokens.caption, + color = colors.textSecondary, + ) + } else { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(AccountTokens.gapSmall)) { + AccountMetricChip(Modifier.weight(1f), l("30天消耗", "30d spend"), "$${VibeXAccountRepository.formatCredits(spent30d)}") + AccountMetricChip(Modifier.weight(1f), l("请求次数", "Requests"), reqs30d.toString()) + AccountMetricChip(Modifier.weight(1f), l("总 Token", "Tokens"), VibeXAccountRepository.formatCompact(tokens30d)) + } + val top = rows.sortedByDescending { it.costMicro }.take(6) + val maxCost = top.maxOf { it.costMicro }.coerceAtLeast(1L) + val summary = top.joinToString(";") { + (overview.usage30d.modelNames[it.modelId] ?: it.modelId) + " " + "$" + VibeXAccountRepository.formatCredits(it.costMicro) + } + Text(l("近 30 天各模型消耗占比", "30-day spend by model"), fontSize = AccountTokens.caption, color = colors.textSecondary) + Row( + Modifier + .fillMaxWidth() + .height(64.dp) + .semantics { contentDescription = summary }, + horizontalArrangement = Arrangement.spacedBy(AccountTokens.gapSmall), + verticalAlignment = Alignment.Bottom, + ) { + top.forEach { row -> + val frac = (row.costMicro.toFloat() / maxCost.toFloat()).coerceIn(0.06f, 1f) + Box( + Modifier + .weight(1f) + .fillMaxHeight(frac) + .clip(RoundedCornerShape(AccountTokens.radiusSmall)) + .background(colors.accent), + ) + } + } + top.forEach { row -> val modelLabel = overview.usage30d.modelNames[row.modelId] ?: row.modelId Row( Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.Top, + horizontalArrangement = Arrangement.spacedBy(AccountTokens.gapSmall), ) { Text( modelLabel, - fontSize = 12.5.sp, + fontSize = AccountTokens.body, fontWeight = FontWeight.Medium, color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) Text( - "${row.requests} 次 · $${VibeXAccountRepository.formatCredits(row.costMicro)}", - fontSize = 12.sp, + "${row.requests} " + l("次", "req") + " · $" + VibeXAccountRepository.formatCredits(row.costMicro), + fontSize = AccountTokens.caption, fontFamily = PlexMono, color = colors.textSecondary, ) } } - } else { - Text("近 30 天暂无模型路由调用记录", fontSize = 12.sp, color = colors.textTertiary) } } } } } - // 4. Cloud Synced Hosts (Summary + Sync Trigger, full management in ConnectionSettings) + // 4. Device sync card if (state.accountSignedIn) { - item { GroupLabel("电脑跨端云同步") } + item { GroupLabel(l("电脑跨端云同步", "Desktop sync")) } item { val colors = VibexTheme.colors val syncedCount = maxOf(state.accountDesktops.size, state.accountSavedHosts.size) - IosSettingsCard { - Column(Modifier.fillMaxWidth()) { - IosSettingsRow( - icon = Icons.Rounded.Computer, - tint = Color(0xFF007AFF), - title = "管理已配对与云端同步的电脑", - subtitle = if (syncedCount > 0) { - "账号下已关联 $syncedCount 台电脑,支持局域网与云服务自动切换" - } else { - "在桌面端登录同一账号或扫码配对后自动跨设备同步" - }, - onClick = { onOpen(SettingsSection.Connection) }, - ) - HorizontalDivider(color = colors.hairline) + val online = state.connection == ConnectionState.Online + val origin = state.activeOrigin.orEmpty().lowercase() + val isLan = origin.contains("://192.168.") || origin.contains("://10.") || + Regex("://172\\.(1[6-9]|2\\d|3[01])\\.").containsMatchIn(origin) || + origin.contains(".local") || origin.contains("://localhost") || origin.contains("://127.") + val route = when { + !online -> l("离线", "Offline") + isLan -> l("在线 · 局域网", "Online · LAN") + else -> l("在线 · 云中继", "Online · Cloud relay") + } + val lastSync = state.profiles.mapNotNull { it.lastSyncAt }.maxOrNull() + val lastSyncText = if (lastSync != null) { + l("最近同步 ", "Last sync ") + java.text.SimpleDateFormat("MM-dd HH:mm", java.util.Locale.getDefault()).format(java.util.Date(lastSync)) + } else { + l("尚未同步", "Not synced yet") + } + AccountCard { + Column( + Modifier.fillMaxWidth().padding(AccountTokens.cardPadding), + verticalArrangement = Arrangement.spacedBy(AccountTokens.gap), + ) { Row( Modifier .fillMaxWidth() - .clickable(enabled = !state.accountSyncingHosts) { model.syncAccountHosts(forcePush = true) } - .padding(horizontal = 16.dp, vertical = 12.dp), + .heightIn(min = AccountTokens.minTouch) + .clickable(onClickLabel = l("管理已配对电脑", "Manage paired computers")) { onOpen(SettingsSection.Connection) }, verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.Center, + horizontalArrangement = Arrangement.spacedBy(AccountTokens.gap), ) { - Text( - if (state.accountSyncingHosts) "正在同步已配对电脑…" else "立即同步账号下的电脑", - fontSize = 13.5.sp, - fontWeight = FontWeight.SemiBold, - color = colors.accent, - ) + ColoredIconBadge(Icons.Rounded.Computer, if (online) colors.accent else colors.textTertiary) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + if (syncedCount > 0) l("已关联 $syncedCount 台电脑", "$syncedCount computer(s) linked") else l("尚未关联电脑", "No computers linked"), + fontSize = AccountTokens.title, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + ) + Text(route + " · " + lastSyncText, fontSize = AccountTokens.caption, color = colors.textSecondary) + if (syncedCount == 0) { + Text( + l("在桌面端登录同一账号或扫码配对后自动同步", "Sign in on desktop or scan to pair; sync is automatic"), + fontSize = AccountTokens.caption, + color = colors.textSecondary, + ) + } + } + Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = colors.textTertiary, modifier = Modifier.size(18.dp)) } + AccountSecondaryButton( + text = if (state.accountSyncingHosts) l("正在同步…", "Syncing…") else l("立即同步", "Sync now"), + description = l("立即同步账号下的电脑", "Sync computers on this account now"), + enabled = !state.accountSyncingHosts, + modifier = Modifier.fillMaxWidth(), + onClick = { model.syncAccountHosts(forcePush = true) }, + ) } } } @@ -1633,7 +1888,7 @@ private fun LazyListScope.AccountSettings( contentAlignment = Alignment.Center, ) { Text( - if (state.accountSigningOut) "正在退出…" else "退出 VibeX 账号", + if (state.accountSigningOut) "正在退出…" else l("退出 Dimo 账号", "Sign out of Dimo"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.danger, @@ -1669,3 +1924,53 @@ private fun GroupLabel(text: String) { modifier = Modifier.padding(start = 6.dp, top = 4.dp), ) } + +private object AccountTokens { + val radius = 16.dp + val radiusSmall = 8.dp + val cardPadding = 16.dp + val gap = 12.dp + val gapSmall = 8.dp + val minTouch = 48.dp + val display = 28.sp + val title = 16.sp + val body = 14.sp + val caption = 12.5.sp +} + +@Composable +private fun AccountCard(content: @Composable () -> Unit) = IosSettingsCard(content) + +@Composable +private fun AccountPrimaryButton(text: String, description: String, modifier: Modifier = Modifier, onClick: () -> Unit) { + val colors = VibexTheme.colors + Box( + modifier + .heightIn(min = AccountTokens.minTouch) + .clip(RoundedCornerShape(AccountTokens.radius - 4.dp)) + .background(colors.accent) + .clickable(role = Role.Button, onClickLabel = description, onClick = onClick) + .padding(horizontal = AccountTokens.cardPadding, vertical = 10.dp) + .semantics { contentDescription = description }, + contentAlignment = Alignment.Center, + ) { + Text(text, fontSize = AccountTokens.body, fontWeight = FontWeight.SemiBold, color = Color.White, maxLines = 1, softWrap = false) + } +} + +@Composable +private fun AccountSecondaryButton(text: String, description: String, enabled: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { + val colors = VibexTheme.colors + Box( + modifier + .heightIn(min = AccountTokens.minTouch) + .clip(RoundedCornerShape(AccountTokens.radius - 4.dp)) + .background(colors.accent.copy(alpha = if (enabled) 0.12f else 0.06f)) + .clickable(enabled = enabled, role = Role.Button, onClickLabel = description, onClick = onClick) + .padding(horizontal = AccountTokens.cardPadding, vertical = 10.dp) + .semantics { contentDescription = description }, + contentAlignment = Alignment.Center, + ) { + Text(text, fontSize = AccountTokens.body, fontWeight = FontWeight.SemiBold, color = colors.accent, maxLines = 1, softWrap = false) + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/SplashScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/SplashScreen.kt index 194d7dd..533b02f 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/SplashScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/SplashScreen.kt @@ -60,6 +60,6 @@ fun SplashScreen() { horizontalAlignment = Alignment.CenterHorizontally, ) { BrandMark(88.dp) - Text("VibeX", style = MaterialTheme.typography.headlineLarge, color = MaterialTheme.colorScheme.onBackground) + Text("Dimo", style = MaterialTheme.typography.headlineLarge, color = MaterialTheme.colorScheme.onBackground) } } diff --git a/app/src/main/java/dev/vibex/companion/app/ui/StatusScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/StatusScreen.kt index aaa90a7..6e2ccbc 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/StatusScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/StatusScreen.kt @@ -3,11 +3,8 @@ package dev.vibex.companion.app.ui import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.detectVerticalDragGestures -import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row @@ -16,7 +13,6 @@ import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width @@ -24,57 +20,30 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBackIos -import androidx.compose.material.icons.automirrored.rounded.List -import androidx.compose.material.icons.rounded.Add -import androidx.compose.material.icons.rounded.AddCircle -import androidx.compose.material.icons.rounded.Archive -import androidx.compose.material.icons.rounded.BarChart import androidx.compose.material.icons.rounded.Bolt -import androidx.compose.material.icons.rounded.CallSplit import androidx.compose.material.icons.rounded.ChatBubble import androidx.compose.material.icons.rounded.Check -import androidx.compose.material.icons.rounded.Close -import androidx.compose.material.icons.rounded.ContentCopy import androidx.compose.material.icons.rounded.CreditCard -import androidx.compose.material.icons.rounded.Delete -import androidx.compose.material.icons.rounded.Edit import androidx.compose.material.icons.rounded.ExpandMore import androidx.compose.material.icons.rounded.Folder -import androidx.compose.material.icons.rounded.Groups import androidx.compose.material.icons.rounded.Info -import androidx.compose.material.icons.rounded.Inventory2 -import androidx.compose.material.icons.rounded.Layers import androidx.compose.material.icons.rounded.Memory -import androidx.compose.material.icons.rounded.MoreHoriz import androidx.compose.material.icons.rounded.Paid import androidx.compose.material.icons.rounded.Public -import androidx.compose.material.icons.rounded.PushPin import androidx.compose.material.icons.rounded.Refresh -import androidx.compose.material.icons.rounded.SwapHoriz -import androidx.compose.material.icons.rounded.Tag -import androidx.compose.material.icons.rounded.TrendingUp -import androidx.compose.material.icons.rounded.Unarchive -import androidx.compose.material.icons.rounded.ViewColumn +import androidx.compose.material.icons.rounded.SwapVert import androidx.compose.material.icons.rounded.Warning -import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon -import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf @@ -88,702 +57,29 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.hapticfeedback.HapticFeedbackType -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalHapticFeedback -import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import dev.vibex.companion.CatalogProject -import dev.vibex.companion.KanbanSessionStatus -import dev.vibex.companion.KanbanSessionSummary -import dev.vibex.companion.KanbanSortField import dev.vibex.companion.PlanUsageResponse import dev.vibex.companion.PlanUsageWindow import dev.vibex.companion.ProjectUsageStatistics -import dev.vibex.companion.UsageDashboardTab import dev.vibex.companion.UsageDateRange import dev.vibex.companion.agentDisplayName import dev.vibex.companion.app.CompanionModel import dev.vibex.companion.app.UiState import dev.vibex.companion.app.ui.theme.PlexMono import dev.vibex.companion.app.ui.theme.VibexTheme -import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import java.time.Instant import java.util.Locale -private enum class KanbanViewMode(val id: String, val title: String, val icon: ImageVector) { - Columns("columns", "四栏看板", Icons.Rounded.ViewColumn), - Usage("usage", "计量统计", Icons.Rounded.BarChart), +private enum class BoardDashboardMode(val id: String, val label: String) { + Overview("overview", "用量概览"), + PlanQuota("quota", "套餐额度"), } -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun StatusScreen(state: UiState, model: CompanionModel) { - val colors = VibexTheme.colors - val scope = rememberCoroutineScope() - val clipboard = LocalClipboardManager.current - - var viewMode by rememberSaveable { mutableStateOf(KanbanViewMode.Columns.id) } - var selectedProjectId by rememberSaveable { mutableStateOf(state.selectedProjectId) } - var sessions by remember { mutableStateOf>(emptyList()) } - var isLoading by remember { mutableStateOf(true) } - var errorMessage by remember { mutableStateOf(null) } - var noticeMessage by remember { mutableStateOf(null) } - var usageRefreshTrigger by remember { mutableIntStateOf(0) } - - // Modals & Alerts - var showProjectMenu by remember { mutableStateOf(false) } - var showCreateSheet by remember { mutableStateOf(false) } - var createInitialStatus by remember { mutableStateOf(KanbanSessionStatus.Todo) } - var renamingSession by remember { mutableStateOf(null) } - var renameDraft by remember { mutableStateOf("") } - var deletingSession by remember { mutableStateOf(null) } - - val projects = state.catalog?.projects.orEmpty() - val workspaces = state.catalog?.workspaces.orEmpty() - val selectedProject = projects.find { it.id.equals(selectedProjectId, ignoreCase = true) } - - suspend fun reload() { - runCatching { - val loaded = model.fetchKanbanSessions(selectedProjectId) - sessions = loaded - errorMessage = null - isLoading = false - }.onFailure { err -> - if (sessions.isEmpty() && state.conversations.isNotEmpty()) { - sessions = state.conversations.map { conv -> - val branch = workspaces.find { it.id == conv.workspaceId }?.branch - KanbanSessionSummary.fromConversationSummary(conv, branch) - } - } - errorMessage = err.message ?: "加载看板失败" - isLoading = false - } - } - - LaunchedEffect(state.selectedHostId, selectedProjectId, state.connection) { - isLoading = sessions.isEmpty() - while (true) { - reload() - delay(if (errorMessage == null) 15_000L else 4_000L) - } - } - - val activeSessions = remember(sessions) { sessions.filter { !it.isArchived } } - - fun openSession(session: KanbanSessionSummary) { - if (session.completesWhenViewed) { - sessions = sessions.map { if (it.id == session.id) it.copy(status = KanbanSessionStatus.Done) else it } - scope.launch { - runCatching { model.mutateKanbanSessionViewed(session.id) } - } - } - model.openConversation(session.id) - } - - fun performStatusChange(session: KanbanSessionSummary, newStatus: KanbanSessionStatus) { - val oldStatus = session.status - sessions = sessions.map { if (it.id == session.id) it.copy(status = newStatus) else it } - scope.launch { - runCatching { - model.mutateKanbanSessionStatus(session.id, newStatus) - reload() - }.onFailure { err -> - sessions = sessions.map { if (it.id == session.id) it.copy(status = oldStatus) else it } - noticeMessage = err.message ?: "状态修改失败" - } - } - } - - fun performTogglePin(session: KanbanSessionSummary) { - val nextPinned = !session.isPinned - sessions = sessions.map { - if (it.id == session.id) it.copy(pinnedAt = if (nextPinned) Instant.now().toString() else null) else it - } - scope.launch { - runCatching { - model.mutateKanbanSessionPinned(session.id, nextPinned) - reload() - }.onFailure { err -> - noticeMessage = err.message ?: "置顶操作失败" - reload() - } - } - } - - fun performRename(session: KanbanSessionSummary, newName: String) { - val trimmed = newName.trim() - sessions = sessions.map { - if (it.id == session.id) it.copy(name = trimmed.ifEmpty { null }) else it - } - scope.launch { - runCatching { - model.mutateKanbanSessionRename(session.id, trimmed.ifEmpty { null }) - reload() - }.onFailure { err -> - noticeMessage = err.message ?: "重命名失败" - reload() - } - } - } - - fun performDelete(session: KanbanSessionSummary) { - sessions = sessions.filterNot { it.id == session.id } - scope.launch { - runCatching { - model.mutateKanbanSessionDelete(session.id) - reload() - }.onFailure { err -> - noticeMessage = err.message ?: "删除失败" - reload() - } - } - } - - fun performFork(session: KanbanSessionSummary) { - scope.launch { - runCatching { - val forkedId = model.mutateKanbanSessionFork(session.id) - noticeMessage = "已分叉会话" - reload() - if (!forkedId.isNullOrBlank()) { - model.openConversation(forkedId) - } - }.onFailure { err -> - noticeMessage = "分叉失败:${err.message ?: "未知错误"}" - } - } - } - - Column(Modifier.fillMaxSize().background(colors.bg)) { - // Row 1 (Single Navigation Bar): - // - Columns mode: Project Selector Menu | 看板 | 计量统计 Icon + 新建会话 Icon - // - Usage mode: ← 看板 | 计量统计 | ↻ 刷新 - Box( - Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 10.dp), - ) { - if (viewMode == KanbanViewMode.Columns.id) { - Box(Modifier.align(Alignment.CenterStart)) { - Row( - Modifier - .clip(CircleShape) - .background(colors.bgElevated) - .clickable { showProjectMenu = true } - .padding(horizontal = 10.dp, vertical = 5.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - Icon( - imageVector = if (selectedProject == null) Icons.Rounded.Layers else Icons.Rounded.Folder, - contentDescription = null, - tint = colors.accent, - modifier = Modifier.size(14.dp), - ) - Text( - selectedProject?.name ?: "全部项目", - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.widthIn(max = 115.dp), - ) - Icon(Icons.Rounded.ExpandMore, null, tint = colors.textSecondary, modifier = Modifier.size(14.dp)) - } - DropdownMenu(expanded = showProjectMenu, onDismissRequest = { showProjectMenu = false }) { - DropdownMenuItem( - text = { Text("全部项目") }, - leadingIcon = { Icon(Icons.Rounded.Layers, null, modifier = Modifier.size(16.dp)) }, - trailingIcon = if (selectedProjectId == null) { - { Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(16.dp)) } - } else null, - onClick = { - showProjectMenu = false - selectedProjectId = null - }, - ) - HorizontalDivider() - projects.forEach { proj -> - val isSelected = selectedProjectId?.equals(proj.id, ignoreCase = true) == true - DropdownMenuItem( - text = { Text(proj.name) }, - leadingIcon = { Icon(Icons.Rounded.Folder, null, modifier = Modifier.size(16.dp)) }, - trailingIcon = if (isSelected) { - { Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(16.dp)) } - } else null, - onClick = { - showProjectMenu = false - selectedProjectId = proj.id - model.selectProjectInPlace(proj.id) - }, - ) - } - } - } - - Text( - "看板", - fontSize = 17.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, - modifier = Modifier.align(Alignment.Center), - ) - - Row( - Modifier.align(Alignment.CenterEnd), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Icon( - Icons.Rounded.BarChart, - contentDescription = "计量统计", - tint = colors.accent, - modifier = Modifier - .size(21.dp) - .clickable { viewMode = KanbanViewMode.Usage.id }, - ) - Icon( - Icons.Rounded.AddCircle, - contentDescription = "新建会话", - tint = colors.accent, - modifier = Modifier - .size(24.dp) - .clickable { - createInitialStatus = KanbanSessionStatus.Todo - model.loadCatalogSilent() - showCreateSheet = true - }, - ) - } - } else { - Row( - Modifier - .align(Alignment.CenterStart) - .clip(CircleShape) - .clickable { viewMode = KanbanViewMode.Columns.id } - .padding(vertical = 4.dp, horizontal = 2.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - ) { - Icon( - Icons.AutoMirrored.Rounded.ArrowBackIos, - contentDescription = "返回看板", - tint = colors.accent, - modifier = Modifier.size(15.dp), - ) - Text( - "看板", - fontSize = 15.sp, - fontWeight = FontWeight.Medium, - color = colors.accent, - ) - } - - Text( - "计量统计", - fontSize = 17.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, - modifier = Modifier.align(Alignment.Center), - ) - - Icon( - Icons.Rounded.Refresh, - contentDescription = "刷新统计", - tint = colors.accent, - modifier = Modifier - .align(Alignment.CenterEnd) - .size(21.dp) - .clickable { usageRefreshTrigger++ }, - ) - } - } - - HorizontalDivider(color = colors.hairline) - - if (noticeMessage != null) { - Row( - Modifier - .fillMaxWidth() - .background(colors.bgElevated) - .padding(horizontal = 14.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Icon(Icons.Rounded.Info, null, tint = colors.accent, modifier = Modifier.size(15.dp)) - Text( - noticeMessage.orEmpty(), - fontSize = 12.sp, - color = colors.textPrimary, - maxLines = 2, - modifier = Modifier.weight(1f), - ) - Icon( - Icons.Rounded.Close, - contentDescription = "关闭", - tint = colors.textSecondary, - modifier = Modifier - .size(15.dp) - .clickable { noticeMessage = null }, - ) - } - } - - when (viewMode) { - KanbanViewMode.Columns.id -> { - ColumnsBoardContent( - isLoading = isLoading, - errorMessage = errorMessage, - activeSessions = activeSessions, - onReload = { scope.launch { reload() } }, - onOpenUsage = { viewMode = KanbanViewMode.Usage.id }, - onCreateInColumn = { colStatus -> - createInitialStatus = colStatus - showCreateSheet = true - }, - onOpenSession = ::openSession, - onStatusChange = ::performStatusChange, - onTogglePin = ::performTogglePin, - onRequestRename = { target -> - renameDraft = target.resolvedTitle - renamingSession = target - }, - onFork = ::performFork, - onCopyText = { text, msg -> - clipboard.setText(AnnotatedString(text)) - noticeMessage = msg - }, - onRequestDelete = { deletingSession = it }, - ) - } - - else -> { - KanbanUsageDashboardView( - model = model, - projects = projects, - initialProjectId = selectedProjectId, - refreshTrigger = usageRefreshTrigger, - ) - } - } - } - - if (showCreateSheet) { - NewConversationSheet(state, model) { - showCreateSheet = false - scope.launch { reload() } - } - } - - if (renamingSession != null) { - val target = renamingSession!! - AlertDialog( - onDismissRequest = { renamingSession = null }, - title = { Text("重命名会话") }, - text = { - OutlinedTextField( - value = renameDraft, - onValueChange = { renameDraft = it }, - label = { Text("会话名称") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - }, - confirmButton = { - TextButton( - onClick = { - performRename(target, renameDraft) - renamingSession = null - }, - ) { Text("保存") } - }, - dismissButton = { - TextButton(onClick = { renamingSession = null }) { Text("取消") } - }, - ) - } - - if (deletingSession != null) { - val target = deletingSession!! - AlertDialog( - onDismissRequest = { deletingSession = null }, - title = { Text("删除会话") }, - text = { Text("确定删除会话“${target.resolvedTitle}”吗?正在执行中的会话不会被删除。") }, - confirmButton = { - TextButton( - onClick = { - performDelete(target) - deletingSession = null - }, - ) { Text("删除", color = colors.danger) } - }, - dismissButton = { - TextButton(onClick = { deletingSession = null }) { Text("取消") } - }, - ) - } -} - -// ============================================================================ -// MARK: - 1. Four-Column Kanban Board (`columnsBoardContent`) -// ============================================================================ - -@Composable -private fun ColumnsBoardContent( - isLoading: Boolean, - errorMessage: String?, - activeSessions: List, - onReload: () -> Unit, - onOpenUsage: () -> Unit, - onCreateInColumn: (KanbanSessionStatus) -> Unit, - onOpenSession: (KanbanSessionSummary) -> Unit, - onStatusChange: (KanbanSessionSummary, KanbanSessionStatus) -> Unit, - onTogglePin: (KanbanSessionSummary) -> Unit, - onRequestRename: (KanbanSessionSummary) -> Unit, - onFork: (KanbanSessionSummary) -> Unit, - onCopyText: (String, String) -> Unit, - onRequestDelete: (KanbanSessionSummary) -> Unit, -) { - val colors = VibexTheme.colors - val haptic = LocalHapticFeedback.current - val density = LocalDensity.current - - var pullOffsetPx by remember { mutableFloatStateOf(0f) } - var didTriggerFullPullHaptic by remember { mutableStateOf(false) } - val refreshThresholdPx = with(density) { 45.dp.toPx() } - val usageThresholdPx = with(density) { 100.dp.toPx() } - val pullOffsetDp = with(density) { pullOffsetPx.toDp() } - - if (isLoading && activeSessions.isEmpty()) { - KanbanBoardSkeletonView(modifier = Modifier.fillMaxSize()) - return - } - - if (errorMessage != null && activeSessions.isEmpty()) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - EmptyState( - icon = Icons.Rounded.Warning, - title = "加载失败", - message = errorMessage, - action = "重试", - onAction = onReload, - ) - } - return - } - - Box( - Modifier - .fillMaxSize() - .pointerInput(Unit) { - detectVerticalDragGestures( - onVerticalDrag = { _, dragAmount -> - if (dragAmount > 0f || pullOffsetPx > 0f) { - val next = (pullOffsetPx + dragAmount * 0.65f).coerceIn(0f, usageThresholdPx * 1.35f) - pullOffsetPx = next - if (next >= usageThresholdPx && !didTriggerFullPullHaptic) { - didTriggerFullPullHaptic = true - haptic.performHapticFeedback(HapticFeedbackType.LongPress) - } else if (next < usageThresholdPx) { - didTriggerFullPullHaptic = false - } - } - }, - onDragEnd = { - val finalPx = pullOffsetPx - pullOffsetPx = 0f - didTriggerFullPullHaptic = false - if (finalPx >= usageThresholdPx) { - onOpenUsage() - } else if (finalPx >= refreshThresholdPx) { - onReload() - } - }, - onDragCancel = { - pullOffsetPx = 0f - didTriggerFullPullHaptic = false - }, - ) - }, - ) { - BoxWithConstraints(Modifier.fillMaxSize()) { - val columnWidth = minOf(maxWidth - 52.dp, 344.dp).coerceAtLeast(260.dp) - val boardListState = rememberLazyListState() - LazyRow( - state = boardListState, - flingBehavior = rememberSnapFlingBehavior(boardListState), - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues( - start = 16.dp, - end = 16.dp, - top = 10.dp + (pullOffsetDp * 0.35f).coerceAtMost(42.dp), - bottom = 20.dp, - ), - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - items(KanbanSessionStatus.activeColumns, key = { it.rawValue }) { colStatus -> - val colItems = remember(activeSessions, colStatus) { - sortKanbanSessions(activeSessions.filter { it.status == colStatus }, KanbanSortField.DefaultOrder) - } - KanbanColumnCard( - status = colStatus, - width = columnWidth, - items = colItems, - onCreateInColumn = { onCreateInColumn(colStatus) }, - onOpenSession = onOpenSession, - onStatusChange = onStatusChange, - onTogglePin = onTogglePin, - onRequestRename = onRequestRename, - onFork = onFork, - onCopyText = onCopyText, - onRequestDelete = onRequestDelete, - ) - } - } - } - - if (pullOffsetPx > with(density) { 8.dp.toPx() }) { - val isDeepPull = pullOffsetPx >= usageThresholdPx - val isHalfPull = pullOffsetPx >= refreshThresholdPx && !isDeepPull - val label = when { - isDeepPull -> "松手打开计量统计" - isHalfPull -> "松手刷新看板 · 继续下拉打开计量统计" - else -> "下拉刷新 · 拉到底打开计量统计" - } - Row( - Modifier - .align(Alignment.TopCenter) - .padding(top = 8.dp) - .shadow(8.dp, CircleShape) - .clip(CircleShape) - .background(if (isDeepPull) colors.accent else colors.bgElevated) - .border(0.5.dp, colors.stroke, CircleShape) - .padding(horizontal = 14.dp, vertical = 7.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - Icon( - imageVector = if (isDeepPull) Icons.Rounded.BarChart else Icons.Rounded.Refresh, - contentDescription = null, - tint = if (isDeepPull) Color.White else colors.accent, - modifier = Modifier.size(14.dp), - ) - Text( - label, - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, - color = if (isDeepPull) Color.White else colors.textPrimary, - ) - } - } - } -} - -@Composable -private fun KanbanColumnCard( - status: KanbanSessionStatus, - width: Dp, - items: List, - onCreateInColumn: () -> Unit, - onOpenSession: (KanbanSessionSummary) -> Unit, - onStatusChange: (KanbanSessionSummary, KanbanSessionStatus) -> Unit, - onTogglePin: (KanbanSessionSummary) -> Unit, - onRequestRename: (KanbanSessionSummary) -> Unit, - onFork: (KanbanSessionSummary) -> Unit, - onCopyText: (String, String) -> Unit, - onRequestDelete: (KanbanSessionSummary) -> Unit, -) { - val colors = VibexTheme.colors - val colColor = statusColor(status) - - Column( - Modifier - .width(width) - .fillMaxHeight() - .clip(RoundedCornerShape(16.dp)) - .background(colors.bgElevated) - .border(0.5.dp, colors.stroke, RoundedCornerShape(16.dp)), - ) { - // Column Header - Row( - Modifier - .fillMaxWidth() - .background(colColor.copy(0.06f)) - .padding(horizontal = 12.dp, vertical = 9.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(7.dp), - ) { - Box(Modifier.size(8.dp).clip(CircleShape).background(colColor)) - Text(status.title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary) - Text("${items.size}", fontSize = 13.sp, fontWeight = FontWeight.Medium, fontFamily = PlexMono, color = colors.textSecondary) - Spacer(Modifier.weight(1f)) - Box( - Modifier - .size(26.dp) - .clip(CircleShape) - .background(colors.textPrimary.copy(alpha = 0.06f)) - .clickable(onClick = onCreateInColumn), - contentAlignment = Alignment.Center, - ) { - Icon(Icons.Rounded.Add, contentDescription = "新建会话", tint = colors.textSecondary, modifier = Modifier.size(14.dp)) - } - } - - if (items.isEmpty()) { - Column( - Modifier - .fillMaxWidth() - .padding(vertical = 48.dp, horizontal = 12.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text("暂无${status.title}会话", fontSize = 12.sp, color = colors.textSecondary) - Row( - Modifier.clickable(onClick = onCreateInColumn), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - ) { - Icon(Icons.Rounded.Add, null, tint = colors.accent, modifier = Modifier.size(14.dp)) - Text("新建会话", fontSize = 12.sp, fontWeight = FontWeight.Medium, color = colors.accent) - } - } - } else { - LazyColumn( - contentPadding = PaddingValues(8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - items(items, key = { it.id }) { session -> - KanbanSessionItemCard( - session = session, - showStatusPill = false, - onOpenSession = { onOpenSession(session) }, - onStatusChange = { onStatusChange(session, it) }, - onTogglePin = { onTogglePin(session) }, - onRequestRename = { onRequestRename(session) }, - onFork = { onFork(session) }, - onCopyText = onCopyText, - onRequestDelete = { onRequestDelete(session) }, - ) - } - } - } - } -} - -// ============================================================================ -// MARK: - 2. Usage Dashboard (`KanbanUsageDashboardView.swift` 1:1 Parity, <= 2 Rows) -// ============================================================================ - private data class PlanAgentDescriptor( val id: String, val title: String, @@ -800,42 +96,46 @@ private val planAgentDescriptors = listOf( PlanAgentDescriptor("antigravity", "Antigravity 套餐", "读取设置里的 Antigravity 订阅凭据"), ) -private fun usageTabIcon(tab: UsageDashboardTab): ImageVector = when (tab) { - UsageDashboardTab.Overview -> Icons.Rounded.TrendingUp - UsageDashboardTab.Folders -> Icons.Rounded.Folder - UsageDashboardTab.Agents -> Icons.Rounded.Bolt - UsageDashboardTab.Models -> Icons.Rounded.Tag - UsageDashboardTab.Sessions -> Icons.AutoMirrored.Rounded.List - UsageDashboardTab.Plan -> Icons.Rounded.Inventory2 -} - +/** + * 1:1 port of iOS `BoardView.swift`: + * Streamlined Analytics & Plan Quota Dashboard (`用量概览` | `套餐额度`). + */ @Composable -private fun KanbanUsageDashboardView( +fun StatusScreen( + state: UiState, model: CompanionModel, - projects: List, - initialProjectId: String?, - refreshTrigger: Int = 0, ) { val colors = VibexTheme.colors val scope = rememberCoroutineScope() + val projects = state.catalog?.projects.orEmpty() + + var modeId by rememberSaveable { mutableStateOf(BoardDashboardMode.Overview.id) } + val activeMode = BoardDashboardMode.entries.find { it.id == modeId } ?: BoardDashboardMode.Overview var selectedTarget by rememberSaveable { - mutableStateOf(if (!initialProjectId.isNullOrBlank()) "project:$initialProjectId" else "global") + mutableStateOf( + if (!state.selectedProjectId.isNullOrBlank()) "project:${state.selectedProjectId}" else "global", + ) } var dateRange by remember { mutableStateOf(UsageDateRange.SevenDays) } - var activeTab by remember { mutableStateOf(UsageDashboardTab.Overview) } var statistics by remember { mutableStateOf(null) } var isLoading by remember { mutableStateOf(false) } var errorMessage by remember { mutableStateOf(null) } - var sessionSortByCost by rememberSaveable { mutableStateOf(true) } - var showTabMenu by remember { mutableStateOf(false) } var showTargetMenu by remember { mutableStateOf(false) } + var refreshTrigger by remember { mutableIntStateOf(0) } - // Plan usage state var selectedPlanAgent by remember { mutableStateOf(planAgentDescriptors.first()) } val planUsageByAgent = remember { mutableStateMapOf() } var isLoadingPlan by remember { mutableStateOf(false) } + val selectedTargetLabel = remember(selectedTarget, projects) { + if (selectedTarget == "global") "全局" + else { + val id = selectedTarget.removePrefix("project:") + projects.find { it.id.equals(id, ignoreCase = true) }?.name ?: "当前项目" + } + } + suspend fun reloadStatistics() { isLoading = true val sc = if (selectedTarget == "global") "global" else "project" @@ -861,15 +161,15 @@ private fun KanbanUsageDashboardView( reloadStatistics() } - LaunchedEffect(activeTab, selectedPlanAgent.id) { - if (activeTab == UsageDashboardTab.Plan) { + LaunchedEffect(activeMode, selectedPlanAgent.id) { + if (activeMode == BoardDashboardMode.PlanQuota) { loadPlanUsage(selectedPlanAgent.id) } } LaunchedEffect(refreshTrigger) { if (refreshTrigger > 0) { - if (activeTab == UsageDashboardTab.Plan) { + if (activeMode == BoardDashboardMode.PlanQuota) { loadPlanUsage(selectedPlanAgent.id, force = true) } else { reloadStatistics() @@ -877,314 +177,210 @@ private fun KanbanUsageDashboardView( } } - val selectedTargetLabel = remember(selectedTarget, projects) { - if (selectedTarget == "global") "全局" - else { - val id = selectedTarget.removePrefix("project:") - projects.find { it.id.equals(id, ignoreCase = true) }?.name ?: "当前项目" - } - } - - Column(Modifier.fillMaxSize()) { - // Row 2 (Unified Filter Row): Left [概览 ▾] + [全局 ▾] closely grouped (6.dp) | Right [7天 / 30天 / 全部] - Row( - Modifier + Column( + modifier = Modifier + .fillMaxSize() + .background(colors.bg), + ) { + // Top Header: Plain Scope Selector | Centered "看板" | Refresh Button + Box( + modifier = Modifier .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), + .padding(horizontal = 16.dp, vertical = 10.dp), ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - // 1. Dimension Dropdown (概览 / 目录 / Agent / 模型 / 会话 / 套餐) - Box { + if (activeMode == BoardDashboardMode.Overview) { + Box(modifier = Modifier.align(Alignment.CenterStart)) { Row( - Modifier - .clip(CircleShape) - .background(colors.bgElevated) - .border(0.5.dp, colors.stroke, CircleShape) - .clickable { showTabMenu = true } - .padding(horizontal = 10.dp, vertical = 6.dp), + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { showTargetMenu = true } + .padding(horizontal = 4.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), + horizontalArrangement = Arrangement.spacedBy(5.dp), ) { Icon( - imageVector = usageTabIcon(activeTab), + imageVector = if (selectedTarget == "global") Icons.Rounded.Public else Icons.Rounded.Folder, contentDescription = null, - tint = colors.accent, - modifier = Modifier.size(13.dp), + tint = colors.textSecondary, + modifier = Modifier.size(15.dp), ) Text( - activeTab.label, - fontSize = 12.5.sp, - fontWeight = FontWeight.SemiBold, + text = selectedTargetLabel, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, color = colors.textPrimary, maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 104.dp), + ) + Icon( + imageVector = Icons.Rounded.ExpandMore, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(15.dp), ) - Icon(Icons.Rounded.ExpandMore, null, tint = colors.textSecondary, modifier = Modifier.size(13.dp)) - } - DropdownMenu(expanded = showTabMenu, onDismissRequest = { showTabMenu = false }) { - UsageDashboardTab.entries.forEach { tab -> - DropdownMenuItem( - text = { Text(tab.label) }, - leadingIcon = { Icon(usageTabIcon(tab), null, modifier = Modifier.size(16.dp)) }, - trailingIcon = if (activeTab == tab) { - { Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(16.dp)) } - } else null, - onClick = { - showTabMenu = false - activeTab = tab - }, - ) - } } - } - - // 2. Scope Dropdown (全局 / 项目) — Placed right next to 概览 ▾ - if (activeTab != UsageDashboardTab.Plan) { - Box { - Row( - Modifier - .clip(CircleShape) - .background(colors.bgElevated) - .border(0.5.dp, colors.stroke, CircleShape) - .clickable { showTargetMenu = true } - .padding(horizontal = 10.dp, vertical = 6.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - Icon( - imageVector = if (selectedTarget == "global") Icons.Rounded.Public else Icons.Rounded.Folder, - contentDescription = null, - tint = colors.textSecondary, - modifier = Modifier.size(13.dp), - ) - Text( - selectedTargetLabel, - fontSize = 12.5.sp, - fontWeight = FontWeight.Medium, - color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.widthIn(max = 88.dp), - ) - Icon(Icons.Rounded.ExpandMore, null, tint = colors.textSecondary, modifier = Modifier.size(13.dp)) + VibexDropdownMenu( + expanded = showTargetMenu, + onDismissRequest = { showTargetMenu = false }, + ) { + VibexDropdownMenuItem( + text = "全局", + leadingIcon = Icons.Rounded.Public, + selected = selectedTarget == "global", + onClick = { + showTargetMenu = false + selectedTarget = "global" + }, + ) + if (projects.isNotEmpty()) { + VibexDropdownDivider() } - DropdownMenu(expanded = showTargetMenu, onDismissRequest = { showTargetMenu = false }) { - DropdownMenuItem( - text = { Text("全局") }, - trailingIcon = if (selectedTarget == "global") { - { Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(16.dp)) } - } else null, + projects.forEach { project -> + val target = "project:${project.id}" + VibexDropdownMenuItem( + text = project.name, + leadingIcon = Icons.Rounded.Folder, + selected = selectedTarget == target, onClick = { showTargetMenu = false - selectedTarget = "global" + selectedTarget = target }, ) - projects.forEach { project -> - val target = "project:${project.id}" - DropdownMenuItem( - text = { Text(project.name) }, - trailingIcon = if (selectedTarget == target) { - { Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(16.dp)) } - } else null, - onClick = { - showTargetMenu = false - selectedTarget = target - }, - ) - } } } } } - Spacer(Modifier.weight(1f)) + Text( + text = "看板", + fontSize = 17.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + modifier = Modifier.align(Alignment.Center), + ) - if (activeTab != UsageDashboardTab.Plan) { - Row( - Modifier - .width(142.dp) - .clip(RoundedCornerShape(8.dp)) - .background(colors.segmentedTrack) - .padding(2.dp), - ) { - UsageDateRange.entries.forEach { range -> - val selected = dateRange == range - Text( - range.label, - fontSize = 11.5.sp, - fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, - color = if (selected) colors.textPrimary else colors.textSecondary, - textAlign = TextAlign.Center, - modifier = Modifier - .weight(1f) - .then( - if (selected) Modifier.shadow(1.5.dp, RoundedCornerShape(6.dp), ambientColor = Color.Black.copy(0.08f)) - else Modifier, - ) - .clip(RoundedCornerShape(6.dp)) - .background(if (selected) colors.segmentedThumb else Color.Transparent) - .clickable { dateRange = range } - .padding(vertical = 5.dp), - ) - } + Box( + modifier = Modifier + .align(Alignment.CenterEnd) + .size(34.dp) + .clip(CircleShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, CircleShape) + .clickable { refreshTrigger += 1 }, + contentAlignment = Alignment.Center, + ) { + if (isLoading || isLoadingPlan) { + CircularProgressIndicator( + color = colors.accent, + strokeWidth = 1.8.dp, + modifier = Modifier.size(15.dp), + ) + } else { + Icon( + imageVector = Icons.Rounded.Refresh, + contentDescription = "刷新", + tint = colors.textPrimary, + modifier = Modifier.size(17.dp), + ) } } } - HorizontalDivider(color = colors.hairline) - - if (activeTab == UsageDashboardTab.Plan) { - UsagePlanTabContent( - selectedPlanAgent = selectedPlanAgent, - onSelectPlanAgent = { selectedPlanAgent = it }, - planUsageByAgent = planUsageByAgent, - isLoadingPlan = isLoadingPlan, - ) - } else if (isLoading && statistics == null) { - KanbanBoardSkeletonView(modifier = Modifier.fillMaxSize()) - } else if (errorMessage != null && statistics == null) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - EmptyState( - icon = Icons.Rounded.Warning, - title = "统计读取失败", - message = errorMessage.orEmpty(), - action = "重试", - onAction = { scope.launch { reloadStatistics() } }, + // 2-Mode Segmented Picker ("用量概览" | "套餐额度") + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(bottom = 10.dp) + .clip(RoundedCornerShape(10.dp)) + .background(colors.segmentedTrack) + .padding(3.dp), + ) { + BoardDashboardMode.entries.forEach { mode -> + val selected = activeMode == mode + Text( + text = mode.label, + fontSize = 13.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = if (selected) colors.textPrimary else colors.textSecondary, + textAlign = TextAlign.Center, + modifier = Modifier + .weight(1f) + .then( + if (selected) Modifier.shadow(1.5.dp, RoundedCornerShape(8.dp), ambientColor = Color.Black.copy(0.08f)) + else Modifier, + ) + .clip(RoundedCornerShape(8.dp)) + .background(if (selected) colors.segmentedThumb else Color.Transparent) + .clickable { modeId = mode.id } + .padding(vertical = 7.dp), ) } - } else if (statistics != null) { - val stats = statistics!! - LazyColumn( - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(14.dp), - ) { - when (activeTab) { - UsageDashboardTab.Overview -> { - item { UsageOverviewContent(stats) } - } - UsageDashboardTab.Folders -> { - if (stats.byFolder.isEmpty()) { - item { EmptyState(Icons.Rounded.Folder, "暂无目录数据", "当前范围内没有工作区目录记录。") } - } else { - items(stats.byFolder, key = { "${it.workspaceId}-${it.folder.orEmpty()}" }) { item -> - val counts = item.tokens.preferred - Column( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(14.dp)) - .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Icon(Icons.Rounded.Folder, null, tint = colors.accent, modifier = Modifier.size(16.dp)) - Spacer(Modifier.width(6.dp)) - Text(item.displayName, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, modifier = Modifier.weight(1f)) - if (item.cost != null) { - Text(formatUsageCost(item.cost), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, fontFamily = PlexMono, color = colors.pass) - } - } - val folderPath = item.folder - if (!folderPath.isNullOrBlank()) { - Text(folderPath, fontSize = 11.sp, color = colors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Text("${item.sessionCount} 会话", fontSize = 12.sp, color = colors.textSecondary) - Text("总 Token: ${formatUsageTokens(counts.resolvedTotal)}", fontSize = 12.sp, color = colors.textSecondary) - } - } - } - } - } - UsageDashboardTab.Agents -> { - if (stats.byAgent.isEmpty()) { - item { EmptyState(Icons.Rounded.Bolt, "暂无 Agent 数据", "当前范围内没有 Agent 统计记录。") } - } else { - items(stats.byAgent, key = { it.agentId }) { item -> - val counts = item.tokens.preferred - Column( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(14.dp)) - .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - AgentAvatar(item.agentId, 20.dp) - Text(item.displayName, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, modifier = Modifier.weight(1f)) - if (item.cost != null) { - Text(formatUsageCost(item.cost), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, fontFamily = PlexMono, color = colors.pass) - } - } - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Text("${item.sessionCount} 会话", fontSize = 12.sp, color = colors.textSecondary) - Text("输入: ${formatUsageTokens(counts.inputTokens)}", fontSize = 12.sp, color = colors.textSecondary) - Text("输出: ${formatUsageTokens(counts.outputTokens)}", fontSize = 12.sp, color = colors.textSecondary) - Text("总计: ${formatUsageTokens(counts.resolvedTotal)}", fontSize = 12.sp, color = colors.textSecondary) - } - } - } - } - } - UsageDashboardTab.Models -> { - if (stats.byModel.isEmpty()) { - item { EmptyState(Icons.Rounded.Tag, "暂无模型数据", "当前范围内没有模型用量记录。") } - } else { - items(stats.byModel, key = { it.model }) { item -> - val counts = item.tokens.preferred - Column( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(14.dp)) - .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Icon(Icons.Rounded.Memory, null, tint = Color(0xFF5856D6), modifier = Modifier.size(16.dp)) - Text(item.model, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - if (item.cost != null) { - Text(formatUsageCost(item.cost), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, fontFamily = PlexMono, color = colors.pass) - } - } - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Text("${item.sessionCount} 会话", fontSize = 12.sp, color = colors.textSecondary) - Text("输入: ${formatUsageTokens(counts.inputTokens)}", fontSize = 12.sp, color = colors.textSecondary) - Text("输出: ${formatUsageTokens(counts.outputTokens)}", fontSize = 12.sp, color = colors.textSecondary) - Text("总 Token: ${formatUsageTokens(counts.resolvedTotal)}", fontSize = 12.sp, color = colors.textSecondary) - } - } - } - } + } + + when (activeMode) { + BoardDashboardMode.PlanQuota -> { + UsagePlanTabContent( + selectedPlanAgent = selectedPlanAgent, + onSelectPlanAgent = { selectedPlanAgent = it }, + planUsageByAgent = planUsageByAgent, + isLoadingPlan = isLoadingPlan, + ) + } + + BoardDashboardMode.Overview -> { + if (isLoading && statistics == null) { + KanbanBoardSkeletonView(modifier = Modifier.fillMaxSize()) + } else if (errorMessage != null && statistics == null) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(bottom = BOTTOM_DOCK_CLEARANCE), + contentAlignment = Alignment.Center, + ) { + EmptyState( + icon = Icons.Rounded.Warning, + title = "统计读取失败", + message = errorMessage.orEmpty(), + action = "重试", + onAction = { scope.launch { reloadStatistics() } }, + ) } - UsageDashboardTab.Sessions -> { - val sorted = if (sessionSortByCost) { - stats.sessions.sortedByDescending { it.cost ?: -1.0 } - } else { - stats.sessions.sortedByDescending { it.timestamp } - } - item { - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text("会话列表 (${sorted.size})", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, modifier = Modifier.weight(1f)) + } else { + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues( + start = 16.dp, + end = 16.dp, + top = 4.dp, + bottom = BOTTOM_DOCK_CLEARANCE + 18.dp, + ), + verticalArrangement = Arrangement.spacedBy(14.dp), + ) { + item(key = "range_picker") { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = "统计区间", + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + modifier = Modifier.weight(1f), + ) Row( - Modifier - .width(136.dp) + modifier = Modifier + .width(168.dp) .clip(RoundedCornerShape(8.dp)) .background(colors.segmentedTrack) .padding(2.dp), ) { - listOf(true to "按费用", false to "按时间").forEach { (byCost, label) -> - val selected = sessionSortByCost == byCost + UsageDateRange.entries.forEach { range -> + val selected = dateRange == range Text( - label, + text = range.label, fontSize = 12.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, color = if (selected) colors.textPrimary else colors.textSecondary, @@ -1197,59 +393,21 @@ private fun KanbanUsageDashboardView( ) .clip(RoundedCornerShape(6.dp)) .background(if (selected) colors.segmentedThumb else Color.Transparent) - .clickable { sessionSortByCost = byCost } - .padding(vertical = 4.dp), + .clickable { dateRange = range } + .padding(vertical = 5.dp), ) } } } } - items(sorted.take(50), key = { it.sessionId }) { item -> - val counts = item.tokens.preferred - Column( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(12.dp)) - .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(12.dp)) - .clickable { model.openConversation(item.sessionId) } - .padding(12.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text(item.displayTitle, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - if (item.cost != null) { - Text(formatUsageCost(item.cost), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, fontFamily = PlexMono, color = colors.pass) - } - } - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - val itemAgentId = item.agentId - if (!itemAgentId.isNullOrBlank()) { - Row( - Modifier - .clip(CircleShape) - .background(colors.accent.copy(0.12f)) - .padding(horizontal = 6.dp, vertical = 2.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - ) { - AgentAvatar(itemAgentId, 11.dp) - Text(agentDisplayName(itemAgentId), fontSize = 10.sp, color = colors.textPrimary) - } - } - val itemModel = item.model - if (!itemModel.isNullOrBlank()) { - Text(itemModel, fontSize = 11.sp, color = colors.textSecondary, maxLines = 1) - } - if ((item.turns ?: 0) > 0) { - Text("${item.turns} 轮次", fontSize = 11.sp, color = colors.textSecondary) - } - Text("${formatUsageTokens(counts.resolvedTotal)} Token", fontSize = 11.sp, color = colors.textSecondary) - } + + val stats = statistics + if (stats != null) { + item(key = "overview_body") { + UsageOverviewContent(stats) } } } - UsageDashboardTab.Plan -> Unit } } } @@ -1261,87 +419,134 @@ private fun UsageOverviewContent(stats: ProjectUsageStatistics) { val colors = VibexTheme.colors val preferred = stats.totalTokens.preferred - Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { + Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { // 2x2 Summary Metric Grid Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { UsageMetricCard( - title = "总费用", + title = "总 Token", + value = formatUsageTokens(preferred.resolvedTotal), + subtitle = "平均每次 ${formatUsageTokens(stats.avgTokensPerSession)}", + icon = Icons.Rounded.Memory, + tint = Color(0xFFAF52DE), + modifier = Modifier.weight(1f), + ) + UsageMetricCard( + title = "预估成本", value = formatUsageCost(stats.resolvedCost), subtitle = if (stats.totalSessions > 0 && stats.resolvedCost != null) { - "平均 ${formatUsageCost(stats.resolvedCost!! / stats.totalSessions.toDouble())}/会话" - } else "按协议与日志估算", + "均 ${formatUsageCost(stats.resolvedCost!! / stats.totalSessions.toDouble())}/会话" + } else "按官方单价估算", icon = Icons.Rounded.Paid, tint = Color(0xFF34C759), modifier = Modifier.weight(1f), ) + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { UsageMetricCard( - title = "总会话", + title = "会话数", value = "${stats.totalSessions}", subtitle = "${stats.activeDaysCount} 个活跃日", icon = Icons.Rounded.ChatBubble, tint = Color(0xFF007AFF), modifier = Modifier.weight(1f), ) - } - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { - UsageMetricCard( - title = "总 Token", - value = formatUsageTokens(preferred.resolvedTotal), - subtitle = "平均每次 ${formatUsageTokens(stats.avgTokensPerSession)} Token", - icon = Icons.Rounded.Memory, - tint = Color(0xFFAF52DE), - modifier = Modifier.weight(1f), - ) UsageMetricCard( - title = "缓存命中率", - value = stats.cacheHitRatePercent?.let { String.format(Locale.US, "%.1f%%", it) } ?: "--", - subtitle = "缓存读取 ${formatUsageTokens(preferred.cacheReadTokens)}", - icon = Icons.Rounded.Bolt, + title = "输入 / 输出", + value = "${formatUsageTokens(preferred.inputTokens)} / ${formatUsageTokens(preferred.outputTokens)}", + subtitle = stats.cacheHitRatePercent?.let { + String.format(Locale.US, "缓存命中 %.1f%%", it) + } ?: "缓存读取 ${formatUsageTokens(preferred.cacheReadTokens)}", + icon = Icons.Rounded.SwapVert, tint = Color(0xFFFF9500), modifier = Modifier.weight(1f), ) } - // Token Composition + // 7-Day Trend Bar Card + val recentDays = remember(stats.dailyUsage) { stats.dailyUsage.takeLast(7) } Column( - Modifier + modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(14.dp)) .background(colors.card) .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Text("Token 构成", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary) - val total = preferred.resolvedTotal.coerceAtLeast(1L).toFloat() - listOf( - Triple("输入", preferred.inputTokens, Color(0xFF007AFF)), - Triple("输出", preferred.outputTokens, Color(0xFFAF52DE)), - Triple("缓存写入", preferred.cacheWriteTokens, Color(0xFFFF9500)), - Triple("缓存读取", preferred.cacheReadTokens, Color(0xFF34C759)), - ).forEach { (label, count, barColor) -> - val ratio = (count.toFloat() / total).coerceIn(0f, 1f) - Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { - Box(Modifier.size(8.dp).clip(CircleShape).background(barColor)) - Spacer(Modifier.width(6.dp)) - Text(label, fontSize = 12.sp, color = colors.textSecondary, modifier = Modifier.weight(1f)) - Text(formatUsageTokens(count), fontSize = 12.sp, fontWeight = FontWeight.Medium, fontFamily = PlexMono, color = colors.textPrimary) - } - Box( - Modifier - .fillMaxWidth() - .height(6.dp) - .clip(CircleShape) - .background(colors.segmentedTrack), - ) { - if (count > 0L) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = "近 7 日趋势", + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + val peak = recentDays.maxOfOrNull { it.tokens.preferred.resolvedTotal } ?: 0L + if (peak > 0L) { + Text( + text = "峰值 ${formatUsageTokens(peak)}", + style = TextStyle( + fontSize = 11.5.sp, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), + ) + } + } + + if (recentDays.isEmpty()) { + Text( + text = "当前区间暂无每日趋势记录", + fontSize = 12.5.sp, + color = colors.textSecondary, + modifier = Modifier.padding(vertical = 12.dp), + ) + } else { + val maxTokens = (recentDays.maxOfOrNull { it.tokens.preferred.resolvedTotal } ?: 1L) + .coerceAtLeast(1L) + .toFloat() + Row( + modifier = Modifier + .fillMaxWidth() + .height(116.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.Bottom, + ) { + recentDays.forEach { day -> + val dayTokens = day.tokens.preferred.resolvedTotal + val ratio = (dayTokens.toFloat() / maxTokens).coerceIn(0f, 1f) + Column( + modifier = Modifier + .weight(1f) + .fillMaxHeight(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Bottom, + ) { Box( - Modifier - .fillMaxWidth(ratio.coerceAtLeast(0.02f)) - .height(6.dp) - .clip(CircleShape) - .background(barColor), + modifier = Modifier + .weight(1f) + .fillMaxWidth(), + contentAlignment = Alignment.BottomCenter, + ) { + Box( + modifier = Modifier + .width(20.dp) + .fillMaxHeight(if (dayTokens > 0L) ratio.coerceAtLeast(0.06f) else 0.03f) + .clip(RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp, bottomStart = 3.dp, bottomEnd = 3.dp)) + .background(if (dayTokens > 0L) colors.accent else colors.segmentedTrack), + ) + } + Spacer(Modifier.height(6.dp)) + Text( + text = day.date.takeLast(5), + style = TextStyle( + fontSize = 10.sp, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), + maxLines = 1, ) } } @@ -1349,48 +554,86 @@ private fun UsageOverviewContent(stats: ProjectUsageStatistics) { } } - // Daily Trend - if (stats.dailyUsage.isNotEmpty()) { - Column( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(14.dp)) - .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text("用量趋势", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary, modifier = Modifier.weight(1f)) - Text("${stats.dailyUsage.size} 天", fontSize = 12.sp, color = colors.textSecondary) - } - val maxTokens = (stats.dailyUsage.maxOfOrNull { it.tokens.preferred.resolvedTotal } ?: 1L).coerceAtLeast(1L).toFloat() - stats.dailyUsage.takeLast(14).reversed().forEach { day -> - val dayTokens = day.tokens.preferred.resolvedTotal - val ratio = (dayTokens.toFloat() / maxTokens).coerceIn(0f, 1f) + // Top 6 Models Card + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(14.dp)) + .background(colors.card) + .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) + .padding(14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text( + text = "常用模型", + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textPrimary, + ) + if (stats.byModel.isEmpty()) { + Text( + text = "暂无模型调用记录", + fontSize = 12.5.sp, + color = colors.textSecondary, + ) + } else { + val topModels = stats.byModel.take(6) + val maxModelTokens = (topModels.maxOfOrNull { it.tokens.preferred.resolvedTotal } ?: 1L) + .coerceAtLeast(1L) + .toFloat() + topModels.forEach { item -> + val count = item.tokens.preferred.resolvedTotal + val ratio = (count.toFloat() / maxModelTokens).coerceIn(0f, 1f) Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(day.date, fontSize = 12.sp, fontFamily = PlexMono, color = colors.textSecondary, modifier = Modifier.weight(1f)) - Text("${day.sessions} 会话", fontSize = 11.sp, color = colors.textSecondary) - Text("${formatUsageTokens(dayTokens)} Token", fontSize = 12.sp, fontWeight = FontWeight.Medium, fontFamily = PlexMono, color = colors.textPrimary) - if (day.cost != null) { - Text(formatUsageCost(day.cost), fontSize = 12.sp, fontFamily = PlexMono, color = colors.pass) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = item.model, + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Text( + text = formatUsageTokens(count), + style = TextStyle( + fontSize = 12.sp, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), + ) + if (item.cost != null) { + Text( + text = formatUsageCost(item.cost), + style = TextStyle( + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textPrimary, + ), + ) } } Box( - Modifier + modifier = Modifier .fillMaxWidth() - .height(6.dp) + .height(5.dp) .clip(CircleShape) .background(colors.segmentedTrack), ) { - if (dayTokens > 0L) { + if (count > 0L) { Box( - Modifier - .fillMaxWidth(ratio.coerceAtLeast(0.02f)) - .height(6.dp) + modifier = Modifier + .fillMaxWidth(ratio.coerceAtLeast(0.03f)) + .height(5.dp) .clip(CircleShape) - .background(colors.accent), + .background(colors.accent.copy(alpha = 0.85f)), ) } } @@ -1398,31 +641,6 @@ private fun UsageOverviewContent(stats: ProjectUsageStatistics) { } } } - - // Top Models - if (stats.byModel.isNotEmpty()) { - Column( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(14.dp)) - .background(colors.card) - .border(0.75.dp, colors.stroke, RoundedCornerShape(14.dp)) - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text("常用模型", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.textPrimary) - stats.byModel.take(5).forEach { item -> - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(item.model, fontSize = 13.sp, fontWeight = FontWeight.Medium, color = colors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - Text("${item.sessionCount} 会话", fontSize = 12.sp, color = colors.textSecondary) - Text(formatUsageTokens(item.tokens.preferred.resolvedTotal), fontSize = 12.sp, fontFamily = PlexMono, color = colors.textSecondary) - if (item.cost != null) { - Text(formatUsageCost(item.cost), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, fontFamily = PlexMono, color = colors.textPrimary) - } - } - } - } - } } } @@ -1437,7 +655,13 @@ private fun UsagePlanTabContent( val response = planUsageByAgent[selectedPlanAgent.id] LazyColumn( - contentPadding = PaddingValues(16.dp), + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues( + start = 16.dp, + end = 16.dp, + top = 4.dp, + bottom = BOTTOM_DOCK_CLEARANCE + 18.dp, + ), verticalArrangement = Arrangement.spacedBy(16.dp), ) { item { @@ -1447,7 +671,12 @@ private fun UsagePlanTabContent( Row( Modifier .clip(CircleShape) - .background(if (isSelected) colors.accent else colors.bgElevated) + .background(if (isSelected) colors.accent else colors.card) + .border( + width = 0.6.dp, + color = if (isSelected) Color.Transparent else colors.stroke, + shape = CircleShape, + ) .clickable { onSelectPlanAgent(descriptor) } .padding(horizontal = 12.dp, vertical = 7.dp), verticalAlignment = Alignment.CenterVertically, @@ -1455,10 +684,10 @@ private fun UsagePlanTabContent( ) { AgentAvatar(descriptor.id, 14.dp) Text( - agentDisplayName(descriptor.id), + text = agentDisplayName(descriptor.id), fontSize = 13.sp, fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium, - color = if (isSelected) Color.White else colors.textPrimary, + color = if (isSelected) colors.onAccent else colors.textPrimary, ) } } @@ -1482,7 +711,7 @@ private fun UsagePlanTabContent( } if (response is PlanUsageResponse.Ok && !response.usage.planType.isNullOrBlank()) { Text( - "${response.usage.planType!!.uppercase()} 套餐", + text = "${response.usage.planType!!.uppercase()} 套餐", fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = colors.accent, @@ -1521,9 +750,12 @@ private fun UsagePlanTabContent( ) { Icon(Icons.Rounded.CreditCard, null, tint = colors.textSecondary, modifier = Modifier.size(16.dp)) Text( - if (credits.unlimited) "额度不限量" else "赠送额度余额:${credits.balance ?: "--"}", - fontSize = 13.sp, - color = colors.textSecondary, + text = if (credits.unlimited) "额度不限量" else "赠送额度余额:${credits.balance ?: "--"}", + style = TextStyle( + fontSize = 13.sp, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), ) } } @@ -1575,8 +807,25 @@ private fun PlanWindowRow(window: PlanUsageWindow) { } } Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text(used?.let { "已用 $it%" } ?: "--", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, fontFamily = PlexMono, color = colors.textPrimary) - Text(remaining?.let { "剩余 $it%" } ?: "--", fontSize = 12.sp, fontFamily = PlexMono, color = colors.textSecondary) + Text( + text = used?.let { "已用 $it%" } ?: "--", + style = TextStyle( + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textPrimary, + ), + ) + Text( + text = remaining?.let { "剩余 $it%" } ?: "--", + style = TextStyle( + fontSize = 12.sp, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), + ) } } Box( @@ -1622,355 +871,22 @@ private fun UsageMetricCard( Icon(icon, null, tint = tint, modifier = Modifier.size(16.dp)) Text(title, fontSize = 12.sp, color = colors.textSecondary) } - Text(value, fontSize = 19.sp, fontWeight = FontWeight.Bold, fontFamily = PlexMono, color = colors.textPrimary, maxLines = 1) - Text(subtitle, fontSize = 11.sp, color = colors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) - } -} - -// ============================================================================ -// MARK: - Reusable Session Card & Context Menu (`BoardView.sessionCard` Parity) -// ============================================================================ - -@Composable -private fun KanbanSessionItemCard( - session: KanbanSessionSummary, - showStatusPill: Boolean, - onOpenSession: () -> Unit, - onStatusChange: (KanbanSessionStatus) -> Unit, - onTogglePin: () -> Unit, - onRequestRename: () -> Unit, - onFork: () -> Unit, - onCopyText: (String, String) -> Unit, - onRequestDelete: () -> Unit, -) { - val colors = VibexTheme.colors - var showMenu by remember { mutableStateOf(false) } - val member = session.collaboration?.memberName?.takeIf { it.isNotBlank() } - val showsStatus = !session.isRunning && (showStatusPill || session.status == KanbanSessionStatus.InReview) - val accentColor = if (session.isRunning) Color(0xFFFF9500) else statusColor(session.status) - - Box( - Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(12.dp)) - .background(colors.card) - .border( - width = if (session.isRunning) 1.dp else 0.6.dp, - color = if (session.isRunning) Color(0xFFFF9500).copy(0.4f) else colors.stroke, - shape = RoundedCornerShape(12.dp), - ) - .clickable(onClick = onOpenSession), - ) { - if (session.isRunning || session.status == KanbanSessionStatus.InReview) { - Box( - Modifier - .align(Alignment.CenterStart) - .padding(start = 1.5.dp, top = 10.dp, bottom = 10.dp) - .width(3.dp) - .heightIn(min = 24.dp) - .clip(CircleShape) - .background(accentColor), - ) - } - - Column( - Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 10.dp), - verticalArrangement = Arrangement.spacedBy(7.dp), - ) { - Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - if (session.isPinned) { - Icon( - Icons.Rounded.PushPin, - contentDescription = null, - tint = Color(0xFFFF9500), - modifier = Modifier.padding(top = 2.dp).size(12.dp), - ) - } - Text( - session.resolvedTitle, - fontSize = 14.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - Box { - Icon( - Icons.Rounded.MoreHoriz, - contentDescription = "菜单", - tint = colors.textSecondary, - modifier = Modifier - .size(20.dp) - .clickable { showMenu = true }, - ) - KanbanSessionContextMenu( - expanded = showMenu, - onDismiss = { showMenu = false }, - session = session, - onOpenSession = onOpenSession, - onStatusChange = onStatusChange, - onTogglePin = onTogglePin, - onRequestRename = onRequestRename, - onFork = onFork, - onCopyText = onCopyText, - onRequestDelete = onRequestDelete, - ) - } - } - - val prompt = session.firstPrompt?.trim() - if (!prompt.isNullOrEmpty() && prompt != session.resolvedTitle) { - val cleanedPrompt = remember(prompt) { cleanMarkdownPreview(prompt) } - Text( - cleanedPrompt, - fontSize = 12.sp, - color = colors.textSecondary, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - - if (session.isRunning || showsStatus || member != null) { - Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) { - if (session.isRunning) { - Text( - "进行中", - fontSize = 10.sp, - fontWeight = FontWeight.SemiBold, - color = Color(0xFFFF9500), - modifier = Modifier - .clip(CircleShape) - .background(Color(0xFFFF9500).copy(0.14f)) - .padding(horizontal = 6.dp, vertical = 2.dp), - ) - } else if (showsStatus) { - val stColor = statusColor(session.status) - Text( - session.status.title, - fontSize = 10.sp, - fontWeight = FontWeight.SemiBold, - color = stColor, - modifier = Modifier - .clip(CircleShape) - .background(stColor.copy(0.14f)) - .padding(horizontal = 6.dp, vertical = 2.dp), - ) - } - if (member != null) { - Row( - Modifier - .clip(CircleShape) - .background(Color(0xFF5856D6).copy(0.14f)) - .padding(horizontal = 6.dp, vertical = 2.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(3.dp), - ) { - Icon(Icons.Rounded.Groups, null, tint = Color(0xFF5856D6), modifier = Modifier.size(10.dp)) - Text(member, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = Color(0xFF5856D6), maxLines = 1) - } - } - } - } - - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { - AgentAvatar(session.effectiveAgentKey, 13.dp) - Text( - session.model?.takeIf { it.isNotBlank() } ?: session.agentDisplayLabel, - fontSize = 11.sp, - color = colors.textSecondary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (session.workspaceDisplayLabel.isNotBlank()) { - Text("·", fontSize = 11.sp, color = colors.textTertiary) - Text( - session.workspaceDisplayLabel, - fontSize = 11.sp, - color = colors.textSecondary, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Spacer(Modifier.weight(1f)) - Text( - shortRelativeIso(session.updatedAt), - fontSize = 11.sp, - color = colors.textTertiary, - ) - } - } - } -} - -@Composable -private fun KanbanSessionContextMenu( - expanded: Boolean, - onDismiss: () -> Unit, - session: KanbanSessionSummary, - onOpenSession: () -> Unit, - onStatusChange: (KanbanSessionStatus) -> Unit, - onTogglePin: () -> Unit, - onRequestRename: () -> Unit, - onFork: () -> Unit, - onCopyText: (String, String) -> Unit, - onRequestDelete: () -> Unit, -) { - val colors = VibexTheme.colors - DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) { - DropdownMenuItem( - text = { Text("打开会话") }, - leadingIcon = { Icon(Icons.Rounded.ChatBubble, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onOpenSession() - }, - ) - KanbanSessionStatus.activeColumns.forEach { st -> - if (st != session.status) { - DropdownMenuItem( - text = { Text("移至:${st.title}") }, - leadingIcon = { Icon(Icons.Rounded.SwapHoriz, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onStatusChange(st) - }, - ) - } - } - DropdownMenuItem( - text = { Text(if (session.isPinned) "取消置顶" else "置顶") }, - leadingIcon = { Icon(Icons.Rounded.PushPin, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onTogglePin() - }, - ) - DropdownMenuItem( - text = { Text("重命名会话") }, - leadingIcon = { Icon(Icons.Rounded.Edit, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onRequestRename() - }, - ) - if (session.isForkSupported) { - DropdownMenuItem( - text = { Text("从本会话 Fork") }, - leadingIcon = { Icon(Icons.Rounded.CallSplit, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onFork() - }, - ) - } - DropdownMenuItem( - text = { Text("复制会话名称") }, - leadingIcon = { Icon(Icons.Rounded.ContentCopy, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onCopyText(session.resolvedTitle, "已复制会话名称") - }, - ) - DropdownMenuItem( - text = { Text("复制会话信息") }, - leadingIcon = { Icon(Icons.Rounded.Info, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onCopyText(session.sessionInfoText, "已复制会话信息") - }, - ) - HorizontalDivider() - if (session.isArchived) { - DropdownMenuItem( - text = { Text("移至待办") }, - leadingIcon = { Icon(Icons.Rounded.Unarchive, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onStatusChange(KanbanSessionStatus.Todo) - }, - ) - } else { - DropdownMenuItem( - text = { Text("归档") }, - leadingIcon = { Icon(Icons.Rounded.Archive, null, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onStatusChange(KanbanSessionStatus.Archived) - }, - ) - } - DropdownMenuItem( - text = { Text("删除会话", color = colors.danger) }, - leadingIcon = { Icon(Icons.Rounded.Delete, null, tint = colors.danger, modifier = Modifier.size(16.dp)) }, - onClick = { - onDismiss() - onRequestDelete() - }, + Text( + text = value, + style = TextStyle( + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + fontFamily = PlexMono, + fontFeatureSettings = "tnum", + color = colors.textPrimary, + ), + maxLines = 1, + overflow = TextOverflow.Ellipsis, ) + Text(subtitle, fontSize = 11.sp, color = colors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) } } -// ============================================================================ -// MARK: - Formatting & Sorting Helpers -// ============================================================================ - -private fun statusColor(status: KanbanSessionStatus): Color = when (status) { - KanbanSessionStatus.Todo -> Color(0xFF007AFF) - KanbanSessionStatus.InProgress -> Color(0xFFFF9500) - KanbanSessionStatus.InReview -> Color(0xFFAF52DE) - KanbanSessionStatus.Done -> Color(0xFF34C759) - KanbanSessionStatus.Archived -> Color(0xFF8E8E93) -} - -private fun sortKanbanSessions( - list: List, - field: KanbanSortField, -): List { - return list.sortedWith { left, right -> - if (left.isPinned != right.isPinned) { - return@sortedWith if (left.isPinned) -1 else 1 - } - when (field) { - KanbanSortField.DefaultOrder, KanbanSortField.Time -> right.updatedAt.compareTo(left.updatedAt) - KanbanSortField.Name -> { - val cmp = left.resolvedTitle.compareTo(right.resolvedTitle, ignoreCase = true) - if (cmp != 0) cmp else right.updatedAt.compareTo(left.updatedAt) - } - KanbanSortField.Status -> { - if (left.status.sortOrder != right.status.sortOrder) { - left.status.sortOrder.compareTo(right.status.sortOrder) - } else right.updatedAt.compareTo(left.updatedAt) - } - KanbanSortField.Agent -> { - val cmp = left.agentDisplayLabel.compareTo(right.agentDisplayLabel, ignoreCase = true) - if (cmp != 0) cmp else right.updatedAt.compareTo(left.updatedAt) - } - } - } -} - -private fun parseIsoMillis(iso: String): Long? = - runCatching { Instant.parse(iso).toEpochMilli() }.getOrNull() - -private fun shortRelativeIso(iso: String): String { - if (iso.isBlank()) return "刚刚" - val ms = parseIsoMillis(iso) - if (ms != null) { - val diffSec = (System.currentTimeMillis() - ms) / 1000L - return when { - diffSec < 60L -> "刚刚" - diffSec < 3600L -> "${diffSec / 60L}分钟前" - diffSec < 86400L -> "${diffSec / 3600L}小时前" - diffSec < 86400L * 30L -> "${diffSec / 86400L}天前" - else -> iso.take(10) - } - } - return iso.substringAfter('T').take(5).ifBlank { iso.take(10) } -} - private fun formatUsageCost(cost: Double?): String { if (cost == null) return "--" if (cost == 0.0) return "$0.00" @@ -1978,17 +894,6 @@ private fun formatUsageCost(cost: Double?): String { return String.format(Locale.US, "$%.2f", cost) } -private fun cleanMarkdownPreview(raw: String): String = - raw - .replace(Regex("```[a-zA-Z0-9_-]*\\n?"), "") - .replace("```", "") - .replace("**", "") - .replace("__", "") - .replace("`", "") - .replace(Regex("(?m)^#{1,6}\\s+"), "") - .replace(Regex("\\s+"), " ") - .trim() - private fun formatUsageTokens(count: Long): String = when { count >= 1_000_000_000L -> String.format(Locale.US, "%.2fB", count / 1_000_000_000.0) count >= 1_000_000L -> String.format(Locale.US, "%.2fM", count / 1_000_000.0) diff --git a/app/src/main/java/dev/vibex/companion/app/ui/ThreadSettingsSheet.kt b/app/src/main/java/dev/vibex/companion/app/ui/ThreadSettingsSheet.kt new file mode 100644 index 0000000..ac6224a --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/ThreadSettingsSheet.kt @@ -0,0 +1,1180 @@ +package dev.vibex.companion.app.ui + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowLeft +import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight +import androidx.compose.material.icons.rounded.AddCircleOutline +import androidx.compose.material.icons.rounded.Cancel +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.ExpandLess +import androidx.compose.material.icons.rounded.ExpandMore +import androidx.compose.material.icons.rounded.FilterList +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material.icons.rounded.Star +import androidx.compose.material.icons.rounded.StarOutline +import androidx.compose.material.icons.rounded.Visibility +import androidx.compose.material.icons.rounded.VisibilityOff +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.vibex.companion.CatalogAgent +import dev.vibex.companion.SessionConfigChoice +import dev.vibex.companion.SessionConfigOption +import dev.vibex.companion.SessionMode +import dev.vibex.companion.agentDisplayName +import dev.vibex.companion.app.data.ModelPreferencesStore +import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.fallbackModelOptionForAgent + +private sealed interface ModelCatalogFilter { + data object All : ModelCatalogFilter + data object Favorites : ModelCatalogFilter + data class Provider(val agentId: String, val title: String) : ModelCatalogFilter +} + +private enum class SettingsSubpage { Main, Effort, Runtime } + +private data class ProviderModelGroup( + val agentId: String, + val title: String, + val iconSvg: String, + val modelKey: String, + val choices: List, + val activeValue: String?, +) + +private val StarGold = Color(0xFFF5B400) +private val HiddenOrange = Color(0xFFFF9500) + +private fun storageKeyForModel(agentId: String, choice: SessionConfigChoice): String = + "${agentId.lowercase()}::${choice.value.lowercase()}" + +internal fun findSettingsModelOption(options: List): SessionConfigOption? = + options.firstOrNull { opt -> + val k = opt.key.lowercase() + val c = opt.category.lowercase() + c == "model" || k == "model" || k.contains("model") + } + +internal fun findSettingsEffortOption(options: List): SessionConfigOption? = + options.firstOrNull { opt -> + val k = opt.key.lowercase() + val c = opt.category.lowercase() + c.contains("thought") || c.contains("effort") || c.contains("reason") || + k.contains("thought") || k.contains("effort") || k.contains("thinking") || k.contains("reason") + } + +/** + * 1:1 port of iOS `ThreadSettingsSheet` (`ThreadSettingsSheet.swift`). + * Grouped collapsible provider model catalog with favorites, hidden-model management, + * inline reasoning effort & runtime access controls, custom relay model entry, + * and a floating bottom filter + search bar. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ThreadSettingsSheet( + agentId: String, + agent: CatalogAgent?, + agents: List, + allowCrossAgentSwitch: Boolean, + modes: List, + currentModeId: String, + configOptions: List, + modelPrefs: ModelPreferencesStore, + onSelectAgentAndModel: (agentId: String, modelKey: String, modelValue: String) -> Unit, + onSelectMode: (String) -> Unit, + onSelectOption: (key: String, value: String) -> Unit, + onRefreshCatalog: (() -> Unit)? = null, + onDismiss: () -> Unit, +) { + val colors = VibexTheme.colors + val haptic = LocalHapticFeedback.current + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + + val favoriteIds by modelPrefs.favoriteIds.collectAsState() + val hiddenIds by modelPrefs.hiddenIds.collectAsState() + val customModelsByAgent by modelPrefs.customModelsByAgent.collectAsState() + + var subpage by remember { mutableStateOf(SettingsSubpage.Main) } + var searchQuery by remember { mutableStateOf("") } + var activeFilter by remember { mutableStateOf(ModelCatalogFilter.All) } + var filterMenuExpanded by remember { mutableStateOf(false) } + var manageHiddenModels by remember { mutableStateOf(false) } + var collapsedGroupIds by remember { mutableStateOf>(emptySet()) } + var initialGroupOrder by remember { mutableStateOf>(emptyList()) } + var didApplyDefaultCollapse by remember { mutableStateOf(false) } + var showCustomModelDialog by remember { mutableStateOf(false) } + var customModelDraft by remember { mutableStateOf("") } + + LaunchedEffect(Unit) { + onRefreshCatalog?.invoke() + } + + val activeModelOption = remember(configOptions, agent, agentId) { + findSettingsModelOption(configOptions) + ?: agent?.modelOptions?.firstOrNull() + ?: fallbackModelOptionForAgent(agentId) + } + val effortOption = remember(configOptions, agent) { + findSettingsEffortOption(configOptions) + ?: findSettingsEffortOption(agent?.otherOptions.orEmpty()) + } + val extraOptions = remember(configOptions) { + configOptions.filter { opt -> + opt.key != activeModelOption.key && + opt.key != effortOption?.key && + !opt.category.equals("model", ignoreCase = true) && + !opt.category.equals("mode", ignoreCase = true) && + opt.choices.size > 1 + } + } + + val rawGroups = remember( + agentId, + agent, + agents, + allowCrossAgentSwitch, + activeModelOption, + customModelsByAgent, + ) { + val usableAgents = agents.filter { it.usable } + val primaryTitle = agent?.displayName?.takeIf { it.isNotBlank() } + ?: agentDisplayName(agentId, "") + val primaryCustoms = customModelsByAgent[agentId].orEmpty() + val primaryChoices = buildList { + primaryCustoms.forEach { custom -> + if (activeModelOption.choices.none { it.value.equals(custom, ignoreCase = true) }) { + add(CatalogAgent.makeCustomChoice(custom)) + } + } + addAll(activeModelOption.choices) + } + val primaryGroup = ProviderModelGroup( + agentId = agentId, + title = primaryTitle, + iconSvg = agent?.iconSvg.orEmpty(), + modelKey = activeModelOption.key.ifBlank { "model" }, + choices = primaryChoices, + activeValue = activeModelOption.value.ifBlank { primaryChoices.firstOrNull()?.value }, + ) + + if (!allowCrossAgentSwitch) { + listOf(primaryGroup) + } else { + val others = usableAgents + .filterNot { it.id.equals(agentId, ignoreCase = true) } + .map { other -> + val opt = other.modelOptions.firstOrNull() ?: fallbackModelOptionForAgent(other.id) + val customs = customModelsByAgent[other.id].orEmpty() + val merged = buildList { + customs.forEach { custom -> + if (opt.choices.none { c -> c.value.equals(custom, ignoreCase = true) }) { + add(CatalogAgent.makeCustomChoice(custom)) + } + } + addAll(opt.choices) + } + ProviderModelGroup( + agentId = other.id, + title = agentDisplayName(other.id, other.displayName), + iconSvg = other.iconSvg, + modelKey = opt.key.ifBlank { "model" }, + choices = merged, + activeValue = null, + ) + } + listOf(primaryGroup) + others + } + } + + LaunchedEffect(rawGroups.map { it.agentId }) { + val missing = rawGroups.map { it.agentId }.filterNot { it in initialGroupOrder } + if (missing.isNotEmpty()) { + initialGroupOrder = initialGroupOrder + missing + } + if (!didApplyDefaultCollapse && rawGroups.size > 1) { + val totalChoices = rawGroups.sumOf { it.choices.size } + if (rawGroups.size >= 3 || totalChoices > 8) { + collapsedGroupIds = rawGroups.drop(1).map { it.agentId }.toSet() + } + didApplyDefaultCollapse = true + } + } + + val orderedGroups = remember(rawGroups, initialGroupOrder) { + if (initialGroupOrder.isEmpty()) rawGroups + else { + val rank = initialGroupOrder.withIndex().associate { it.value to it.index } + rawGroups.sortedBy { rank[it.agentId] ?: 10_000 } + } + } + + val isSearchingModels = searchQuery.trim().isNotEmpty() + + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState, + containerColor = colors.bg, + dragHandle = null, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 420.dp, max = 720.dp) + .navigationBarsPadding() + .imePadding(), + ) { + AnimatedContent( + targetState = subpage, + transitionSpec = { fadeIn() togetherWith fadeOut() }, + label = "settingsSubpage", + modifier = Modifier.weight(1f), + ) { page -> + when (page) { + SettingsSubpage.Effort -> EffortSubpageContent( + option = effortOption, + onBack = { subpage = SettingsSubpage.Main }, + onSelect = { value -> + effortOption?.let { onSelectOption(it.key, value) } + subpage = SettingsSubpage.Main + }, + ) + + SettingsSubpage.Runtime -> RuntimeSubpageContent( + modes = modes, + currentModeId = currentModeId, + onBack = { subpage = SettingsSubpage.Main }, + onSelect = { modeId -> + onSelectMode(modeId) + subpage = SettingsSubpage.Main + }, + ) + + SettingsSubpage.Main -> Column(modifier = Modifier.fillMaxWidth()) { + // Top Header (`✕` · `会话设置` · `✓`) + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(38.dp) + .shadow(4.dp, CircleShape, ambientColor = Color.Black.copy(alpha = 0.06f)) + .clip(CircleShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, CircleShape) + .clickable(onClick = onDismiss), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.Close, + contentDescription = "关闭", + tint = colors.textPrimary, + modifier = Modifier.size(18.dp), + ) + } + + Spacer(modifier = Modifier.weight(1f)) + + Text( + text = "会话设置", + fontSize = 17.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + + Spacer(modifier = Modifier.weight(1f)) + + Box( + modifier = Modifier + .size(38.dp) + .shadow(4.dp, CircleShape, ambientColor = Color.Black.copy(alpha = 0.12f)) + .clip(CircleShape) + .background(colors.textPrimary) + .clickable { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + onDismiss() + }, + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.Check, + contentDescription = "完成", + tint = colors.bg, + modifier = Modifier.size(18.dp), + ) + } + } + + Column( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 6.dp), + verticalArrangement = Arrangement.spacedBy(18.dp), + ) { + val hasSessionParams = !isSearchingModels && + ((effortOption != null && effortOption.choices.size > 1) || + extraOptions.isNotEmpty() || + modes.isNotEmpty()) + + if (hasSessionParams) { + SessionParametersCard( + effortOption = effortOption, + extraOptions = extraOptions, + modes = modes, + currentModeId = currentModeId, + onSelectEffort = { value -> + effortOption?.let { onSelectOption(it.key, value) } + }, + onOpenEffortSubpage = { subpage = SettingsSubpage.Effort }, + onCycleExtraOption = { opt -> + val idx = opt.choices.indexOfFirst { it.value == opt.value } + val next = opt.choices[(idx + 1).coerceAtLeast(0) % opt.choices.size] + onSelectOption(opt.key, next.value) + }, + onOpenRuntimeSubpage = { subpage = SettingsSubpage.Runtime }, + ) + } + + // Provider-grouped model catalog + val visibleGroups = orderedGroups.mapNotNull { group -> + val filtered = filterGroupChoices( + group = group, + query = searchQuery, + filter = activeFilter, + favoriteIds = favoriteIds, + hiddenIds = hiddenIds, + manageHiddenModels = manageHiddenModels, + ) + if (filtered.isEmpty()) null else group to filtered + } + + if (visibleGroups.isEmpty()) { + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .padding(vertical = 28.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + imageVector = Icons.Rounded.Search, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(24.dp), + ) + Text( + text = "没有匹配的模型", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = colors.textSecondary, + ) + } + } else { + visibleGroups.forEach { (group, rows) -> + val providerFiltered = (activeFilter as? ModelCatalogFilter.Provider) + ?.agentId?.equals(group.agentId, ignoreCase = true) == true + val isCollapsed = group.agentId in collapsedGroupIds && + !isSearchingModels && + !providerFiltered + val hasSelected = rows.any { it.value == group.activeValue } + + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .clickable { + collapsedGroupIds = if (group.agentId in collapsedGroupIds) { + collapsedGroupIds - group.agentId + } else { + collapsedGroupIds + group.agentId + } + } + .padding(horizontal = 4.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(7.dp), + ) { + AgentAvatar( + agentId = group.agentId, + size = 16.dp, + iconSvg = group.iconSvg, + displayName = group.title, + ) + Text( + text = group.title, + fontSize = 13.5.sp, + fontWeight = FontWeight.SemiBold, + color = if (hasSelected) colors.textPrimary else colors.textSecondary, + modifier = Modifier.weight(1f), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (isCollapsed) { + val selectedChoice = rows.firstOrNull { it.value == group.activeValue } + Text( + text = selectedChoice?.label ?: "${rows.size}", + style = TextStyle( + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + fontFeatureSettings = "tnum", + color = if (selectedChoice != null) colors.textSecondary else colors.textTertiary, + ), + maxLines = 1, + ) + } + Icon( + imageVector = if (isCollapsed) Icons.Rounded.ExpandMore else Icons.Rounded.ExpandLess, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(16.dp), + ) + } + + if (!isCollapsed) { + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)), + ) { + rows.forEachIndexed { idx, choice -> + val key = storageKeyForModel(group.agentId, choice) + val isSelected = choice.value == group.activeValue + val isFav = key in favoriteIds + val isHidden = key in hiddenIds + val isDefaultBadge = idx == 0 && + !(choice.description.orEmpty().contains("自定义")) + + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + onSelectAgentAndModel( + group.agentId, + group.modelKey, + choice.value, + ) + } + .padding(horizontal = 16.dp, vertical = 11.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = choice.label, + fontSize = 15.sp, + fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium, + color = if (isHidden) colors.textSecondary else colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (isDefaultBadge) { + SmallBadgePill("默认") + } + } + val desc = choice.description?.takeIf { it.isNotBlank() } + if (desc != null) { + Text( + text = desc, + fontSize = 12.sp, + color = colors.textTertiary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + + if (isSelected) { + Icon( + imageVector = Icons.Rounded.Check, + contentDescription = null, + tint = colors.textPrimary, + modifier = Modifier.size(16.dp), + ) + } + + if (manageHiddenModels) { + Icon( + imageVector = if (isHidden) Icons.Rounded.VisibilityOff else Icons.Rounded.Visibility, + contentDescription = if (isHidden) "取消隐藏模型" else "隐藏模型", + tint = if (isHidden) HiddenOrange else colors.textSecondary, + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .clickable { modelPrefs.toggleHidden(key) } + .padding(5.dp), + ) + } + + Icon( + imageVector = if (isFav) Icons.Rounded.Star else Icons.Rounded.StarOutline, + contentDescription = if (isFav) "取消收藏" else "收藏模型", + tint = if (isFav) StarGold else colors.textTertiary, + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .clickable { modelPrefs.toggleFavorite(key) } + .padding(5.dp), + ) + } + + if (idx < rows.lastIndex) { + HorizontalDivider( + modifier = Modifier.padding(start = 16.dp), + thickness = 0.5.dp, + color = colors.stroke, + ) + } + } + } + } + } + } + } + + // Catalog Management Section (`模型目录`) + if (!isSearchingModels) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = "模型目录", + fontSize = 13.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + modifier = Modifier.padding(horizontal = 4.dp), + ) + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)), + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = "管理隐藏模型", + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + Switch( + checked = manageHiddenModels, + onCheckedChange = { manageHiddenModels = it }, + ) + } + + HorizontalDivider( + modifier = Modifier.padding(start = 16.dp), + thickness = 0.5.dp, + color = colors.stroke, + ) + + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { + customModelDraft = "" + showCustomModelDialog = true + } + .padding(horizontal = 16.dp, vertical = 13.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = "自定义 / 中转模型…", + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + Icon( + imageVector = Icons.Rounded.AddCircleOutline, + contentDescription = null, + tint = colors.accent, + modifier = Modifier.size(18.dp), + ) + } + } + } + } + + Spacer(modifier = Modifier.height(8.dp)) + } + } + } + } + + // Bottom Floating Filter + Search Capsule Bar + if (subpage == SettingsSubpage.Main) { + Row( + modifier = Modifier + .fillMaxWidth() + .background(colors.bg) + .padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Box { + Box( + modifier = Modifier + .size(44.dp) + .shadow(6.dp, CircleShape, ambientColor = Color.Black.copy(alpha = 0.08f)) + .clip(CircleShape) + .background(colors.card) + .border(0.7.dp, colors.stroke, CircleShape) + .clickable { filterMenuExpanded = true }, + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Rounded.FilterList, + contentDescription = "筛选模型", + tint = colors.textPrimary, + modifier = Modifier.size(19.dp), + ) + if (activeFilter != ModelCatalogFilter.All) { + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .offset(x = (-3).dp, y = 3.dp) + .size(8.5.dp) + .clip(CircleShape) + .background(colors.accent), + ) + } + } + + VibexDropdownMenu( + expanded = filterMenuExpanded, + onDismissRequest = { filterMenuExpanded = false }, + ) { + VibexDropdownMenuItem( + text = "全部模型", + selected = activeFilter == ModelCatalogFilter.All, + onClick = { + activeFilter = ModelCatalogFilter.All + filterMenuExpanded = false + }, + ) + VibexDropdownMenuItem( + text = "仅显示收藏", + selected = activeFilter == ModelCatalogFilter.Favorites, + onClick = { + activeFilter = ModelCatalogFilter.Favorites + filterMenuExpanded = false + }, + ) + if (orderedGroups.size > 1) { + VibexDropdownDivider() + orderedGroups.forEach { grp -> + val selected = (activeFilter as? ModelCatalogFilter.Provider) + ?.agentId?.equals(grp.agentId, ignoreCase = true) == true + VibexDropdownMenuItem( + text = grp.title, + selected = selected, + onClick = { + activeFilter = ModelCatalogFilter.Provider(grp.agentId, grp.title) + filterMenuExpanded = false + }, + ) + } + } + } + } + + Row( + modifier = Modifier + .weight(1f) + .height(44.dp) + .shadow(6.dp, CircleShape, ambientColor = Color.Black.copy(alpha = 0.08f)) + .clip(CircleShape) + .background(colors.card) + .border(0.7.dp, colors.stroke, CircleShape) + .padding(horizontal = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Icon( + imageVector = Icons.Rounded.Search, + contentDescription = null, + tint = colors.textSecondary, + modifier = Modifier.size(17.dp), + ) + Box(modifier = Modifier.weight(1f)) { + if (searchQuery.isEmpty()) { + Text( + text = "搜索模型…", + fontSize = 14.5.sp, + color = colors.textTertiary, + ) + } + BasicTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + singleLine = true, + textStyle = TextStyle(fontSize = 14.5.sp, color = colors.textPrimary), + cursorBrush = SolidColor(colors.accent), + modifier = Modifier.fillMaxWidth(), + ) + } + if (searchQuery.isNotEmpty()) { + Icon( + imageVector = Icons.Rounded.Cancel, + contentDescription = "清除", + tint = colors.textTertiary, + modifier = Modifier + .size(16.dp) + .clickable { searchQuery = "" }, + ) + } + } + } + } + } + } + + if (showCustomModelDialog) { + AlertDialog( + onDismissRequest = { showCustomModelDialog = false }, + containerColor = colors.card, + title = { Text("添加自定义 / 中转模型", fontSize = 17.sp, fontWeight = FontWeight.Bold) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = "若桌面端已配置 API 中转或网关,输入模型 ID 即可直接切换。", + fontSize = 13.sp, + color = colors.textSecondary, + ) + OutlinedTextField( + value = customModelDraft, + onValueChange = { customModelDraft = it }, + placeholder = { Text("例如 claude-opus-4-8 / gpt-6-sol", fontSize = 13.5.sp) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + TextButton( + onClick = { + val trimmed = customModelDraft.trim() + showCustomModelDialog = false + if (trimmed.isNotEmpty()) { + modelPrefs.addCustomModel(agentId, trimmed) + onSelectAgentAndModel(agentId, activeModelOption.key.ifBlank { "model" }, trimmed) + } + }, + ) { + Text("使用此模型", fontWeight = FontWeight.SemiBold, color = colors.accent) + } + }, + dismissButton = { + TextButton(onClick = { showCustomModelDialog = false }) { + Text("取消", color = colors.textSecondary) + } + }, + ) + } +} + +@Composable +private fun SessionParametersCard( + effortOption: SessionConfigOption?, + extraOptions: List, + modes: List, + currentModeId: String, + onSelectEffort: (String) -> Unit, + onOpenEffortSubpage: () -> Unit, + onCycleExtraOption: (SessionConfigOption) -> Unit, + onOpenRuntimeSubpage: () -> Unit, +) { + val colors = VibexTheme.colors + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = "会话参数", + fontSize = 13.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + modifier = Modifier.padding(horizontal = 4.dp), + ) + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)), + ) { + if (effortOption != null && effortOption.choices.size > 1) { + val useInline = effortOption.choices.size <= 4 && effortOption.choices.all { it.label.length <= 6 } + if (useInline) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 9.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = "推理强度", + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + Row( + modifier = Modifier + .clip(CircleShape) + .background(colors.segmentedTrack) + .padding(3.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), + ) { + val activeVal = effortOption.value.ifBlank { effortOption.choices.first().value } + effortOption.choices.forEach { choice -> + val selected = choice.value == activeVal + Text( + text = choice.label, + fontSize = 13.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium, + color = if (selected) colors.textPrimary else colors.textSecondary, + modifier = Modifier + .clip(CircleShape) + .background(if (selected) colors.segmentedThumb else Color.Transparent) + .clickable { + if (!selected) onSelectEffort(choice.value) + } + .padding(horizontal = 11.dp, vertical = 5.dp), + ) + } + } + } + } else { + val currentLabel = effortOption.choices.firstOrNull { it.value == effortOption.value }?.label + ?: effortOption.choices.first().label + SettingsDisclosureRow( + label = "推理强度", + value = currentLabel, + onClick = onOpenEffortSubpage, + ) + } + + if (extraOptions.isNotEmpty() || modes.isNotEmpty()) { + HorizontalDivider( + modifier = Modifier.padding(start = 16.dp), + thickness = 0.5.dp, + color = colors.stroke, + ) + } + } + + extraOptions.forEachIndexed { idx, extra -> + val valLabel = extra.choices.firstOrNull { it.value == extra.value }?.label ?: extra.value + SettingsDisclosureRow( + label = extra.label, + value = valLabel, + onClick = { onCycleExtraOption(extra) }, + ) + if (idx < extraOptions.lastIndex || modes.isNotEmpty()) { + HorizontalDivider( + modifier = Modifier.padding(start = 16.dp), + thickness = 0.5.dp, + color = colors.stroke, + ) + } + } + + if (modes.isNotEmpty()) { + val activeMode = modes.firstOrNull { it.id == currentModeId } ?: modes.first() + SettingsDisclosureRow( + label = "运行权限", + value = activeMode.name, + onClick = onOpenRuntimeSubpage, + ) + } + } + } +} + +@Composable +private fun SettingsDisclosureRow( + label: String, + value: String, + onClick: () -> Unit, +) { + val colors = VibexTheme.colors + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 13.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = label, + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + Text( + text = value, + fontSize = 14.5.sp, + color = colors.textSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowRight, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(16.dp), + ) + } +} + +@Composable +private fun EffortSubpageContent( + option: SessionConfigOption?, + onBack: () -> Unit, + onSelect: (String) -> Unit, +) { + val colors = VibexTheme.colors + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) { + SubpageTopHeader(title = "推理强度", onBack = onBack) + Spacer(modifier = Modifier.height(10.dp)) + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)), + ) { + val choices = option?.choices.orEmpty() + choices.forEachIndexed { idx, choice -> + val selected = choice.value == option?.value + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSelect(choice.value) } + .padding(horizontal = 16.dp, vertical = 13.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = choice.label, + fontSize = 15.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + if (selected) { + Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(17.dp)) + } + } + if (idx < choices.lastIndex) { + HorizontalDivider(modifier = Modifier.padding(start = 16.dp), thickness = 0.5.dp, color = colors.stroke) + } + } + } + } +} + +@Composable +private fun RuntimeSubpageContent( + modes: List, + currentModeId: String, + onBack: () -> Unit, + onSelect: (String) -> Unit, +) { + val colors = VibexTheme.colors + val activeId = currentModeId.ifBlank { modes.firstOrNull()?.id.orEmpty() } + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) { + SubpageTopHeader(title = "运行权限", onBack = onBack) + Spacer(modifier = Modifier.height(10.dp)) + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .background(colors.card) + .border(0.6.dp, colors.stroke, RoundedCornerShape(16.dp)), + ) { + modes.forEachIndexed { idx, mode -> + val selected = mode.id == activeId + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onSelect(mode.id) } + .padding(horizontal = 16.dp, vertical = 13.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = mode.name, + fontSize = 15.sp, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = colors.textPrimary, + modifier = Modifier.weight(1f), + ) + if (selected) { + Icon(Icons.Rounded.Check, null, tint = colors.accent, modifier = Modifier.size(17.dp)) + } + } + if (idx < modes.lastIndex) { + HorizontalDivider(modifier = Modifier.padding(start = 16.dp), thickness = 0.5.dp, color = colors.stroke) + } + } + } + } +} + +@Composable +private fun SubpageTopHeader( + title: String, + onBack: () -> Unit, +) { + val colors = VibexTheme.colors + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .background(colors.card) + .border(0.6.dp, colors.stroke, CircleShape) + .clickable(onClick = onBack), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.AutoMirrored.Rounded.KeyboardArrowLeft, + contentDescription = "返回", + tint = colors.textPrimary, + modifier = Modifier.size(20.dp), + ) + } + Spacer(modifier = Modifier.weight(1f)) + Text( + text = title, + fontSize = 17.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, + ) + Spacer(modifier = Modifier.weight(1f)) + Spacer(modifier = Modifier.size(36.dp)) + } +} + +@Composable +private fun SmallBadgePill(label: String) { + val colors = VibexTheme.colors + Text( + text = label, + fontSize = 10.5.sp, + fontWeight = FontWeight.SemiBold, + color = colors.textSecondary, + modifier = Modifier + .clip(CircleShape) + .background(colors.textPrimary.copy(alpha = if (colors.isDark) 0.12f else 0.07f)) + .padding(horizontal = 7.dp, vertical = 2.dp), + ) +} + +private fun filterGroupChoices( + group: ProviderModelGroup, + query: String, + filter: ModelCatalogFilter, + favoriteIds: Set, + hiddenIds: Set, + manageHiddenModels: Boolean, +): List { + if (filter is ModelCatalogFilter.Provider && !filter.agentId.equals(group.agentId, ignoreCase = true)) { + return emptyList() + } + val q = query.trim().lowercase() + val visible = group.choices.filter { choice -> + val key = storageKeyForModel(group.agentId, choice) + val isSelected = choice.value == group.activeValue + if (!manageHiddenModels && !isSelected && key in hiddenIds) return@filter false + if (filter == ModelCatalogFilter.Favorites && key !in favoriteIds && !isSelected) return@filter false + if (q.isEmpty()) return@filter true + choice.label.lowercase().contains(q) || + choice.value.lowercase().contains(q) || + choice.description.orEmpty().lowercase().contains(q) || + group.title.lowercase().contains(q) + } + return visible.sortedWith( + compareByDescending { choice -> storageKeyForModel(group.agentId, choice) in favoriteIds }, + ) +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/TimelineExtras.kt b/app/src/main/java/dev/vibex/companion/app/ui/TimelineExtras.kt new file mode 100644 index 0000000..3201b62 --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/TimelineExtras.kt @@ -0,0 +1,115 @@ +package dev.vibex.companion.app.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.WarningAmber +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.vibex.companion.RateLimitBanner +import dev.vibex.companion.agentDisplayName +import dev.vibex.companion.app.ui.theme.VibexTheme +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** Divider row for cross-engine handoff / fork (`agent_handoff` host note). */ +@Composable +fun HandoffDivider(label: String) { + val colors = VibexTheme.colors + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Box(Modifier.weight(1f).height(0.5.dp).background(colors.textTertiary.copy(alpha = 0.4f))) + Text( + text = label, + color = colors.textTertiary, + fontSize = 11.sp, + textAlign = TextAlign.Center, + modifier = Modifier.weight(4f, fill = false), + ) + Box(Modifier.weight(1f).height(0.5.dp).background(colors.textTertiary.copy(alpha = 0.4f))) + } +} + +/** + * Rate-limit recovery banner. The host's live `conversation-rate-limit` push channel is not part of + * the remote WebSocket, so the banner is derived from the `rate_limited` turn error and the + * actions map to the host commands that exist (cancel wait / auto-resume). + */ +@Composable +fun RateLimitRecoveryBanner( + banner: RateLimitBanner, + agentId: String, + writable: Boolean, + onAutoResume: () -> Unit, + onCancelWait: () -> Unit, +) { + val colors = VibexTheme.colors + val tint = colors.hold + val engine = agentDisplayName(banner.engine.ifBlank { agentId }) + val recovery = when { + banner.resetAtMs != null -> + "预计 ${SimpleDateFormat("MM-dd HH:mm", Locale.getDefault()).format(Date(banner.resetAtMs!!))} 后额度恢复" + banner.retryAfterSeconds != null -> "约 ${banner.retryAfterSeconds} 秒后可重试" + else -> "恢复时间未知" + } + Column( + Modifier + .padding(horizontal = 8.dp, vertical = 4.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(tint.copy(0.12f)) + .border(0.5.dp, tint.copy(0.32f), RoundedCornerShape(12.dp)) + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Icon(Icons.Rounded.WarningAmber, null, tint = tint, modifier = Modifier.size(16.dp)) + Text("$engine 已触发限流", color = colors.textPrimary, fontSize = 14.sp) + } + Text(recovery, color = colors.textSecondary, fontSize = 13.sp) + if (writable) { + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + TextButton(onClick = onAutoResume) { Text("恢复后自动继续", color = colors.accent) } + TextButton(onClick = onCancelWait) { Text("取消等待", color = colors.textSecondary) } + } + } + } +} + +/** One-line honest steering hint shown while a turn is in flight. */ +@Composable +fun SteeringHint(canSteer: Boolean, known: Boolean) { + val colors = VibexTheme.colors + val text = when { + !known -> "正在确认 Agent 是否支持回合纠偏…" + canSteer -> "该 Agent 支持回合纠偏:发送的消息会直接引导当前回合" + else -> "该 Agent 不支持回合纠偏:消息将排队,待当前回合结束后发送" + } + Text( + text = text, + color = colors.textTertiary, + fontSize = 11.sp, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp), + ) +} diff --git a/app/src/main/java/dev/vibex/companion/app/ui/TimelineScreen.kt b/app/src/main/java/dev/vibex/companion/app/ui/TimelineScreen.kt index e1c9ea4..c61573e 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/TimelineScreen.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/TimelineScreen.kt @@ -4,6 +4,7 @@ import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -24,23 +25,11 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBack -import androidx.compose.material.icons.automirrored.rounded.Chat import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight -import androidx.compose.material.icons.rounded.ArrowDownward import androidx.compose.material.icons.rounded.Check import androidx.compose.material.icons.rounded.Close -import androidx.compose.material.icons.rounded.Code import androidx.compose.material.icons.rounded.ContentCopy -import androidx.compose.material.icons.rounded.EditNote -import androidx.compose.material.icons.rounded.Folder -import androidx.compose.material.icons.rounded.Info import androidx.compose.material.icons.rounded.KeyboardArrowDown -import androidx.compose.material.icons.rounded.MoreHoriz -import androidx.compose.material.icons.rounded.Settings -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -48,6 +37,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -61,7 +51,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -69,7 +59,6 @@ import androidx.compose.ui.unit.sp import dev.vibex.companion.CatalogAgent import dev.vibex.companion.FileChangeItem import dev.vibex.companion.QueuedInput -import dev.vibex.companion.SessionConfigOption import dev.vibex.companion.TimelineItem import dev.vibex.companion.TimelineSegment import dev.vibex.companion.agentDisplayName @@ -85,6 +74,9 @@ private val RunningOrange = Color(0xFFFF9500) /** * 1:1 port of iOS `ConversationDetailView` (`ConversationDetailView.swift`). + * Uses `FloatingCircleBackButton` + left-aligned title/model header + `WorkspaceDualToolsCapsule`, + * instant optimistic `isThinkingOrRunning` feedback, auto-mark-viewed when a turn finishes while + * watching, and the unified single-capsule `PromptBar`. */ @Composable fun TimelinePane( @@ -97,6 +89,11 @@ fun TimelinePane( val focusManager = LocalFocusManager.current val scope = rememberCoroutineScope() + val handleBack = remember(onBack, model) { + onBack ?: { model.go(Route.Conversations) } + } + BackHandler(onBack = handleBack) + val view = state.timeline?.takeIf { it.conversationId == conversationId } val summary = state.conversations.find { it.id == conversationId } val agentId = view?.agentId?.takeIf { it.isNotBlank() } ?: summary?.agentId.orEmpty() @@ -119,11 +116,7 @@ fun TimelinePane( val configOptions = view?.sessionConfig?.takeIf { it.isNotEmpty() } ?: agent?.sessionConfig.orEmpty() val currentModelLabel = remember(configOptions, agent, agentId) { - val modelOpt = configOptions.firstOrNull { opt -> - val k = opt.key.lowercase() - val c = opt.category.lowercase() - c == "model" || k == "model" || k.contains("model") - } + val modelOpt = findSettingsModelOption(configOptions) val selected = modelOpt?.choices?.firstOrNull { it.value == modelOpt.value }?.label ?: modelOpt?.value selected?.takeIf { it.isNotBlank() } ?: agent?.displayName?.takeIf { it.isNotBlank() } @@ -131,37 +124,54 @@ fun TimelinePane( } val items = view?.items.orEmpty() - val isTurnRunning = view?.inFlightTurnId != null + val isTurnRunning = view?.isThinkingOrRunning == true var workspaceDiffCount by remember(conversationId, workspaceId) { mutableIntStateOf(0) } - LaunchedEffect(conversationId, workspaceId, isTurnRunning) { - if (workspaceId.isNotBlank() && !isTurnRunning) { - model.fetchWorkspaceDiff(workspaceId, conversationId) { result -> - result.getOrNull()?.let { diffs -> - workspaceDiffCount = diffs.size - } + var workspaceAdditions by remember(conversationId, workspaceId) { mutableLongStateOf(0L) } + var workspaceDeletions by remember(conversationId, workspaceId) { mutableLongStateOf(0L) } + var wasTurnRunning by remember(conversationId) { mutableStateOf(false) } + + fun refreshDiffSummary() { + if (workspaceId.isBlank()) return + model.fetchWorkspaceDiff(workspaceId, conversationId) { result -> + result.getOrNull()?.let { diffs -> + workspaceDiffCount = diffs.size + workspaceAdditions = diffs.sumOf { it.additions.toLong() } + workspaceDeletions = diffs.sumOf { it.deletions.toLong() } + } + } + } + + LaunchedEffect(conversationId, workspaceId) { + refreshDiffSummary() + } + + LaunchedEffect(conversationId, isTurnRunning) { + if (wasTurnRunning && !isTurnRunning) { + if (view?.permissionPrompt == null && view?.pendingQuestion == null) { + model.markSessionViewed(conversationId) } + refreshDiffSummary() } + wasTurnRunning = isTurnRunning } + val totalChangeCount = remember(workspaceDiffCount, view?.fileChanges, items) { val turnChanges = items.flatMap { it.changes }.map { it.path }.toSet().size maxOf(workspaceDiffCount, view?.fileChanges?.size ?: 0, turnChanges) } - var input by remember(conversationId) { mutableStateOf("") } - var menu by remember(conversationId) { mutableStateOf(null) } - BackHandler(enabled = menu != null) { - menu = null - } var respondingPermission by remember(conversationId) { mutableStateOf(false) } var respondingQuestion by remember(conversationId) { mutableStateOf(false) } + var openSettingsTrigger by remember(conversationId) { mutableIntStateOf(0) } var showFiles by remember { mutableStateOf(false) } var showDiff by remember { mutableStateOf(false) } var diffTarget by remember { mutableStateOf(null) } var showSessionSheet by remember { mutableStateOf(false) } - var showNewConvSheet by remember { mutableStateOf(false) } - var moreMenuExpanded by remember { mutableStateOf(false) } + var showMoreMenu by remember { mutableStateOf(false) } + var showHandoff by remember { mutableStateOf(false) } + var showSideChat by remember { mutableStateOf(false) } val listState = rememberLazyListState() var pinnedToBottom by remember(conversationId) { mutableStateOf(true) } @@ -191,7 +201,7 @@ fun TimelinePane( val tailSignature = remember(items, isTurnRunning) { val last = items.lastOrNull() - "${items.size}:${last?.id}:${last?.text?.length}:${last?.thinking?.length}:${last?.tools?.size}:${isTurnRunning}" + "${items.size}:${last?.id}:${last?.text?.length}:${last?.thinking?.length}:${last?.tools?.size}:$isTurnRunning" } LaunchedEffect(tailSignature) { @@ -207,154 +217,128 @@ fun TimelinePane( val conversationTitle = view?.title?.takeIf { it.isNotBlank() } ?: summary?.title?.takeIf { it.isNotBlank() } - ?: "对话" + ?: "未命名会话" Column( modifier = Modifier .fillMaxSize() + .background(colors.bg) .navigationBarsPadding() .imePadding(), ) { - // Embedded Header Bar (1:1 iOS `embeddedHeaderBar`) + // Level-2 Header Bar (1:1 iOS `levelTwoHeaderBar`) Row( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 8.dp), - horizontalArrangement = Arrangement.spacedBy(10.dp), + .padding(horizontal = 14.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, ) { - Box( - modifier = Modifier - .size(36.dp) - .clip(CircleShape) - .background(colors.card) - .border(0.6.dp, colors.textPrimary.copy(alpha = 0.08f), CircleShape) - .clickable { - if (onBack != null) onBack() else model.openNewChatLanding() - }, - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.AutoMirrored.Rounded.ArrowBack, - contentDescription = "返回对话列表", - tint = colors.textPrimary, - modifier = Modifier.size(17.dp), - ) - } + FloatingCircleBackButton(onClick = handleBack) Column( modifier = Modifier.weight(1f), - horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(2.dp), ) { Row( + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { showSessionSheet = true }, horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, ) { if (isTurnRunning) { Box( modifier = Modifier - .size(6.5.dp) + .size(7.dp) .clip(CircleShape) .background(RunningOrange), ) } Text( text = conversationTitle, - fontSize = 15.5.sp, - fontWeight = FontWeight.SemiBold, + fontSize = 16.5.sp, + fontWeight = FontWeight.Bold, color = colors.textPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } + Row( - horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { openSettingsTrigger += 1 }, + horizontalArrangement = Arrangement.spacedBy(4.5.dp), verticalAlignment = Alignment.CenterVertically, ) { AgentAvatar( agentId = agentId, - size = 11.dp, + size = 11.5.dp, iconSvg = agent?.iconSvg, displayName = agent?.displayName.orEmpty(), ) Text( text = currentModelLabel, - fontSize = 11.sp, + fontSize = 11.5.sp, fontWeight = FontWeight.Medium, color = colors.textSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis, ) + Icon( + imageVector = Icons.Rounded.KeyboardArrowDown, + contentDescription = null, + tint = colors.textTertiary, + modifier = Modifier.size(12.dp), + ) } } - Row( - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Box( + WorkspaceDualToolsCapsule( + diffCount = totalChangeCount, + additionCount = workspaceAdditions, + deletionCount = workspaceDeletions, + enabled = workspaceId.isNotBlank(), + onOpenDiff = { showDiff = true }, + onOpenFiles = { showFiles = true }, + ) + + Box { + Text( + text = "⋯", + fontSize = 22.sp, + fontWeight = FontWeight.Bold, + color = colors.textPrimary, modifier = Modifier - .size(36.dp) .clip(CircleShape) - .background(colors.card) - .border(0.6.dp, colors.textPrimary.copy(alpha = 0.08f), CircleShape) - .clickable { model.openNewChatLanding() }, - contentAlignment = Alignment.Center, + .clickable { showMoreMenu = true } + .padding(horizontal = 8.dp), + ) + androidx.compose.material3.DropdownMenu( + expanded = showMoreMenu, + onDismissRequest = { showMoreMenu = false }, ) { - Icon( - imageVector = Icons.Rounded.EditNote, - contentDescription = "新建对话", - tint = colors.textPrimary, - modifier = Modifier.size(17.dp), + androidx.compose.material3.DropdownMenuItem( + text = { Text("切换引擎…") }, + enabled = state.connection.allowsWrites && !isTurnRunning, + onClick = { + showMoreMenu = false + model.openHandoff(conversationId) + showHandoff = true + }, + ) + androidx.compose.material3.DropdownMenuItem( + text = { Text("旁路对话") }, + onClick = { + showMoreMenu = false + showSideChat = true + }, ) - } - - Box { - Box( - modifier = Modifier - .size(36.dp) - .clip(CircleShape) - .background(colors.card) - .border(0.6.dp, colors.textPrimary.copy(alpha = 0.08f), CircleShape) - .clickable { moreMenuExpanded = true }, - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.Rounded.MoreHoriz, - contentDescription = "更多操作", - tint = colors.textPrimary, - modifier = Modifier.size(17.dp), - ) - } - - DropdownMenu( - expanded = moreMenuExpanded, - onDismissRequest = { moreMenuExpanded = false }, - ) { - DropdownMenuItem( - text = { Text("查看代码变更 (Diff)", fontSize = 14.sp) }, - leadingIcon = { Icon(Icons.Rounded.Code, null, modifier = Modifier.size(18.dp)) }, - onClick = { - moreMenuExpanded = false - showDiff = true - }, - ) - DropdownMenuItem( - text = { Text("会话信息与操作", fontSize = 14.sp) }, - leadingIcon = { Icon(Icons.Rounded.Info, null, modifier = Modifier.size(18.dp)) }, - onClick = { - moreMenuExpanded = false - showSessionSheet = true - }, - ) - } } } } - HorizontalDivider(thickness = 0.5.dp, color = colors.stroke) - // Session Notices view?.notices.orEmpty().forEach { item -> SessionNoticeCard( @@ -364,16 +348,25 @@ fun TimelinePane( ) } + view?.rateLimit?.let { limit -> + RateLimitRecoveryBanner( + banner = limit, + agentId = agentId, + writable = state.connection.allowsWrites, + onAutoResume = { model.setRateLimitAutoResume(conversationId, true) }, + onCancelWait = { model.cancelRateLimitWait(conversationId) }, + ) + } + // Main Timeline + Floating Scroll-to-Bottom Button Box( modifier = Modifier .weight(1f) .fillMaxWidth() .clickable( - interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }, + interactionSource = remember { MutableInteractionSource() }, indication = null, ) { - if (menu != null) menu = null focusManager.clearFocus() }, ) { @@ -385,7 +378,7 @@ fun TimelinePane( contentAlignment = Alignment.Center, ) { Text( - text = "发送第一条消息开始对话", + text = "还没有消息", fontSize = 14.sp, color = colors.textSecondary, ) @@ -501,53 +494,47 @@ fun TimelinePane( ) } - if (totalChangeCount > 0) { - ChangesSummaryBar( - count = totalChangeCount, - onOpenDiff = { showDiff = true }, - onOpenFiles = { showFiles = true }, - modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), - ) + if (isTurnRunning) { + SteeringHint(canSteer = view?.canSteer == true, known = view?.steeringKnown == true) } - // PromptBar (`PromptBar.kt`) + // Unified Single-Capsule PromptBar (`PromptBar.kt`) PromptBar( - text = input, - onTextChange = { input = it }, - menu = menu, - onMenuChange = { menu = it }, + conversationKey = conversationId, agentId = agentId, agent = agent, agents = state.catalog?.agents.orEmpty(), - onAddCustomModel = { rawModel -> - val trimmed = rawModel.trim() - if (trimmed.isNotEmpty()) { - val modelKey = configOptions.firstOrNull { - val k = it.key.lowercase() - val c = it.category.lowercase() - c == "model" || k == "model" || k.contains("model") - }?.key ?: "model" - model.setSessionConfig(conversationId, modelKey, trimmed) - } - }, + allowCrossAgentSwitch = false, modes = modes, currentModeId = currentModeId, configOptions = configOptions, + modelPrefs = model.modelPrefs, isStreaming = isTurnRunning, + hasAlert = view?.permissionPrompt != null, enabled = state.connection.allowsWrites, - onSend = { - val trimmed = input.trim() - if (trimmed.isNotEmpty()) { - input = "" - pinnedToBottom = true - unreadUpdates = 0 - model.send(conversationId, trimmed) + openSettingsTrigger = openSettingsTrigger, + onSubmit = { text -> + pinnedToBottom = true + unreadUpdates = 0 + if (isTurnRunning && view?.canSteer == true) { + model.steer(conversationId, text) + } else { + model.send(conversationId, text) } }, onStop = { model.cancel(conversationId) }, + onSelectAgentAndModel = { _, key, value -> + model.setSessionConfig(conversationId, key, value) + }, onSelectMode = { modeId -> model.setSessionMode(conversationId, modeId) }, onSelectOption = { key, value -> model.setSessionConfig(conversationId, key, value) }, - onOpenFileBrowser = { showFiles = true }, + onOpenFileBrowser = if (workspaceId.isNotBlank()) { + { showFiles = true } + } else { + null + }, + onCompact = { model.compact(conversationId) }, + onRefreshCatalog = { model.loadCatalogSilent() }, ) } @@ -581,20 +568,30 @@ fun TimelinePane( ) } - if (showSessionSheet) { - SessionInfoSheet( + if (showHandoff) { + dev.vibex.companion.app.ui.timeline.EngineHandoffSheet( state = state, + currentAgentId = agentId, + model = model, + onDismiss = { showHandoff = false }, + ) + } + + if (showSideChat) { + dev.vibex.companion.app.ui.timeline.SideChatSheet( conversationId = conversationId, + items = items, model = model, - onDismiss = { showSessionSheet = false }, + onDismiss = { showSideChat = false }, ) } - if (showNewConvSheet) { - NewConversationSheet( + if (showSessionSheet) { + SessionInfoSheet( state = state, + conversationId = conversationId, model = model, - onDismiss = { showNewConvSheet = false }, + onDismiss = { showSessionSheet = false }, ) } } @@ -612,6 +609,7 @@ fun MessageRow( val colors = VibexTheme.colors when (item.role) { + TimelineItem.Role.Divider -> HandoffDivider(item.text) TimelineItem.Role.User -> { Row( modifier = Modifier.fillMaxWidth(), @@ -666,7 +664,6 @@ fun MessageRow( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp), ) { - // Desktop-style `> Worked for Xh Ym` Collapsible Process Group (`MessageTurnView.tsx:537-595`) if (hasProcessSteps) { Row( modifier = Modifier @@ -686,9 +683,12 @@ fun MessageRow( ) Text( text = workedForLabel, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - color = colors.textSecondary, + style = TextStyle( + fontSize = 13.sp, + fontWeight = FontWeight.Medium, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), ) if (item.streaming) { Box( @@ -741,7 +741,6 @@ fun MessageRow( } } - // Assistant Markdown Answer textSegments.forEachIndexed { idx, segment -> val isLastText = idx == textSegments.lastIndex StreamingMessageText( @@ -759,62 +758,6 @@ fun MessageRow( } } -@Composable -private fun ChangesSummaryBar( - count: Int, - onOpenDiff: () -> Unit, - onOpenFiles: () -> Unit, - modifier: Modifier = Modifier, -) { - val colors = VibexTheme.colors - Row( - modifier = modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - modifier = Modifier - .clip(CircleShape) - .background(colors.card) - .border(0.75.dp, colors.textPrimary.copy(alpha = 0.10f), CircleShape) - .clickable(onClick = onOpenDiff) - .padding(horizontal = 10.dp, vertical = 5.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon( - imageVector = Icons.Rounded.Settings, - contentDescription = null, - tint = colors.textSecondary, - modifier = Modifier.size(12.dp), - ) - Text( - text = "$count CHANGES", - fontSize = 11.5.sp, - fontWeight = FontWeight.SemiBold, - fontFamily = FontFamily.Monospace, - color = colors.textPrimary.copy(alpha = 0.88f), - ) - } - - Box( - modifier = Modifier - .size(26.dp) - .clip(RoundedCornerShape(6.dp)) - .background(colors.card) - .clickable(onClick = onOpenFiles), - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.Rounded.Folder, - contentDescription = "浏览文件", - tint = colors.textSecondary, - modifier = Modifier.size(14.dp), - ) - } - } -} - private fun orderedSegments(item: TimelineItem): List { if (item.segments.isNotEmpty()) return item.segments val fallback = mutableListOf() @@ -938,9 +881,12 @@ private fun ScrollToBottomButton( if (label != null) { Text( text = label, - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textPrimary, + style = TextStyle( + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + fontFeatureSettings = "tnum", + color = colors.textPrimary, + ), ) } Icon( @@ -971,9 +917,12 @@ private fun QueuedStrip( ) { Text( text = "排队中 (${items.size})", - fontSize = 11.5.sp, - fontWeight = FontWeight.SemiBold, - color = colors.textSecondary, + style = TextStyle( + fontSize = 11.5.sp, + fontWeight = FontWeight.SemiBold, + fontFeatureSettings = "tnum", + color = colors.textSecondary, + ), ) items.forEach { item -> Row( diff --git a/app/src/main/java/dev/vibex/companion/app/ui/theme/Appearance.kt b/app/src/main/java/dev/vibex/companion/app/ui/theme/Appearance.kt index c3485ec..2f37c59 100644 --- a/app/src/main/java/dev/vibex/companion/app/ui/theme/Appearance.kt +++ b/app/src/main/java/dev/vibex/companion/app/ui/theme/Appearance.kt @@ -1,5 +1,8 @@ package dev.vibex.companion.app.ui.theme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.compositionLocalOf + enum class Appearance(val id: String) { Light("light"), Dark("dark"), @@ -9,3 +12,20 @@ enum class Appearance(val id: String) { fun from(id: String?): Appearance = entries.firstOrNull { it.id == id } ?: System } } + +enum class AppLanguage(val id: String) { + ZhHans("zh-Hans"), + En("en"); + + companion object { + fun from(id: String?): AppLanguage = entries.firstOrNull { it.id == id } ?: ZhHans + } +} + +val LocalAppLanguage = compositionLocalOf { AppLanguage.ZhHans } + +val LocalConfirmHighRiskApproval = compositionLocalOf { true } + +@Composable +fun l(zh: String, en: String): String = + if (LocalAppLanguage.current == AppLanguage.En) en else zh diff --git a/app/src/main/java/dev/vibex/companion/app/ui/timeline/HandoffSideChatSheets.kt b/app/src/main/java/dev/vibex/companion/app/ui/timeline/HandoffSideChatSheets.kt new file mode 100644 index 0000000..d98aa6c --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/ui/timeline/HandoffSideChatSheets.kt @@ -0,0 +1,227 @@ +package dev.vibex.companion.app.ui.timeline + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import dev.vibex.companion.TimelineItem +import dev.vibex.companion.agentDisplayName +import dev.vibex.companion.app.CompanionModel +import dev.vibex.companion.app.UiState +import dev.vibex.companion.app.ui.AgentAvatar +import dev.vibex.companion.app.ui.theme.VibexTheme +import dev.vibex.companion.instancesForAgent + +private val Shape = RoundedCornerShape(12.dp) + +@Composable +private fun ChoiceRow(selected: Boolean, enabled: Boolean = true, onClick: () -> Unit, content: @Composable () -> Unit) { + val colors = VibexTheme.colors + Row( + modifier = Modifier + .fillMaxWidth() + .clip(Shape) + .background(colors.card) + .border(if (selected) 1.2.dp else 0.6.dp, if (selected) colors.textPrimary else colors.stroke, Shape) + .clickable(enabled = enabled, onClick = onClick) + .padding(horizontal = 12.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { content() } +} + +@Composable +private fun PrimaryButton(label: String, enabled: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier) { + val colors = VibexTheme.colors + Box( + modifier = modifier + .clip(Shape) + .background(if (enabled) colors.accent else colors.card) + .clickable(enabled = enabled, onClick = onClick) + .padding(horizontal = 16.dp, vertical = 11.dp), + contentAlignment = Alignment.Center, + ) { + Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (enabled) colors.onAccent else colors.textTertiary) + } +} + +@Composable +fun EngineHandoffSheet(state: UiState, currentAgentId: String, model: CompanionModel, onDismiss: () -> Unit) { + val colors = VibexTheme.colors + val h by model.handoff.collectAsState() + val writable = state.connection.allowsWrites + val engines = state.catalog?.agents.orEmpty().filter { it.usable && !it.id.equals(currentAgentId, true) || (it.usable && it.id.equals(currentAgentId, true) && instancesForAgent(h.instances, it.id).size > 1) } + val instances = instancesForAgent(h.instances, h.targetEngine) + + DraggableSheet(title = "切换引擎", onDismiss = { model.closeHandoff(); onDismiss() }) { + Column( + modifier = Modifier.fillMaxWidth().heightIn(max = 560.dp).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (h.done) { + Text("已切换到 ${agentDisplayName(h.targetEngine, "")}。下一轮将由新引擎接手,并带上交接上下文。", fontSize = 14.sp, color = colors.textPrimary) + PrimaryButton("完成", true, { model.closeHandoff(); onDismiss() }, Modifier.fillMaxWidth()) + return@Column + } + Text("目标引擎", fontSize = 12.sp, color = colors.textTertiary, fontWeight = FontWeight.SemiBold) + if (state.catalog == null) { + Text("正在读取引擎列表…", fontSize = 13.sp, color = colors.textTertiary) + } else if (engines.isEmpty()) { + Text("没有其他可用引擎。请先在电脑端安装并登录其他智能体。", fontSize = 13.sp, color = colors.textTertiary) + } + engines.forEach { a -> + ChoiceRow(selected = a.id == h.targetEngine, enabled = !h.busy, onClick = { + val inst = instancesForAgent(h.instances, a.id) + model.selectHandoffTarget(a.id, inst.firstOrNull { it.isDefault }?.instanceId ?: inst.singleOrNull()?.instanceId) + }) { + AgentAvatar(a.id, 26.dp, a.iconSvg, a.displayName) + Text(a.displayName.ifBlank { agentDisplayName(a.id, "") }, fontSize = 14.5.sp, color = colors.textPrimary, modifier = Modifier.weight(1f)) + if (a.id.equals(currentAgentId, true)) Text("当前", fontSize = 11.sp, color = colors.textTertiary) + } + } + + if (h.targetEngine.isNotBlank()) { + Text("账号实例", fontSize = 12.sp, color = colors.textTertiary, fontWeight = FontWeight.SemiBold) + when { + h.loadingInstances -> Text("正在读取账号实例…", fontSize = 13.sp, color = colors.textTertiary) + h.instancesError != null -> Text("无法读取账号实例(${h.instancesError}),将使用默认账号。", fontSize = 13.sp, color = colors.textTertiary) + instances.isEmpty() -> Text("该引擎没有额外账号实例,使用默认账号。", fontSize = 13.sp, color = colors.textTertiary) + } + instances.forEach { i -> + ChoiceRow(selected = i.instanceId == h.targetInstanceId, enabled = !h.busy, onClick = { + model.selectHandoffTarget(h.targetEngine, i.instanceId) + }) { + Text(i.displayName, fontSize = 14.sp, color = colors.textPrimary, modifier = Modifier.weight(1f)) + if (i.isDefault) Text("默认", fontSize = 11.sp, color = colors.textTertiary) + } + } + } + + h.preview?.let { p -> + Column( + modifier = Modifier.fillMaxWidth().clip(Shape).background(colors.card).padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text("交接预览", fontSize = 12.sp, color = colors.textTertiary, fontWeight = FontWeight.SemiBold) + Text("打包 ${p.packedCount} 条消息,省略 ${p.omittedCount} 条", fontSize = 13.sp, color = colors.textPrimary) + Text("约 ${p.totalTokens} / ${p.tokenBudget} tokens", fontSize = 13.sp, color = colors.textPrimary) + if (p.promptText.isNotBlank()) { + Text(p.promptText.take(600) + if (p.promptText.length > 600) "…" else "", fontSize = 12.sp, color = colors.textTertiary) + } + } + } + h.error?.let { Text(it, fontSize = 13.sp, color = colors.danger) } + if (!writable) Text("当前为只读连接,无法执行切换。", fontSize = 13.sp, color = colors.textTertiary) + + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { + PrimaryButton( + if (h.busy && h.preview == null) "预览中…" else "预览", + enabled = h.targetEngine.isNotBlank() && !h.busy, + onClick = { model.previewHandoff() }, + modifier = Modifier.weight(1f), + ) + PrimaryButton( + if (h.busy && h.preview != null) "切换中…" else "确认切换", + enabled = h.preview != null && !h.busy && writable, + onClick = { model.confirmHandoff() }, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +@Composable +fun SideChatSheet(conversationId: String, items: List, model: CompanionModel, onDismiss: () -> Unit) { + val colors = VibexTheme.colors + val all by model.sideChats.collectAsState() + val chat = all[conversationId] + val messages = chat?.messages.orEmpty() + val sending = chat?.sending == true + var input by remember { mutableStateOf("") } + val scroll = rememberScrollState() + LaunchedEffect(messages.size, sending) { scroll.animateScrollTo(scroll.maxValue) } + + DraggableSheet(title = "旁路对话", onDismiss = onDismiss) { + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + "只读问答,不会写入当前会话,也不会打断正在进行的回合。结果在完成后一次性返回(手机端不显示流式输出)。", + fontSize = 12.sp, color = colors.textTertiary, + ) + Column( + modifier = Modifier.fillMaxWidth().heightIn(min = 120.dp, max = 380.dp).verticalScroll(scroll), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + messages.forEach { m -> + val mine = m.role == "user" + Row(Modifier.fillMaxWidth(), horizontalArrangement = if (mine) Arrangement.End else Arrangement.Start) { + Column( + modifier = Modifier.clip(Shape).background(if (m.isError) colors.danger.copy(alpha = 0.14f) else colors.card).padding(horizontal = 12.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text(m.content, fontSize = 14.sp, color = if (m.isError) colors.danger else colors.textPrimary) + m.toolCalls.forEach { t -> + Text("${t.name} · ${t.status}" + if (t.summary.isNotBlank()) " — ${t.summary.take(80)}" else "", fontSize = 11.sp, color = colors.textTertiary) + } + } + } + } + if (sending) Text("思考中…(最长 3 分钟)", fontSize = 13.sp, color = colors.textTertiary) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Box(Modifier.weight(1f).clip(Shape).background(colors.card).padding(horizontal = 12.dp, vertical = 10.dp)) { + if (input.isEmpty()) Text("问点别的…", fontSize = 14.sp, color = colors.textTertiary) + BasicTextField( + value = input, + onValueChange = { input = it }, + enabled = !sending, + textStyle = TextStyle(fontSize = 14.sp, color = colors.textPrimary), + cursorBrush = SolidColor(colors.textPrimary), + modifier = Modifier.fillMaxWidth(), + ) + } + if (sending) { + PrimaryButton("中止", true, { model.abortSideChat(conversationId) }) + } else { + PrimaryButton("发送", input.isNotBlank(), { + model.sendSideChat(conversationId, input, items) + input = "" + }) + } + } + if (messages.isNotEmpty() && !sending) { + Text("清空对话", fontSize = 12.sp, color = colors.textTertiary, modifier = Modifier.clickable { model.clearSideChat(conversationId) }) + } + Spacer(Modifier.size(4.dp)) + } + } +} diff --git a/app/src/main/java/dev/vibex/companion/app/update/AppUpdateManager.kt b/app/src/main/java/dev/vibex/companion/app/update/AppUpdateManager.kt new file mode 100644 index 0000000..75ce50d --- /dev/null +++ b/app/src/main/java/dev/vibex/companion/app/update/AppUpdateManager.kt @@ -0,0 +1,505 @@ +package dev.vibex.companion.app.update + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.provider.Settings +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import androidx.core.content.FileProvider +import dev.vibex.companion.app.BuildConfig +import dev.vibex.companion.app.MainActivity +import dev.vibex.companion.app.R +import dev.vibex.companion.app.data.VibeXAccountRepository +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import okhttp3.Request +import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream +import java.security.MessageDigest +import java.util.concurrent.TimeUnit + +data class MobileReleaseInfo( + val id: String, + val version: String, + val buildNumber: Int, + val changelog: String, + val forceUpdate: Boolean, + val publishedAt: String, + val apkUrl: String, + val apkSize: Long, + val apkSha256: String, +) { + val releaseKey: String + get() = "${version}_${buildNumber}" +} + +sealed interface ApkDownloadState { + data object Idle : ApkDownloadState + data class Downloading( + val downloadedBytes: Long, + val totalBytes: Long, + val progress: Float, + ) : ApkDownloadState + data class PendingInstallPermission(val apkFile: File) : ApkDownloadState + data class ReadyToInstall(val apkFile: File) : ApkDownloadState + data class Error(val message: String) : ApkDownloadState +} + +data class AppUpdateUiState( + val currentVersionName: String = BuildConfig.VERSION_NAME, + val currentVersionCode: Int = BuildConfig.VERSION_CODE, + val checking: Boolean = false, + val hasUpdate: Boolean = false, + val release: MobileReleaseInfo? = null, + val dialogVisible: Boolean = false, + val downloadState: ApkDownloadState = ApkDownloadState.Idle, + val statusToast: String? = null, +) + +class AppUpdateManager private constructor(private val appContext: Context) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val prefs = appContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + private val httpClient = OkHttpClient.Builder() + .connectTimeout(12, TimeUnit.SECONDS) + .readTimeout(120, TimeUnit.SECONDS) + .build() + + private val _state = MutableStateFlow(AppUpdateUiState()) + val state: StateFlow = _state.asStateFlow() + + private var lastAutoCheckMs: Long = 0L + private var downloadJob: Job? = null + + init { + ensureNotificationChannel() + scope.launch(Dispatchers.IO) { + cleanupInstalledOrObsoleteApks() + } + } + + fun checkIfDue(fromBackground: Boolean = false) { + val now = System.currentTimeMillis() + val interval = if (fromBackground) BACKGROUND_CHECK_INTERVAL_MS else FOREGROUND_CHECK_INTERVAL_MS + if (now - lastAutoCheckMs < interval) return + lastAutoCheckMs = now + checkForUpdate(manual = false, fromBackground = fromBackground) + } + + fun checkForUpdate(manual: Boolean = false, fromBackground: Boolean = false) { + if (_state.value.checking) return + _state.update { it.copy(checking = true, statusToast = null) } + scope.launch { + val result = withContext(Dispatchers.IO) { fetchLatestAndroidRelease() } + result.fold( + onSuccess = { (release, hasUpdate) -> + if (release != null && hasUpdate && release.apkUrl.isNotBlank()) { + val dismissedKey = prefs.getString(KEY_DISMISSED_RELEASE, "") ?: "" + val shouldPopDialog = !fromBackground && ( + manual || release.forceUpdate || dismissedKey != release.releaseKey + ) + _state.update { prev -> + prev.copy( + checking = false, + hasUpdate = true, + release = release, + dialogVisible = prev.dialogVisible || shouldPopDialog, + ) + } + maybePostUpdateNotification(release, forceNotify = fromBackground) + } else { + _state.update { prev -> + prev.copy( + checking = false, + hasUpdate = false, + release = release, + dialogVisible = false, + statusToast = if (manual) "当前已是最新版本 v${BuildConfig.VERSION_NAME}" else null, + ) + } + } + }, + onFailure = { + _state.update { prev -> + prev.copy( + checking = false, + statusToast = if (manual) "检查更新失败,请稍后重试" else null, + ) + } + }, + ) + } + } + + fun openUpdateDialog() { + val rel = _state.value.release + if (_state.value.hasUpdate && rel != null) { + _state.update { it.copy(dialogVisible = true) } + } else { + checkForUpdate(manual = true) + } + } + + fun dismissDialog() { + val rel = _state.value.release + if (rel?.forceUpdate == true) return + if (rel != null) { + prefs.edit().putString(KEY_DISMISSED_RELEASE, rel.releaseKey).apply() + } + _state.update { it.copy(dialogVisible = false) } + } + + fun consumeStatusToast() { + _state.update { it.copy(statusToast = null) } + } + + fun startDownloadAndInstall() { + val release = _state.value.release ?: return + if (downloadJob?.isActive == true) return + + val existingState = _state.value.downloadState + if (existingState is ApkDownloadState.ReadyToInstall && existingState.apkFile.exists()) { + installOrRequestPermission(existingState.apkFile) + return + } + if (existingState is ApkDownloadState.PendingInstallPermission && existingState.apkFile.exists()) { + installOrRequestPermission(existingState.apkFile) + return + } + + downloadJob = scope.launch { + _state.update { + it.copy( + downloadState = ApkDownloadState.Downloading( + downloadedBytes = 0L, + totalBytes = release.apkSize, + progress = 0f, + ), + ) + } + val outcome = withContext(Dispatchers.IO) { + downloadAndVerifyApk(release) { downloaded, total -> + val frac = if (total > 0L) (downloaded.toFloat() / total.toFloat()).coerceIn(0f, 1f) else 0f + _state.update { prev -> + prev.copy( + downloadState = ApkDownloadState.Downloading( + downloadedBytes = downloaded, + totalBytes = total, + progress = frac, + ), + ) + } + } + } + outcome.fold( + onSuccess = { apkFile -> + installOrRequestPermission(apkFile) + }, + onFailure = { err -> + _state.update { + it.copy( + downloadState = ApkDownloadState.Error( + err.message?.takeIf { m -> m.isNotBlank() } ?: "安装包下载失败,请重试", + ), + ) + } + }, + ) + } + } + + fun onActivityResumed() { + val current = _state.value.downloadState + if (current is ApkDownloadState.PendingInstallPermission && current.apkFile.exists()) { + if (canInstallPackages()) { + launchSystemInstaller(current.apkFile) + } + } + } + + private fun installOrRequestPermission(apkFile: File) { + if (!canInstallPackages()) { + _state.update { + it.copy(downloadState = ApkDownloadState.PendingInstallPermission(apkFile)) + } + runCatching { + val intent = Intent( + Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:${appContext.packageName}"), + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + appContext.startActivity(intent) + }.onFailure { + _state.update { + it.copy(downloadState = ApkDownloadState.Error("无法打开安装未知应用授权设置,请在系统设置中手动开启")) + } + } + return + } + launchSystemInstaller(apkFile) + } + + private fun launchSystemInstaller(apkFile: File) { + _state.update { it.copy(downloadState = ApkDownloadState.ReadyToInstall(apkFile)) } + runCatching { + val uri = FileProvider.getUriForFile( + appContext, + "${appContext.packageName}.fileprovider", + apkFile, + ) + val installIntent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + appContext.startActivity(installIntent) + }.onFailure { + _state.update { + it.copy(downloadState = ApkDownloadState.Error("无法调起系统安装器,请重试")) + } + } + } + + private fun canInstallPackages(): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + appContext.packageManager.canRequestPackageInstalls() + } else { + true + } + } + + private fun downloadAndVerifyApk( + release: MobileReleaseInfo, + onProgress: (downloaded: Long, total: Long) -> Unit, + ): Result = runCatching { + val updatesDir = File(appContext.cacheDir, "updates").apply { mkdirs() } + val safeVer = release.version.replace(Regex("[^0-9A-Za-z._-]"), "_") + val targetFile = File(updatesDir, "vibex-${safeVer}-b${release.buildNumber}.apk") + if (targetFile.exists() && targetFile.length() > 1024L) { + if (release.apkSha256.isBlank() || sha256File(targetFile).equals(release.apkSha256, ignoreCase = true)) { + onProgress(targetFile.length(), targetFile.length()) + return@runCatching targetFile + } + targetFile.delete() + } + + val partFile = File(updatesDir, "${targetFile.name}.part") + if (partFile.exists()) partFile.delete() + + val req = Request.Builder().url(release.apkUrl).get().build() + httpClient.newCall(req).execute().use { resp -> + if (!resp.isSuccessful) { + throw IllegalStateException("下载请求失败(HTTP ${resp.code})") + } + val body = resp.body ?: throw IllegalStateException("服务器返回空安装包") + val total = body.contentLength().takeIf { it > 0L } ?: release.apkSize + val digest = MessageDigest.getInstance("SHA-256") + var downloaded = 0L + var lastEmit = 0L + + body.byteStream().use { input -> + FileOutputStream(partFile).use { output -> + val buffer = ByteArray(32 * 1024) + while (true) { + val read = input.read(buffer) + if (read <= 0) break + output.write(buffer, 0, read) + digest.update(buffer, 0, read) + downloaded += read + val now = System.currentTimeMillis() + if (now - lastEmit >= 60L) { + lastEmit = now + onProgress(downloaded, total) + } + } + output.flush() + } + } + onProgress(downloaded, total) + + val actualHash = digest.digest().joinToString("") { "%02x".format(it) } + if (release.apkSha256.isNotBlank() && !actualHash.equals(release.apkSha256, ignoreCase = true)) { + partFile.delete() + throw IllegalStateException("安装包完整性校验未通过,请重新下载") + } + } + + if (targetFile.exists()) targetFile.delete() + if (!partFile.renameTo(targetFile)) { + partFile.copyTo(targetFile, overwrite = true) + partFile.delete() + } + targetFile + } + + private fun sha256File(file: File): String { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().use { input -> + val buf = ByteArray(32 * 1024) + while (true) { + val n = input.read(buf) + if (n <= 0) break + digest.update(buf, 0, n) + } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } + + private fun fetchLatestAndroidRelease(): Result> = runCatching { + val url = "${VibeXAccountRepository.SITE_BASE_URL}/api/mobile/releases/latest" + + "?platform=android&version=${Uri.encode(BuildConfig.VERSION_NAME)}&build=${BuildConfig.VERSION_CODE}" + val req = Request.Builder() + .url(url) + .header("Accept", "application/json") + .get() + .build() + httpClient.newCall(req).execute().use { resp -> + if (!resp.isSuccessful) { + throw IllegalStateException("HTTP ${resp.code}") + } + val raw = resp.body?.string().orEmpty() + val root = JSONObject(raw) + val hasUpdate = root.optBoolean("hasUpdate", false) + val relObj = root.optJSONObject("release") ?: return@use (null to false) + val info = MobileReleaseInfo( + id = relObj.optString("id", ""), + version = relObj.optString("version", ""), + buildNumber = relObj.optInt("buildNumber", 0), + changelog = relObj.optString("changelog", ""), + forceUpdate = relObj.optBoolean("forceUpdate", false), + publishedAt = relObj.optString("publishedAt", ""), + apkUrl = relObj.optString("apkUrl", ""), + apkSize = relObj.optLong("apkSize", 0L), + apkSha256 = relObj.optString("apkSha256", ""), + ) + val localNewer = info.buildNumber > BuildConfig.VERSION_CODE || + (info.buildNumber == BuildConfig.VERSION_CODE && compareSemver(info.version, BuildConfig.VERSION_NAME) > 0) + info to (hasUpdate && localNewer) + } + } + + private fun compareSemver(a: String, b: String): Int { + val pa = a.trim().removePrefix("v").substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 } + val pb = b.trim().removePrefix("v").substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 } + val len = maxOf(pa.size, pb.size, 3) + for (i in 0 until len) { + val da = pa.getOrElse(i) { 0 } + val db = pb.getOrElse(i) { 0 } + if (da != db) return da.compareTo(db) + } + return 0 + } + + private fun cleanupInstalledOrObsoleteApks() { + val dir = File(appContext.cacheDir, "updates") + if (!dir.exists()) return + val buildRegex = Regex("""-b(\d+)\.apk$""") + dir.listFiles()?.forEach { f -> + if (f.name.endsWith(".part")) { + f.delete() + return@forEach + } + val m = buildRegex.find(f.name) + val fileBuild = m?.groupValues?.getOrNull(1)?.toIntOrNull() + if (fileBuild != null && fileBuild <= BuildConfig.VERSION_CODE) { + f.delete() + } + } + } + + private fun ensureNotificationChannel() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val nm = appContext.getSystemService(NotificationManager::class.java) ?: return + nm.createNotificationChannel( + NotificationChannel( + UPDATE_CHANNEL_ID, + "版本更新提醒", + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = "当 Dimo 发布新版本时推送更新日志与一键安装提醒" + }, + ) + } + } + + private fun maybePostUpdateNotification(release: MobileReleaseInfo, forceNotify: Boolean) { + val alreadyNotified = prefs.getString(KEY_NOTIFIED_RELEASE, "") ?: "" + if (!forceNotify && alreadyNotified == release.releaseKey) return + if (alreadyNotified == release.releaseKey) return + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(appContext, Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED + ) { + return + } + + prefs.edit().putString(KEY_NOTIFIED_RELEASE, release.releaseKey).apply() + + val openIntent = Intent(appContext, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP + putExtra(EXTRA_OPEN_UPDATE_DIALOG, true) + } + val pendingIntent = PendingIntent.getActivity( + appContext, + UPDATE_NOTIFICATION_ID, + openIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val summary = release.changelog.lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .take(3) + .joinToString("\n") + .ifBlank { "点击查看更新日志并一键覆盖安装新版本" } + + val notification = NotificationCompat.Builder(appContext, UPDATE_CHANNEL_ID) + .setSmallIcon(R.mipmap.ic_launcher_round) + .setContentTitle("发现 Dimo 新版本 v${release.version}") + .setContentText(summary.lines().first()) + .setStyle(NotificationCompat.BigTextStyle().bigText(summary)) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setAutoCancel(true) + .setContentIntent(pendingIntent) + .build() + + runCatching { + NotificationManagerCompat.from(appContext).notify(UPDATE_NOTIFICATION_ID, notification) + } + } + + companion object { + const val EXTRA_OPEN_UPDATE_DIALOG = "vibex_open_update_dialog" + private const val PREFS_NAME = "vibex.app.update" + private const val KEY_DISMISSED_RELEASE = "dismissed_release_key" + private const val KEY_NOTIFIED_RELEASE = "notified_release_key" + private const val UPDATE_CHANNEL_ID = "vibex-app-updates" + private const val UPDATE_NOTIFICATION_ID = 9401 + private const val FOREGROUND_CHECK_INTERVAL_MS = 10 * 60 * 1000L + private const val BACKGROUND_CHECK_INTERVAL_MS = 30 * 60 * 1000L + + @Volatile + private var instance: AppUpdateManager? = null + + fun getInstance(context: Context): AppUpdateManager { + return instance ?: synchronized(this) { + instance ?: AppUpdateManager(context.applicationContext).also { instance = it } + } + } + } +} diff --git a/app/src/main/res/drawable-nodpi/logo_dark.png b/app/src/main/res/drawable-nodpi/logo_dark.png index 8438059..1079dcc 100644 Binary files a/app/src/main/res/drawable-nodpi/logo_dark.png and b/app/src/main/res/drawable-nodpi/logo_dark.png differ diff --git a/app/src/main/res/drawable-nodpi/logo_light.png b/app/src/main/res/drawable-nodpi/logo_light.png index deeb244..1079dcc 100644 Binary files a/app/src/main/res/drawable-nodpi/logo_light.png and b/app/src/main/res/drawable-nodpi/logo_light.png differ diff --git a/app/src/main/res/drawable/dimo_app_icon.png b/app/src/main/res/drawable/dimo_app_icon.png new file mode 100644 index 0000000..9fb5299 Binary files /dev/null and b/app/src/main/res/drawable/dimo_app_icon.png differ diff --git a/app/src/main/res/drawable/ic_launcher_foreground_inset.xml b/app/src/main/res/drawable/ic_launcher_foreground_inset.xml new file mode 100644 index 0000000..12c7556 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground_inset.xml @@ -0,0 +1,4 @@ + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml index 2ffbf24..1166cab 100644 --- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -1,5 +1,5 @@ - + - \ No newline at end of file + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml index 2ffbf24..1166cab 100644 --- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -1,5 +1,5 @@ - + - \ No newline at end of file + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png index 6eb196e..a834fec 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.png and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png index d093627..2128c19 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png index a780e9b..b44032f 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png index 0e3866b..04846b1 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.png and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png index a514674..d688cda 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png index 69f8720..43f8ebc 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png index fca94ec..d49d53c 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png index 62e672d..f06d3e1 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png index 0dbc4cc..5dc3903 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png index 4328f75..12a85c0 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png index dffac84..35b2ffc 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png index fdeb038..f23cc32 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png index 882ed7c..dea093f 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png index 804b65b..e365d8c 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png index d66d23a..f54fe47 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1f4f8e4..cd7bd7e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,6 +1,6 @@ - VibeX + Dimo 将连接二维码放入框内 diff --git a/app/src/main/res/xml/update_file_paths.xml b/app/src/main/res/xml/update_file_paths.xml new file mode 100644 index 0000000..0abec9a --- /dev/null +++ b/app/src/main/res/xml/update_file_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/AccountDesktops.kt b/companion-core/src/main/kotlin/dev/vibex/companion/AccountDesktops.kt index 4214fc1..5e0d9db 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/AccountDesktops.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/AccountDesktops.kt @@ -3,14 +3,33 @@ package dev.vibex.companion import dev.vibex.remote.v1.JsonValue import java.util.Locale -/** A desktop VibeX install signed in to the user's account, keyed by its raw host id. */ +/** A desktop Dimo install signed in to the user's account, keyed by its raw host id. */ data class AccountDesktop( val hostId: String, val hostName: String, val osType: String = "", val osArch: String = "", val lastSeenAt: String = "", + val cloudOnline: Boolean = false, ) { + val displayName: String + get() { + if (AccountDesktops.isGenericHostName(hostName)) { + return when (osType.trim().lowercase(Locale.ROOT)) { + "macos", "darwin" -> "Dimo 桌面端 (Mac)" + "windows" -> "Dimo 桌面端 (Windows)" + "linux" -> "Dimo 桌面端 (Linux)" + else -> "Dimo 桌面端" + } + } + val trimmed = hostName.trim() + return if (trimmed.endsWith(".local", ignoreCase = true)) { + trimmed.dropLast(".local".length) + } else { + trimmed + } + } + val platformBadge: String? get() { val osLabel = when (osType.trim().lowercase(Locale.ROOT)) { @@ -40,8 +59,43 @@ object AccountDesktops { private const val HOST_ID_PREFIX = "host:" private const val DESKTOP_KIND = "local" + private val PLACEHOLDER_HOST_IDS = setOf( + "local-desktop", + "remote-desktop", + "default", + "localhost", + ) + + private val PLACEHOLDER_HOST_PREFIXES = listOf( + "session:", + "web:", + "profile:", + "origin:", + ) + + private val GENERIC_HOST_NAMES = setOf( + "", + "local host", + "localhost", + "vibex 电脑", + "vibex 桌面端", + "dimo 电脑", + "dimo 桌面端", + "vibex desktop", + "dimo desktop", + ) + fun rawHostId(hostId: String): String = hostId.trim().removePrefix(HOST_ID_PREFIX) + fun isPlaceholderHostId(hostId: String): Boolean { + val normalized = rawHostId(hostId).lowercase(Locale.ROOT) + if (normalized.isEmpty() || normalized in PLACEHOLDER_HOST_IDS) return true + return PLACEHOLDER_HOST_PREFIXES.any { normalized.startsWith(it) } + } + + fun isGenericHostName(name: String): Boolean = + name.trim().lowercase(Locale.ROOT) in GENERIC_HOST_NAMES + /** * Desktops of the account from `/api/account/desktop/host-configs`: `hosts ∪ records`, * deduplicated by host id, `kind == "local"` only, most recently seen first. @@ -54,15 +108,13 @@ object AccountDesktops { val kind = obj.textOrNull("kind")?.trim().orEmpty().ifEmpty { DESKTOP_KIND } if (kind != DESKTOP_KIND) continue val hostId = rawHostId(obj.textOrEmpty("hostId")) - // `session:` is the site's placeholder for a device login without a host - // (phones included); there is no computer behind it to connect to. - if (hostId.isEmpty() || hostId.startsWith("session:")) continue + if (isPlaceholderHostId(hostId)) continue val seenAt = obj.textAny("lastSeenAt", "updatedAt").trim() val existing = byHostId[hostId] byHostId[hostId] = AccountDesktop( hostId = hostId, hostName = existing?.hostName - ?: obj.textOrEmpty("hostName").trim().ifEmpty { "VibeX 电脑" }, + ?: obj.textOrEmpty("hostName").trim().ifEmpty { "Dimo 电脑" }, osType = existing?.osType?.ifEmpty { null } ?: obj.textOrEmpty("osType").trim(), osArch = existing?.osArch?.ifEmpty { null } ?: obj.textOrEmpty("osArch").trim(), lastSeenAt = maxOf(existing?.lastSeenAt.orEmpty(), seenAt), @@ -71,6 +123,55 @@ object AccountDesktops { return byHostId.values.sortedByDescending { it.lastSeenAt } } + /** + * Collapses stale ghost installs that report a generic host name on the same `(osType, osArch)` + * while preserving every confirmed online computer and every custom-named computer. + */ + fun deduplicate( + desktops: List, + onlineLanHostIds: Set = emptySet(), + pairedHostIds: Set = emptySet(), + ): List { + val lanIds = onlineLanHostIds + .map { rawHostId(it).lowercase(Locale.ROOT) } + .filter { it.isNotEmpty() } + .toSet() + val pairedIds = pairedHostIds + .map { rawHostId(it).lowercase(Locale.ROOT) } + .filter { it.isNotEmpty() } + .toSet() + + fun isOnline(desktop: AccountDesktop): Boolean = + desktop.cloudOnline || rawHostId(desktop.hostId).lowercase(Locale.ROOT) in lanIds + + fun isPaired(desktop: AccountDesktop): Boolean = + rawHostId(desktop.hostId).lowercase(Locale.ROOT) in pairedIds + + val valid = desktops.filterNot { isPlaceholderHostId(it.hostId) } + val (generic, custom) = valid.partition { isGenericHostName(it.hostName) } + + val dedupedGeneric = generic + .groupBy { + it.osType.trim().lowercase(Locale.ROOT) to it.osArch.trim().lowercase(Locale.ROOT) + } + .values + .flatMap { group -> + val online = group.filter(::isOnline) + if (online.isNotEmpty()) { + online + } else { + val candidates = group.filter(::isPaired).ifEmpty { group } + listOf(candidates.sortedByDescending { it.lastSeenAt }.first()) + } + } + + return (custom + dedupedGeneric).sortedWith( + compareByDescending(::isOnline) + .thenByDescending(::isPaired) + .thenByDescending { it.lastSeenAt }, + ) + } + /** Base URL of the relay that fronts the account's desktops. */ fun relayBase(server: AssignedRelayServer?, defaultBase: String): String { val publicOrigin = server?.publicOrigin?.trim()?.trimEnd('/').orEmpty() diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/BoardAndCollabModels.kt b/companion-core/src/main/kotlin/dev/vibex/companion/BoardAndCollabModels.kt index 7118ef3..0aacd8e 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/BoardAndCollabModels.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/BoardAndCollabModels.kt @@ -687,15 +687,33 @@ data class CollabSpaceMessage( val origin: String? = null, val inReplyTo: String? = null, val streaming: Boolean = false, + val operationId: String? = null, + val turnId: String? = null, val receipts: List = emptyList(), val envelope: CollabMessageEnvelope = CollabMessageEnvelope(), ) { val id: String get() { val candidate = (rawId ?: envelope.id.orEmpty()).replace("vibex://space-message/", "") - return candidate.ifBlank { "seq-$seq" } + if (candidate.isNotBlank()) return candidate + if (streaming) { + val draftKey = turnId?.takeIf { it.isNotBlank() } + ?: operationId?.takeIf { it.isNotBlank() } + ?: envelope.sender.takeIf { it.isNotBlank() } + if (draftKey != null) return "draft:$draftKey" + } + if (!operationId.isNullOrBlank() && seq <= 0) return "op:$operationId" + return "seq-$seq" } + val isStreamingDraft: Boolean + get() = streaming || id.startsWith("draft:") || (rawId?.startsWith("draft:") == true) + + val effectiveTurnId: String? + get() = turnId?.takeIf { it.isNotBlank() } + ?: id.takeIf { it.startsWith("draft:") }?.removePrefix("draft:")?.takeIf { it.isNotBlank() } + ?: rawId?.takeIf { it.startsWith("draft:") }?.removePrefix("draft:")?.takeIf { it.isNotBlank() } + val isFromUser: Boolean get() = origin == "user" || envelope.isFromUser @@ -741,8 +759,47 @@ data class CollabMessagesPage( val scheduled: List = emptyList(), val cards: List = emptyList(), val conversationId: String? = null, + val hasMoreBefore: Boolean = false, + val oldestSeq: Long? = null, +) + +typealias CollabSpaceMessagePage = CollabMessagesPage + +data class CollabEmbeddedCard( + val id: String = "", + val kind: String = "ask", + val status: String? = null, + val question: String? = null, + val options: List = emptyList(), + val action: String? = null, + val command: String? = null, + val reason: String? = null, + val body: String = "", ) +data class CollabEmbeddedHandoff( + val id: String = "", + val from: String? = null, + val to: String? = null, + val depth: String? = null, + val summary: String = "", + val ask: String? = null, + val done: String? = null, + val inputsConstraints: String? = null, +) + +data class CollabParsedMessageContent( + val cleanText: String, + val cards: List = emptyList(), + val handoffs: List = emptyList(), + val lineCount: Int = countCollabMessageLines(cleanText), + val isCollapsible: Boolean = shouldCollapseLongMessage(cleanText), +) { + val card: CollabEmbeddedCard? get() = cards.firstOrNull() + val handoff: CollabEmbeddedHandoff? get() = handoffs.firstOrNull() + val hasStructuredBlocks: Boolean get() = cards.isNotEmpty() || handoffs.isNotEmpty() +} + data class CollabMemoryFact( val id: Int, val content: String, @@ -1210,13 +1267,34 @@ fun HostApi.collabSpaceMembers(origin: HostOrigin, token: String, spaceId: Strin } } -fun HostApi.collabMessagesPage(origin: HostOrigin, token: String, spaceId: String, limit: Int = 200): CollabMessagesPage { - val root = collaboration( - origin, - token, - "space.listMessages", - mapOf("spaceId" to spaceId, "latest" to true, "limit" to limit.toDouble()), - ).asObject() ?: return CollabMessagesPage() +internal fun buildCollabListMessagesInput( + spaceId: String, + limit: Int = 80, + sinceSeq: Long? = null, + beforeSeq: Long? = null, + latest: Boolean = sinceSeq == null && beforeSeq == null, +): Map { + return when { + beforeSeq != null -> linkedMapOf( + "spaceId" to spaceId, + "beforeSeq" to beforeSeq, + "limit" to limit, + ) + sinceSeq != null && sinceSeq > 0L -> linkedMapOf( + "spaceId" to spaceId, + "sinceSeq" to sinceSeq, + "limit" to limit, + ) + else -> linkedMapOf( + "spaceId" to spaceId, + "latest" to if (latest) true else true, + "limit" to limit, + ) + } +} + +fun parseCollabMessagesPage(root: JsonValue.Object?, fallbackSpaceId: String = ""): CollabMessagesPage { + if (root == null) return CollabMessagesPage() val messages = root.arrAny("messages", "items").orEmpty().mapNotNull { item -> val obj = item.asObject() ?: return@mapNotNull null @@ -1252,6 +1330,8 @@ fun HostApi.collabMessagesPage(origin: HostOrigin, token: String, spaceId: Strin origin = obj.textOrNull("origin"), inReplyTo = obj.textAny("in_reply_to", "inReplyTo").ifBlank { null }, streaming = obj.boolAny("streaming") ?: false, + operationId = obj.textAny("operationId", "operation_id").ifBlank { null }, + turnId = obj.textAny("turnId", "turn_id").ifBlank { null }, receipts = receipts, envelope = envelope, ) @@ -1261,7 +1341,7 @@ fun HostApi.collabMessagesPage(origin: HostOrigin, token: String, spaceId: Strin val obj = item.asObject() ?: return@mapNotNull null CollabScheduledMessage( id = obj.textAny("id", "delayed_input_id").ifBlank { UUID.randomUUID().toString() }, - spaceId = obj.textAny("space_id", "spaceId").ifBlank { spaceId }, + spaceId = obj.textAny("space_id", "spaceId").ifBlank { fallbackSpaceId }, content = obj.textAny("content"), deliverAt = obj.textAny("deliver_at", "deliverAt"), status = obj.textOrNull("status"), @@ -1288,7 +1368,384 @@ fun HostApi.collabMessagesPage(origin: HostOrigin, token: String, spaceId: Strin scheduled = scheduled, cards = cards, conversationId = root.textAny("conversationId", "conversation_id").ifBlank { null }, + hasMoreBefore = root.boolAny("hasMoreBefore", "has_more_before") ?: false, + oldestSeq = root.longAny("oldestSeq", "oldest_seq"), + ) +} + +fun HostApi.collabMessagesPage( + origin: HostOrigin, + token: String, + spaceId: String, + limit: Int = 80, + sinceSeq: Long? = null, + beforeSeq: Long? = null, + latest: Boolean = sinceSeq == null && beforeSeq == null, +): CollabMessagesPage { + val input = buildCollabListMessagesInput( + spaceId = spaceId, + limit = limit, + sinceSeq = sinceSeq, + beforeSeq = beforeSeq, + latest = latest, ) + val root = collaboration(origin, token, "space.listMessages", input).asObject() + return parseCollabMessagesPage(root, fallbackSpaceId = spaceId) +} + +fun HostApi.collabMessages( + origin: HostOrigin, + token: String, + spaceId: String, + limit: Int = 80, + sinceSeq: Long? = null, + beforeSeq: Long? = null, + latest: Boolean = sinceSeq == null && beforeSeq == null, +): CollabMessagesPage = collabMessagesPage( + origin = origin, + token = token, + spaceId = spaceId, + limit = limit, + sinceSeq = sinceSeq, + beforeSeq = beforeSeq, + latest = latest, +) + +private fun explicitCollabMessageId(msg: CollabSpaceMessage): String? = + (msg.rawId ?: msg.envelope.id) + ?.replace("vibex://space-message/", "") + ?.trim() + ?.takeIf { it.isNotEmpty() } + +private fun mergeCollabMessageFields(older: CollabSpaceMessage, newer: CollabSpaceMessage): CollabSpaceMessage = + newer.copy( + rawId = newer.rawId ?: older.rawId, + inReplyTo = newer.inReplyTo ?: older.inReplyTo, + operationId = newer.operationId ?: older.operationId, + turnId = newer.turnId ?: older.turnId, + ) + +fun mergeCollabMessages( + existing: List, + incoming: List, + isIncremental: Boolean = true, +): List { + if (!isIncremental) { + return mergeCollabMessages(emptyList(), incoming, isIncremental = true) + } + if (existing.isEmpty() && incoming.isEmpty()) return emptyList() + + val result = existing.toMutableList() + val maxExistingConfirmedSeq = existing + .asSequence() + .filter { !it.isStreamingDraft && it.seq > 0 } + .maxOfOrNull { it.seq } ?: 0 + + for (inc in incoming) { + val incExplicitId = explicitCollabMessageId(inc) + val incTurnId = inc.effectiveTurnId + val incOpId = inc.operationId?.takeIf { it.isNotBlank() } + + if (inc.isStreamingDraft) { + val alreadyFinalized = result.any { ex -> + !ex.isStreamingDraft && ex.seq > 0 && ( + (incTurnId != null && ex.effectiveTurnId == incTurnId) || + (incOpId != null && ex.operationId == incOpId) + ) + } + if (alreadyFinalized) continue + + val draftIdx = result.indexOfFirst { ex -> + ex.isStreamingDraft && ( + (incExplicitId != null && explicitCollabMessageId(ex) == incExplicitId) || + (ex.id == inc.id) || + (incTurnId != null && ex.effectiveTurnId == incTurnId) || + (incOpId != null && ex.operationId == incOpId) || + ( + (incTurnId == null || ex.effectiveTurnId == null) && + inc.envelope.sender.isNotBlank() && + ex.envelope.sender.equals(inc.envelope.sender, ignoreCase = true) + ) + ) + } + if (draftIdx >= 0) { + result[draftIdx] = mergeCollabMessageFields(result[draftIdx], inc) + } else { + result.add(inc) + } + } else { + result.removeAll { ex -> + ex.isStreamingDraft && ( + (incExplicitId != null && explicitCollabMessageId(ex) == incExplicitId) || + (incTurnId != null && ex.effectiveTurnId == incTurnId) || + (incOpId != null && ex.operationId == incOpId) || + ( + inc.seq > 0 && + inc.envelope.sender.isNotBlank() && + ex.envelope.sender.equals(inc.envelope.sender, ignoreCase = true) && + ( + inc.seq > maxExistingConfirmedSeq || + ( + ex.envelope.content.isNotBlank() && + inc.envelope.content.trim().startsWith( + ex.envelope.content.trim().take(48), + ) + ) + ) + ) + ) + } + + val existingIdx = result.indexOfFirst { ex -> + !ex.isStreamingDraft && ( + (incExplicitId != null && explicitCollabMessageId(ex) == incExplicitId) || + (inc.rawId != null && inc.rawId.isNotBlank() && ex.rawId == inc.rawId) || + (incOpId != null && ex.operationId == incOpId) || + (inc.seq > 0 && ex.seq == inc.seq) + ) + } + if (existingIdx >= 0) { + result[existingIdx] = mergeCollabMessageFields(result[existingIdx], inc) + } else { + result.add(inc) + } + } + } + + val confirmed = result + .filterNot { it.isStreamingDraft } + .withIndex() + .sortedWith( + compareBy> { if (it.value.seq > 0) 0 else 1 } + .thenBy { it.value.seq } + .thenBy { it.index }, + ) + .map { it.value } + val drafts = result.filter { it.isStreamingDraft } + + val dedupById = LinkedHashMap(confirmed.size + drafts.size) + for (msg in confirmed) dedupById[msg.id] = msg + for (msg in drafts) dedupById[msg.id] = msg + return dedupById.values.toList() +} + +fun reconcileCollabStreamingDrafts( + merged: List, + activeTailPage: List, +): List { + if (merged.none { it.isStreamingDraft }) return merged + val activeDrafts = activeTailPage.filter { it.isStreamingDraft } + if (activeDrafts.isEmpty()) { + return merged.filterNot { it.isStreamingDraft } + } + return merged.filter { msg -> + if (!msg.isStreamingDraft) return@filter true + val explicitId = explicitCollabMessageId(msg) + val turnId = msg.effectiveTurnId + activeDrafts.any { live -> + live.id == msg.id || + (explicitId != null && explicitCollabMessageId(live) == explicitId) || + (turnId != null && live.effectiveTurnId == turnId) || + ( + msg.envelope.sender.isNotBlank() && + live.envelope.sender.equals(msg.envelope.sender, ignoreCase = true) + ) + } + } +} + +fun buildCollabMessageLookup(messages: List): Map { + if (messages.isEmpty()) return emptyMap() + val map = HashMap(messages.size * 3) + for (msg in messages) { + map[msg.id] = msg + map["vibex://space-message/${msg.id}"] = msg + msg.rawId?.takeIf { it.isNotBlank() }?.let { map[it] = msg } + msg.envelope.id?.takeIf { it.isNotBlank() }?.let { map[it] = msg } + } + return map +} + +fun lookupCollabReplyMessage( + lookup: Map, + inReplyTo: String?, +): CollabSpaceMessage? { + val ref = inReplyTo?.trim()?.takeIf { it.isNotEmpty() } ?: return null + return lookup[ref] ?: lookup[ref.removePrefix("vibex://space-message/")] +} + +private val CollabCardBlockRegex = Regex("""]*)>([\s\S]*?)""", RegexOption.IGNORE_CASE) +private val CollabUnclosedCardRegex = Regex("""]*>[\s\S]*$""", RegexOption.IGNORE_CASE) +private val CollabHandoffBlockRegex = Regex("""]*)>([\s\S]*?)""", RegexOption.IGNORE_CASE) +private val CollabSelfClosingHandoffRegex = Regex("""]*?)/>""", RegexOption.IGNORE_CASE) +private val CollabUnclosedHandoffRegex = Regex("""]*>[\s\S]*$""", RegexOption.IGNORE_CASE) +private val CollabAnyXmlTagRegex = Regex("""]*)?>""") +private val CollabExcessBlankLinesRegex = Regex("""\n{3,}""") + +private fun unescapeCollabXml(raw: String): String = + raw + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace("'", "'") + .replace("&", "&") + +private fun extractXmlAttr(attrs: String, name: String): String? { + val regex = Regex("""\b$name\s*=\s*(?:"([^"]*)"|'([^']*)')""", RegexOption.IGNORE_CASE) + val match = regex.find(attrs) ?: return null + val value = match.groups[1]?.value ?: match.groups[2]?.value ?: return null + return unescapeCollabXml(value.trim()).takeIf { it.isNotEmpty() } +} + +private fun extractXmlField(inner: String, tag: String): String? { + val regex = Regex("""<$tag\b[^>]*>([\s\S]*?)""", RegexOption.IGNORE_CASE) + val match = regex.find(inner) ?: return null + return unescapeCollabXml(match.groupValues[1].trim()).takeIf { it.isNotEmpty() } +} + +private fun parseEmbeddedCard(attrs: String, inner: String): CollabEmbeddedCard { + val id = extractXmlAttr(attrs, "id") ?: extractXmlField(inner, "id").orEmpty() + val kind = (extractXmlAttr(attrs, "kind") ?: extractXmlField(inner, "kind") ?: "ask").lowercase() + val status = extractXmlAttr(attrs, "status") ?: extractXmlField(inner, "status") + val question = extractXmlField(inner, "question") + val optionsRaw = extractXmlField(inner, "options") + val options = optionsRaw + ?.split('|') + ?.map { it.trim() } + ?.filter { it.isNotEmpty() } + .orEmpty() + val action = extractXmlField(inner, "action") + val command = extractXmlField(inner, "command") + val reason = extractXmlField(inner, "reason") + val explicitBody = extractXmlField(inner, "body") + val strippedFallback = unescapeCollabXml( + inner + .replace(Regex("""]*>[\s\S]*?""", RegexOption.IGNORE_CASE), "") + .replace(CollabAnyXmlTagRegex, " ") + .replace(Regex("""\s+"""), " ") + .trim(), + ) + val body = when (kind) { + "approval" -> listOfNotNull(action, reason, explicitBody) + .firstOrNull { it.isNotBlank() } + ?: command + ?: strippedFallback + else -> listOfNotNull(question, explicitBody, action, reason) + .firstOrNull { it.isNotBlank() } + ?: strippedFallback + } + return CollabEmbeddedCard( + id = id, + kind = kind, + status = status, + question = question, + options = options, + action = action, + command = command, + reason = reason, + body = body, + ) +} + +private fun parseEmbeddedHandoff(attrs: String, inner: String): CollabEmbeddedHandoff { + val id = extractXmlAttr(attrs, "id") ?: extractXmlField(inner, "id").orEmpty() + val from = extractXmlAttr(attrs, "from") + ?: extractXmlAttr(attrs, "sender") + ?: extractXmlField(inner, "from") + val to = extractXmlAttr(attrs, "to") + ?: extractXmlAttr(attrs, "target") + ?: extractXmlAttr(attrs, "recipient") + ?: extractXmlField(inner, "to") + val depth = extractXmlAttr(attrs, "depth") ?: extractXmlField(inner, "depth") + val ask = extractXmlField(inner, "ask") ?: extractXmlAttr(attrs, "ask") + val done = extractXmlField(inner, "done") + val constraints = extractXmlField(inner, "inputs_constraints") ?: extractXmlField(inner, "constraints") + val explicitSummary = extractXmlField(inner, "summary") ?: extractXmlAttr(attrs, "summary") + val strippedInner = unescapeCollabXml( + inner.replace(CollabAnyXmlTagRegex, "\n").lines().map { it.trim() }.filter { it.isNotEmpty() }.joinToString(" · "), + ) + val summary = listOfNotNull(explicitSummary, ask, done, strippedInner.takeIf { it.isNotEmpty() }) + .firstOrNull { it.isNotBlank() } + .orEmpty() + return CollabEmbeddedHandoff( + id = id, + from = from, + to = to, + depth = depth, + summary = summary, + ask = ask, + done = done, + inputsConstraints = constraints, + ) +} + +fun countCollabMessageLines(text: String): Int { + val normalized = text.replace("\r\n", "\n").trim() + if (normalized.isEmpty()) return 0 + return normalized.count { it == '\n' } + 1 +} + +fun shouldCollapseLongMessage( + text: String, + maxLines: Int = 12, + maxChars: Int = 480, +): Boolean { + val trimmed = text.trim() + if (trimmed.isEmpty()) return false + if (trimmed.length > maxChars) return true + return countCollabMessageLines(trimmed) > maxLines +} + +fun parseCollabStructuredMessage(rawContent: String): CollabParsedMessageContent { + if (rawContent.isEmpty()) { + return CollabParsedMessageContent(cleanText = "", lineCount = 0, isCollapsible = false) + } + val cards = mutableListOf() + val handoffs = mutableListOf() + + for (match in CollabCardBlockRegex.findAll(rawContent)) { + cards += parseEmbeddedCard(match.groupValues[1], match.groupValues[2]) + } + for (match in CollabHandoffBlockRegex.findAll(rawContent)) { + handoffs += parseEmbeddedHandoff(match.groupValues[1], match.groupValues[2]) + } + for (match in CollabSelfClosingHandoffRegex.findAll(rawContent)) { + handoffs += parseEmbeddedHandoff(match.groupValues[1], "") + } + + val cleaned = rawContent + .replace("\r\n", "\n") + .replace(CollabCardBlockRegex, "") + .replace(CollabHandoffBlockRegex, "") + .replace(CollabSelfClosingHandoffRegex, "") + .replace(CollabUnclosedCardRegex, "") + .replace(CollabUnclosedHandoffRegex, "") + .replace(CollabExcessBlankLinesRegex, "\n\n") + .trim() + + return CollabParsedMessageContent( + cleanText = cleaned, + cards = cards, + handoffs = handoffs, + lineCount = countCollabMessageLines(cleaned), + isCollapsible = shouldCollapseLongMessage(cleaned), + ) +} + +fun collabMessagePreviewText(rawContent: String): String { + val parsed = parseCollabStructuredMessage(rawContent) + if (parsed.cleanText.isNotBlank()) { + return parsed.cleanText.replace(Regex("""\s+"""), " ").trim() + } + parsed.card?.let { c -> + val prefix = if (c.kind == "approval") "[审批]" else "[提问]" + return if (c.body.isNotBlank()) "$prefix ${c.body}" else prefix + } + parsed.handoff?.let { h -> + return if (h.summary.isNotBlank()) "[交接] ${h.summary}" else "[交接]" + } + return rawContent.replace(Regex("""\s+"""), " ").trim() } fun HostApi.collabPostMessage( @@ -1299,19 +1756,20 @@ fun HostApi.collabPostMessage( to: List = emptyList(), inReplyTo: String? = null, delaySeconds: Int? = null, + operationId: String = UUID.randomUUID().toString().lowercase(), ) { val input = linkedMapOf( "spaceId" to spaceId, "content" to content, - "operationId" to UUID.randomUUID().toString().lowercase(), + "operationId" to operationId, ) if (to.isNotEmpty()) input["to"] = to if (!inReplyTo.isNullOrBlank()) input["inReplyTo"] = inReplyTo if (delaySeconds != null && delaySeconds > 0) { input["delaySeconds"] = delaySeconds - collaboration(origin, token, "space.post", input) + collaboration(origin, token, "space.post", input, operationId) } else { - collaboration(origin, token, "space.submit", input) + collaboration(origin, token, "space.submit", input, operationId) } } @@ -1498,3 +1956,29 @@ fun HostApi.collabTeamsList(origin: HostOrigin, token: String, workspaceId: Stri ) } } + +/** An `@query` token ending at the caret. [start] is the index of '@'. */ +data class MentionToken(val start: Int, val end: Int, val query: String) + +fun mentionTokenAt(text: String, caret: Int): MentionToken? { + val end = caret.coerceIn(0, text.length) + var i = end + while (i > 0) { + val ch = text[i - 1] + if (ch == '@') { + val before = if (i - 1 > 0) text[i - 2] else ' ' + if (!before.isWhitespace()) return null + return MentionToken(i - 1, end, text.substring(i, end)) + } + if (ch.isWhitespace()) return null + i-- + } + return null +} + +/** Replaces [token] with `@label ` and returns the new text and caret index. */ +fun applyMention(text: String, token: MentionToken, label: String): Pair { + val insert = "@$label " + val next = text.substring(0, token.start) + insert + text.substring(token.end) + return next to (token.start + insert.length) +} diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/ConnectionPolicy.kt b/companion-core/src/main/kotlin/dev/vibex/companion/ConnectionPolicy.kt new file mode 100644 index 0000000..c5213f5 --- /dev/null +++ b/companion-core/src/main/kotlin/dev/vibex/companion/ConnectionPolicy.kt @@ -0,0 +1,58 @@ +package dev.vibex.companion + +/** Pure reconnect / debounce policy so connection behaviour is unit-testable. */ +object ConnectionPolicy { + const val BACKOFF_BASE_MS = 800L + const val BACKOFF_MAX_MS = 15_000L + const val RECOVERING_DEBOUNCE_MS = 1_500L + const val WS_PING_INTERVAL_MS = 15_000L + const val HTTP_REFRESH_INTERVAL_MS = 12_000L + const val POLL_FAILURES_BEFORE_DEGRADED = 3 + const val RECONNECT_ATTEMPTS_BEFORE_OFFLINE = 3 + + /** Base delay (no jitter): 0.8s, 1.6s, 3.2s ... capped at 15s. [attempt] is 0-based. */ + fun backoffBaseMs(attempt: Int): Long { + val shift = attempt.coerceIn(0, 20) + return (BACKOFF_BASE_MS shl shift).coerceAtMost(BACKOFF_MAX_MS) + } + + /** Delay with +-20% jitter; [random01] in [0,1). Never exceeds the cap by more than jitter of cap. */ + fun backoffMs(attempt: Int, random01: Double): Long { + val base = backoffBaseMs(attempt) + val factor = 0.8 + 0.4 * random01.coerceIn(0.0, 1.0) + return (base * factor).toLong().coerceAtLeast(1L) + } + + /** Only surface "Recovering" once the link has been down longer than the debounce window. */ + fun shouldShowRecovering(downSinceMs: Long?, nowMs: Long): Boolean = + downSinceMs != null && nowMs - downSinceMs >= RECOVERING_DEBOUNCE_MS + + /** A single failed poll is noise; only a streak counts as degraded. */ + fun pollDegraded(consecutiveFailures: Int): Boolean = + consecutiveFailures >= POLL_FAILURES_BEFORE_DEGRADED + + /** Whether the periodic HTTP refresh should run. */ + fun shouldRunHttpRefresh( + foreground: Boolean, + state: ConnectionState, + sinceLastMs: Long, + ): Boolean = foreground && state == ConnectionState.Online && sinceLastMs >= HTTP_REFRESH_INTERVAL_MS + + /** After this many failed reconnects show Offline instead of Recovering. */ + fun reconnectGivesOffline(failedAttempts: Int): Boolean = + failedAttempts >= RECONNECT_ATTEMPTS_BEFORE_OFFLINE +} + +/** Bounded in-memory ring of connection transitions for diagnostics. */ +class ConnectionLog(private val capacity: Int = 100) { + private val entries = ArrayDeque() + + @Synchronized + fun add(line: String) { + if (entries.size >= capacity) entries.removeFirst() + entries.addLast(line) + } + + @Synchronized + fun snapshot(): List = entries.toList() +} diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/E2eeSessionManager.kt b/companion-core/src/main/kotlin/dev/vibex/companion/E2eeSessionManager.kt index e1e6e0e..ca6b49b 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/E2eeSessionManager.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/E2eeSessionManager.kt @@ -18,20 +18,20 @@ import javax.crypto.spec.SecretKeySpec * between the Android Companion client and a paired VibeX Host. */ object E2eeSessionManager { - const val HEADER_E2EE = "x-vibex-e2ee" - const val HEADER_CLIENT_PUB = "x-vibex-e2ee-client-pub" - const val HEADER_SERVER_PUB = "x-vibex-e2ee-server-pub" - const val HEADER_SESSION = "x-vibex-e2ee-session" - const val HEADER_AUTH = "x-vibex-e2ee-auth" + const val HEADER_E2EE = "x-dimo-e2ee" + const val HEADER_CLIENT_PUB = "x-dimo-e2ee-client-pub" + const val HEADER_SERVER_PUB = "x-dimo-e2ee-server-pub" + const val HEADER_SESSION = "x-dimo-e2ee-session" + const val HEADER_AUTH = "x-dimo-e2ee-auth" const val VERSION = "v1" - private val HKDF_SALT = "vibex-e2ee-v1-salt".toByteArray(Charsets.UTF_8) - private val HKDF_INFO = "vibex-e2ee-v1-aes256gcm".toByteArray(Charsets.UTF_8) + private val HKDF_SALT = "dimo-e2ee-v1-salt".toByteArray(Charsets.UTF_8) + private val HKDF_INFO = "dimo-e2ee-v1-aes256gcm".toByteArray(Charsets.UTF_8) - val AAD_AUTH = "vibex-e2ee-auth-v1".toByteArray(Charsets.UTF_8) - val AAD_REQ = "vibex-e2ee-req-v1".toByteArray(Charsets.UTF_8) - val AAD_RESP = "vibex-e2ee-resp-v1".toByteArray(Charsets.UTF_8) - val AAD_WS = "vibex-e2ee-ws-v1".toByteArray(Charsets.UTF_8) + val AAD_AUTH = "dimo-e2ee-auth-v1".toByteArray(Charsets.UTF_8) + val AAD_REQ = "dimo-e2ee-req-v1".toByteArray(Charsets.UTF_8) + val AAD_RESP = "dimo-e2ee-resp-v1".toByteArray(Charsets.UTF_8) + val AAD_WS = "dimo-e2ee-ws-v1".toByteArray(Charsets.UTF_8) // ASN.1 DER SubjectPublicKeyInfo prefix for NIST P-256 (secp256r1) uncompressed 65-byte point private val P256_SPKI_PREFIX = byteArrayOf( @@ -83,6 +83,10 @@ object E2eeSessionManager { fun isE2eeActive(urlOrOrigin: String): Boolean = session(urlOrOrigin) != null + fun clearSession(urlOrOrigin: String) { + sessionsByOrigin.remove(originKey(urlOrOrigin)) + } + fun ingestHandshake( urlOrOrigin: String, sessionId: String?, diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/EventFold.kt b/companion-core/src/main/kotlin/dev/vibex/companion/EventFold.kt index 2c6f472..a88ba5a 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/EventFold.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/EventFold.kt @@ -76,6 +76,7 @@ object EventFold { if (order.isEmpty()) return val transcriptRows = mutableListOf() + var pendingRateLimit: RateLimitBanner? = null val totalRows = order.size order.forEachIndexed { rowIndex, rowId -> val obj = deduped[rowId]?.second ?: return@forEachIndexed @@ -125,6 +126,10 @@ object EventFold { val err = inner.objOrNull("error") val msg = err?.objOrNull("error")?.textAny("message") ?: err?.textAny("message").orEmpty() + val errBody = err?.objOrNull("error") ?: err + if (errBody?.textAny("kind") == "rate_limited") { + pendingRateLimit = parseRateLimit(errBody, "tx:err:$rowId", session.agentId) + } if (msg.isNotBlank()) { transcriptRows += TimelineRow( id = "tx:err:$rowId", @@ -135,6 +140,11 @@ object EventFold { ) } } + "session_notice" -> { + parseHandoffNotice(inner.objOrNull("notice"), "tx:handoff:$rowId")?.let { + transcriptRows += it + } + } "message_turn" -> { val turn = inner.objOrNull("turn") ?: return@forEachIndexed val turnId = turn.textAny("id").ifBlank { rowId } @@ -310,11 +320,44 @@ object EventFold { } } + // A rate-limit banner only stays while no later user message follows the error. + session.rateLimit = pendingRateLimit?.takeIf { banner -> + val errIdx = transcriptRows.indexOfFirst { it.id == banner.rowId } + val lastUserIdx = transcriptRows.indexOfLast { it.kind == "user" } + errIdx < 0 || lastUserIdx < errIdx + } + if (transcriptRows.isEmpty()) return val prevTxUserCount = session.rows.count { it.id.startsWith("tx:user:") } val newTxUserCount = transcriptRows.count { it.kind == "user" } - val preservedTailUser = if (newTxUserCount <= prevTxUserCount) { + val optimisticText = session.optimisticUserText + if (optimisticText != null) { + val serverMatchedOptimistic = newTxUserCount > session.optimisticBaselineUserCount || + (prevTxUserCount == 0 && transcriptRows.lastOrNull { it.kind == "user" }?.body?.trim() == optimisticText) + if (serverMatchedOptimistic) { + session.optimisticUserText = null + val lastUserRowIdx = transcriptRows.indexOfLast { it.kind == "user" } + val hasReplyAfterLastUser = lastUserRowIdx >= 0 && lastUserRowIdx < transcriptRows.lastIndex + if (hasReplyAfterLastUser || session.inFlightTurnId != null) { + session.optimisticThinkingUntilMs = 0L + } + } + } + val preservedTailUser = if (session.optimisticUserText != null) { + val existingLocal = session.rows.filter { it.id.startsWith("local:") && it.kind == "user" } + existingLocal.ifEmpty { + listOf( + TimelineRow( + id = "local:preserved", + kind = "user", + title = "", + body = session.optimisticUserText!!, + tone = TimelineTone.Quiet, + ), + ) + } + } else if (newTxUserCount <= prevTxUserCount) { val lastTxIdx = session.rows.indexOfLast { it.id.startsWith("tx:") } session.rows.drop(if (lastTxIdx >= 0) lastTxIdx + 1 else 0) .filter { !it.id.startsWith("tx:") && it.kind == "user" } @@ -426,10 +469,12 @@ object EventFold { "user_turn_created" -> { val turnId = payload.fields("turn_id", "turnId").ifBlank { "turn:${event.sequence}" } session.inFlightTurnId = turnId + session.optimisticUserText = null + session.optimisticThinkingUntilMs = 0L session.notices.removeAll { it.id.startsWith("end:") } session.rows.removeAll { it.id.startsWith("end:") } val body = userText(payload) - session.rows.removeAll { it.id.startsWith("local:") && it.body == body } + session.rows.removeAll { it.id.startsWith("local:") } val lastUserIdx = session.rows.indexOfLast { it.kind == "user" } val lastAsstIdx = session.rows.indexOfLast { it.kind == "assistant" } val alreadyInTranscriptTail = lastUserIdx >= 0 && @@ -453,6 +498,7 @@ object EventFold { "user_turn_queued" -> Unit "user_turn_started" -> { session.inFlightTurnId = payload.fields("turn_id", "turnId").ifBlank { "running" } + session.optimisticThinkingUntilMs = 0L session.rows.removeAll { it.id.startsWith("queued-turn:") } } "assistant_text_delta" -> appendAssistant(session, payload, body = payload.textOrEmpty("text")) @@ -656,19 +702,27 @@ object EventFold { ) } "turn_completed" -> { + session.rateLimit = null session.inFlightTurnId = null + session.optimisticThinkingUntilMs = 0L session.permissionPrompt = null session.pendingQuestion = null session.notices.removeAll { it.id.startsWith("end:") } session.rows.removeAll { it.kind == "turn_cancelled" } } - "turn_failed" -> finishTurn( + "turn_failed" -> { + val liveErr = payload?.objOrNull("error") + if (liveErr?.textAny("kind") == "rate_limited") { + session.rateLimit = parseRateLimit(liveErr, "end:${event.sequence}", session.agentId) + } + finishTurn( session, event, "失败", TimelineTone.Stop, payload.nestedText("error", "message") ?: payload.textOrEmpty("message"), - ) + ) + } "turn_cancelled" -> finishTurn(session, event, "已取消", TimelineTone.Quiet) "turn_interrupted" -> finishTurn( session, @@ -690,8 +744,7 @@ object EventFold { } "prompt_capabilities_updated" -> { val caps = payload?.objOrNull("capabilities") ?: payload - session.canSteer = caps?.boolOrNull("steer") == true || - caps?.value?.containsKey("steering") == true + applySteeringCapabilities(session, caps) } "available_commands_updated" -> { session.availableCommands.clear() @@ -926,6 +979,85 @@ object EventFold { session.rows.removeAll { it.id.startsWith("blocked:") } } + /** Honest steering: only a native-capable binding steers; host reports it via `conversation_detail`. */ + fun applySteeringCapabilities(session: TimelineSession, caps: JsonValue.Object?) { + if (caps == null) return + val steering = caps.boolOrNull("steering") == true || caps.boolOrNull("steer") == true + val channel = caps.textAny("delivery_channel", "deliveryChannel") + val hasSignal = caps.value.containsKey("steering") || caps.value.containsKey("steer") || channel.isNotBlank() + if (!hasSignal) return + session.canSteer = steering + session.steeringKnown = true + } + + /** Applies `conversation_detail` (tailTurns=1) steering capability and in-flight turn id. */ + fun applyConversationDetail(session: TimelineSession, payload: JsonValue?) { + val root = unwrapObject(payload) ?: return + val binding = root.objOrNull("active_binding") ?: root.objOrNull("activeBinding") + val caps = binding?.objOrNull("capabilities") + if (caps != null) { + applySteeringCapabilities(session, caps) + if (!session.steeringKnown) { + session.canSteer = false + session.steeringKnown = true + } + } else if (binding == null) { + session.canSteer = false + session.steeringKnown = true + } + } + + private fun parseRateLimit(err: JsonValue.Object, rowId: String, agentId: String): RateLimitBanner { + val raw = err.objOrNull("raw") + val planWindows = (err.objOrNull("plan_usage") ?: err.objOrNull("planUsage")) + ?.arrOrNull("windows").orEmpty() + val resetFromPlan = planWindows.mapNotNull { it.asObject()?.longOrNull("resetsAtMs") }.minOrNull() + val resetFromRaw = raw?.let { r -> + (r.longOrNull("reset_at") ?: r.longOrNull("resetAt") ?: r.longOrNull("resets_at") ?: r.longOrNull("resetsAt")) + ?.let { if (it < 1_000_000_000_000L) it * 1000 else it } + } + val retry = raw?.longOrNull("retry_after_seconds") ?: raw?.longOrNull("retryAfterSeconds") + return RateLimitBanner( + rowId = rowId, + engine = agentId, + resetAtMs = resetFromPlan ?: resetFromRaw, + retryAfterSeconds = retry?.takeIf { it > 0 }, + message = err.textAny("message"), + ) + } + + private fun parseHandoffNotice(notice: JsonValue.Object?, rowId: String): TimelineRow? { + notice ?: return null + val announcement = notice.textAny("announcement_id", "announcementId") + if (!announcement.startsWith("host-note:agent-handoff")) return null + val structured = runCatching { JsonValue.parse(notice.textAny("message")) as? JsonValue.Object }.getOrNull() + ?: return null + val from = structured.textAny("fromAgent") + val to = structured.textAny("toAgent") + if (from.isBlank() || to.isBlank()) return null + val fork = structured.textAny("handoffKind") == "fork" + val fromModel = structured.textAny("fromModel") + val toModel = structured.textAny("toModel") + val tokens = structured.longOrNull("handoffTokens") + val label = buildString { + append(if (fork) "Fork 交接" else "交接") + append(" · ") + append(from) + if (fromModel.isNotBlank()) append(" ($fromModel)") + append(" → ") + append(to) + if (toModel.isNotBlank()) append(" ($toModel)") + if (tokens != null && tokens > 0) append(" · 约 $tokens tokens") + } + return TimelineRow( + id = rowId, + kind = "agent_handoff", + title = "交接", + body = label, + tone = TimelineTone.Quiet, + ) + } + private fun finishTurn( session: TimelineSession, event: RemoteEvent, @@ -934,6 +1066,7 @@ object EventFold { body: String = "", ) { session.inFlightTurnId = null + session.optimisticThinkingUntilMs = 0L session.permissionPrompt = null session.pendingQuestion = null val severity = if (tone == TimelineTone.Stop) NoticeSeverity.Error else NoticeSeverity.Info @@ -1031,7 +1164,8 @@ object EventFold { is JsonValue.Bool -> SessionConfigChoice(item.value.toString(), if (item.value) "On" else "Off") is JsonValue.Object -> { val value = scalarText(item, "value", "id").ifBlank { return null } - SessionConfigChoice(value, item.textAny("label", "name").ifBlank { value }) + val desc = item.textOrNull("description")?.takeIf { it.isNotBlank() } + SessionConfigChoice(value, item.textAny("label", "name").ifBlank { value }, desc) } else -> null } diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/HandoffSideChat.kt b/companion-core/src/main/kotlin/dev/vibex/companion/HandoffSideChat.kt new file mode 100644 index 0000000..abf9d24 --- /dev/null +++ b/companion-core/src/main/kotlin/dev/vibex/companion/HandoffSideChat.kt @@ -0,0 +1,196 @@ +package dev.vibex.companion + +import dev.vibex.remote.v1.JsonValue + +/** `provider_instances_list` wire row (camelCase `ProviderInstanceWireView`). */ +data class ProviderInstanceItem( + val instanceId: String, + val agentId: String, + val displayName: String, + val isDefault: Boolean, +) + +/** `ConversationEngineHandoffPreview` (camelCase). */ +data class EngineHandoffPreview( + val sourceEngine: String, + val targetEngine: String, + val packedCount: Int, + val omittedCount: Int, + val totalTokens: Int, + val tokenBudget: Int, + val promptText: String, +) + +data class SideChatToolCall(val id: String, val name: String, val status: String, val summary: String) + +data class SideChatReply(val content: String, val toolCalls: List) + +data class SideChatContextTurn(val turnNumber: Int, val userText: String, val assistantText: String) + +data class SideChatMessage( + val id: String, + val role: String, // "user" | "assistant" + val content: String, + val toolCalls: List = emptyList(), + val isError: Boolean = false, +) + +fun parseProviderInstances(data: JsonValue): List { + val rows = data.asArray()?.value + ?: data.asObject()?.arrOrNull("items") + ?: data.asObject()?.arrOrNull("instances") + ?: return emptyList() + return rows.mapNotNull { item -> + val obj = item.asObject() ?: return@mapNotNull null + val instanceId = obj.textAny("instanceId", "instance_id") + val agentId = obj.textAny("agentId", "agent_id") + if (instanceId.isBlank() || agentId.isBlank()) return@mapNotNull null + ProviderInstanceItem( + instanceId = instanceId, + agentId = agentId, + displayName = obj.textAny("displayName", "display_name").ifBlank { instanceId }, + isDefault = obj.boolOrNull("isDefault") ?: obj.boolOrNull("is_default") ?: false, + ) + } +} + +fun parseEngineHandoffPreview(data: JsonValue): EngineHandoffPreview? { + val obj = data.asObject() ?: return null + return EngineHandoffPreview( + sourceEngine = obj.textAny("sourceEngine", "source_engine"), + targetEngine = obj.textAny("targetEngine", "target_engine"), + packedCount = (obj.arrOrNull("packedMessages") ?: obj.arrOrNull("packed_messages")).orEmpty().size, + omittedCount = (obj.arrOrNull("omittedIds") ?: obj.arrOrNull("omitted_ids")).orEmpty().size, + totalTokens = (obj.longOrNull("totalTokens") ?: obj.longOrNull("total_tokens") ?: 0L).toInt(), + tokenBudget = (obj.longOrNull("tokenBudget") ?: obj.longOrNull("token_budget") ?: 0L).toInt(), + promptText = obj.textAny("handoffPromptText", "handoff_prompt_text"), + ) +} + +/** Instances available for [agentId], case-insensitive and tolerant of `-`/`_` differences. */ +fun instancesForAgent(all: List, agentId: String): List { + fun norm(s: String) = s.lowercase().replace('-', '_') + return all.filter { norm(it.agentId) == norm(agentId) } +} + +fun parseSideChatReply(data: JsonValue): SideChatReply? { + val obj = data.asObject() ?: return null + fun tool(v: JsonValue): SideChatToolCall? { + val t = v.asObject() ?: return null + return SideChatToolCall( + id = t.textAny("id"), + name = t.textAny("name").ifBlank { "tool" }, + status = t.textAny("status"), + summary = t.textAny("summary"), + ) + } + val tools = obj.arrOrNull("toolCalls").orEmpty().mapNotNull(::tool) + val content = obj.textOrNull("content") + // Fall back to the terminal `done` stream event if top-level content is absent. + ?: obj.arrOrNull("events").orEmpty().asReversed().firstNotNullOfOrNull { e -> + e.asObject()?.takeIf { it.textOrNull("type") == "done" }?.textOrNull("content") + } + ?: return null + return SideChatReply(content, tools) +} + +/** Last [maxTurns] user→assistant pairs as side-chat context (text truncated like desktop: 600 chars). */ +fun buildSideChatContext(items: List, maxTurns: Int = 6, maxChars: Int = 600): List { + fun clip(s: String): String = s.trim().let { if (it.length <= maxChars) it else it.take(maxChars) + "…" } + val turns = mutableListOf() + var user: String? = null + var assistant = StringBuilder() + fun flush() { + val u = user + if (u != null) turns += SideChatContextTurn(turns.size + 1, clip(u), clip(assistant.toString())) + user = null + assistant = StringBuilder() + } + for (item in items) { + when (item.role) { + TimelineItem.Role.User -> { flush(); user = item.text } + TimelineItem.Role.Assistant -> if (user != null && item.text.isNotBlank()) { + if (assistant.isNotEmpty()) assistant.append("\n\n") + assistant.append(item.text.trim()) + } + TimelineItem.Role.Divider -> {} + } + } + flush() + return turns.takeLast(maxTurns).mapIndexed { i, t -> t.copy(turnNumber = i + 1) } +} + +fun HostApi.providerInstances(origin: HostOrigin, token: String): List = + parseProviderInstances(call(origin, token, "provider_instances_list", emptyMap())) + +fun HostApi.previewEngineHandoff( + origin: HostOrigin, + token: String, + conversationId: String, + targetEngine: String, + targetProviderInstanceId: String?, + tokenBudget: Int? = null, +): EngineHandoffPreview = + parseEngineHandoffPreview( + call(origin, token, "conversation_preview_engine_handoff", handoffArgs(conversationId, targetEngine, targetProviderInstanceId, tokenBudget)), + ) ?: throw HostApiException(500, "Host 返回了无法识别的交接预览") + +fun HostApi.confirmEngineHandoff( + origin: HostOrigin, + token: String, + conversationId: String, + targetEngine: String, + targetProviderInstanceId: String?, +) { + call(origin, token, "conversation_confirm_engine_handoff", handoffArgs(conversationId, targetEngine, targetProviderInstanceId, null)) +} + +internal fun handoffArgs( + conversationId: String, + targetEngine: String, + targetProviderInstanceId: String?, + tokenBudget: Int?, +): Map { + val args = linkedMapOf("conversationId" to conversationId, "targetEngine" to targetEngine) + if (!targetProviderInstanceId.isNullOrBlank()) args["targetProviderInstanceId"] = targetProviderInstanceId + if (tokenBudget != null && tokenBudget > 0) args["tokenBudget"] = tokenBudget.toDouble() + return args +} + +fun HostApi.sideChatSend( + origin: HostOrigin, + token: String, + conversationId: String, + sideChatId: String, + prompt: String, + contextTurns: List, + history: List, +): SideChatReply = + parseSideChatReply( + call( + origin, + token, + "conversation_side_chat_send", + sideChatArgs(conversationId, sideChatId, prompt, contextTurns, history), + ), + ) ?: throw HostApiException(500, "Host 返回了无法识别的旁路对话结果") + +fun HostApi.sideChatAbort(origin: HostOrigin, token: String, conversationId: String, sideChatId: String) { + call(origin, token, "conversation_side_chat_abort", mapOf("conversationId" to conversationId, "sideChatId" to sideChatId)) +} + +internal fun sideChatArgs( + conversationId: String, + sideChatId: String, + prompt: String, + contextTurns: List, + history: List, +): Map = mapOf( + "conversationId" to conversationId, + "sideChatId" to sideChatId, + "prompt" to prompt, + "contextTurns" to contextTurns.map { + mapOf("turnNumber" to it.turnNumber.toDouble(), "userText" to it.userText, "assistantText" to it.assistantText) + }, + "history" to history.filter { !it.isError }.map { mapOf("role" to it.role, "content" to it.content) }, +) diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/HostApi.kt b/companion-core/src/main/kotlin/dev/vibex/companion/HostApi.kt index fc26cd8..75dffac 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/HostApi.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/HostApi.kt @@ -2,6 +2,13 @@ package dev.vibex.companion import dev.vibex.remote.v1.JsonValue import dev.vibex.remote.v1.RemoteEvent +import java.time.Instant +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import java.time.format.DateTimeFormatterBuilder +import java.time.temporal.ChronoField import java.util.UUID data class ConversationSummary( @@ -27,7 +34,41 @@ data class CatalogAgent( val usable: Boolean = true, val lifecycle: String = "", val authentication: String = "", -) +) { + val modelOptions: List + get() { + val matched = sessionConfig.filter { + val cat = it.category.lowercase() + val key = it.key.lowercase() + cat == "model" || key == "model" || key.contains("model") + } + if (matched.isNotEmpty() && matched.any { it.choices.isNotEmpty() }) { + return matched + } + return listOf(fallbackModelOptionForAgent(id)) + } + + val otherOptions: List + get() = sessionConfig.filter { + val cat = it.category.lowercase() + val key = it.key.lowercase() + cat != "model" && cat != "mode" && key != "model" && !key.contains("model") && key != "mode" + } + + companion object { + fun makeCustomChoice(modelId: String): SessionConfigChoice = + SessionConfigChoice(value = modelId, label = modelId, description = "自定义 / 中转模型") + + fun makeCustomModelOption(key: String = "model", modelId: String): SessionConfigOption = + SessionConfigOption( + key = key, + label = "模型", + category = "model", + value = modelId, + choices = listOf(makeCustomChoice(modelId)), + ) + } +} data class CatalogTag(val id: String, val name: String, val content: String = "") data class WorkspaceEntry(val name: String, val path: String, val directory: Boolean) @@ -136,6 +177,9 @@ class HostApi( fun catalog(origin: HostOrigin, token: String): SessionCatalog { val data = call(origin, token, "conversation_catalog", emptyMap()) val root = data.asObject() ?: return SessionCatalog(emptyList(), emptyList(), emptyList()) + val managementBar = runCatching { + call(origin, token, "agent_management_bar", emptyMap()) + }.getOrNull() return SessionCatalog( projects = root.arrOrNull("projects").orEmpty().mapNotNull { item -> val obj = item.asObject() ?: return@mapNotNull null @@ -154,41 +198,7 @@ class HostApi( obj.textAny("branch"), ) }, - agents = root.arrOrNull("agents").orEmpty().mapNotNull { item -> - val obj = item.asObject() ?: return@mapNotNull null - val ready = obj.boolOrNull("ready") ?: true - val lifecycle = obj.textAny("lifecycle") - val authentication = obj.textAny("authentication") - val agentId = obj.textAny("id") - val parsedConfig = parseJsonOptions( - obj, - "sessionConfigJson", - "session_config_json", - "sessionConfig", - "session_config", - "configOptions", - "config_options", - "controls", - ) - CatalogAgent( - id = agentId, - ready = ready, - displayName = obj.textAny("displayName", "display_name", "name"), - iconSvg = obj.textAny("iconSvg", "icon_svg"), - currentModeId = parseCurrentMode(obj), - sessionConfig = ensureAgentDefaultOptions(agentId, parsedConfig), - sessionModes = parseJsonModes( - obj, - "sessionModesJson", - "session_modes_json", - "sessionModes", - "session_modes", - ).ifEmpty { extractModesFromControls(obj) }, - usable = obj.boolOrNull("usable") ?: agentIsUsable(ready, lifecycle, authentication), - lifecycle = lifecycle, - authentication = authentication, - ) - }, + agents = parseCatalogAgents(root, managementBar), tags = root.arrOrNull("tags").orEmpty().mapNotNull { item -> val obj = item.asObject() ?: return@mapNotNull null val name = obj.textAny("name", "tagName", "tag_name") @@ -465,6 +475,45 @@ class HostApi( } + /** Light `conversation_detail` read used for steering capability + current turn. */ + fun conversationDetailLight(origin: HostOrigin, token: String, conversationId: String): JsonValue = + call( + origin, + token, + "conversation_detail", + mapOf("conversationId" to conversationId, "tailTurns" to 1.0), + ) + + fun rateLimitUpdateAutoResume( + origin: HostOrigin, + token: String, + conversationId: String, + autoResume: Boolean, + continuationPrompt: String? = null, + ) { + call( + origin, + token, + "conversation_rate_limit_update_auto_resume", + mapOf( + "request" to mapOf( + "conversationId" to conversationId, + "autoResume" to autoResume, + "continuationPrompt" to continuationPrompt, + ), + ), + ) + } + + fun rateLimitCancelWait(origin: HostOrigin, token: String, conversationId: String) { + call( + origin, + token, + "conversation_rate_limit_cancel_wait", + mapOf("request" to mapOf("conversationId" to conversationId)), + ) + } + fun cancelConversationInput( origin: HostOrigin, token: String, @@ -680,8 +729,15 @@ class HostApi( } } - fun collaboration(origin: HostOrigin, token: String, operation: String, input: Map): JsonValue { + fun collaboration( + origin: HostOrigin, + token: String, + operation: String, + input: Map, + operationId: String = UUID.randomUUID().toString(), + ): JsonValue { return call( + operationId = operationId, origin = origin, token = token, command = "collaboration_call", @@ -951,8 +1007,13 @@ class HostApi( ) } - fun call(origin: HostOrigin, token: String, command: String, args: Map): JsonValue { - val operationId = UUID.randomUUID().toString() + fun call( + origin: HostOrigin, + token: String, + command: String, + args: Map, + operationId: String = UUID.randomUUID().toString(), + ): JsonValue { val body = encodeObject( mapOf( "operation_id" to operationId, @@ -1094,6 +1155,108 @@ private fun unwrapObject(node: JsonValue?): JsonValue.Object? = when (node) { else -> null } +internal fun parseCatalogAgents( + root: JsonValue.Object, + managementBar: JsonValue? = null, +): List { + val rawAgents = root.arrOrNull("agents").orEmpty() + if (rawAgents.isEmpty()) return emptyList() + + var managementRunnableIds: Set? = null + val managementPositions = mutableMapOf() + val barRows = managementBar?.asArray()?.value + ?: managementBar?.asObject()?.arrOrNull("items", "entries") + if (!barRows.isNullOrEmpty()) { + val runnable = mutableSetOf() + var sawBarEntry = false + barRows.forEachIndexed { idx, rowItem -> + val row = rowItem.asObject() ?: return@forEachIndexed + val id = row.textAny("agent_id", "agentId").trim() + if (id.isEmpty()) return@forEachIndexed + sawBarEntry = true + val pos = row.longOrNull("position")?.toInt() ?: idx + managementPositions[id] = pos + val enabled = row.boolOrNull("enabled") == true + val retired = row.boolOrNull("retired") == true + val lifecycle = row.textAny("lifecycle").trim().lowercase() + val activeOp = row.textAny("active_operation", "activeOperation").trim() + val localPath = ( + row.objOrNull("local_runtime")?.textAny("path") + ?: row.objOrNull("localRuntime")?.textAny("path") + ).orEmpty().trim() + if (enabled && !retired && activeOp.isEmpty() && (lifecycle == "ready" || localPath.isNotEmpty())) { + runnable += id + } + } + if (sawBarEntry) { + managementRunnableIds = runnable + } + } + + val hasLifecycleSignal = rawAgents.any { item -> + item.asObject()?.textAny("lifecycle")?.trim()?.isNotEmpty() == true + } + + val indexed = rawAgents.mapIndexedNotNull { originalIdx, item -> + val obj = item.asObject() ?: return@mapIndexedNotNull null + val agentId = obj.textAny("id") + if (agentId.isBlank()) return@mapIndexedNotNull null + val ready = obj.boolOrNull("ready") ?: true + val lifecycle = obj.textAny("lifecycle").trim() + val authentication = obj.textAny("authentication") + val parsedConfig = parseJsonOptions( + obj, + "sessionConfigJson", + "session_config_json", + "sessionConfig", + "session_config", + "configOptions", + "config_options", + "controls", + ) + val parsedModes = parseJsonModes( + obj, + "sessionModesJson", + "session_modes_json", + "sessionModes", + "session_modes", + ).ifEmpty { extractModesFromControls(obj) } + val catalogUsable = obj.boolOrNull("usable") ?: agentIsUsable(ready, lifecycle, authentication) + val runnableSet = managementRunnableIds + val effectiveUsable = when { + runnableSet != null -> catalogUsable && agentId in runnableSet + hasLifecycleSignal -> { + val isInstalledByCatalog = lifecycle.equals("ready", ignoreCase = true) || + parsedConfig.isNotEmpty() || + parsedModes.isNotEmpty() + catalogUsable && isInstalledByCatalog + } + else -> catalogUsable + } + originalIdx to CatalogAgent( + id = agentId, + ready = ready, + displayName = obj.textAny("displayName", "display_name", "name").ifBlank { agentId }, + iconSvg = obj.textAny("iconSvg", "icon_svg"), + currentModeId = parseCurrentMode(obj), + sessionConfig = parsedConfig, + sessionModes = parsedModes, + usable = effectiveUsable, + lifecycle = lifecycle, + authentication = authentication, + ) + } + + if (managementPositions.isEmpty()) { + return indexed.map { it.second } + } + return indexed.sortedWith { lhs, rhs -> + val lPos = managementPositions[lhs.second.id] ?: (10_000 + lhs.first) + val rPos = managementPositions[rhs.second.id] ?: (10_000 + rhs.first) + if (lPos != rPos) lPos.compareTo(rPos) else lhs.first.compareTo(rhs.first) + }.map { it.second } +} + fun fallbackModelOptionForAgent(agentId: String): SessionConfigOption { val lower = agentId.lowercase() return when { @@ -1101,15 +1264,14 @@ fun fallbackModelOptionForAgent(agentId: String): SessionConfigOption { key = "model", label = "模型", category = "model", - value = "default", + value = "opus", choices = listOf( - SessionConfigChoice("default", "Default (推荐)"), - SessionConfigChoice("opus", "Claude Opus 4.7"), - SessionConfigChoice("sonnet", "Claude Sonnet 4.6"), - SessionConfigChoice("haiku", "Claude Haiku 4.5"), - SessionConfigChoice("claude-opus-4-8", "Claude Opus 4.8 (中转)"), - SessionConfigChoice("claude-sonnet-5", "Claude Sonnet 5 (中转)"), - SessionConfigChoice("claude-haiku-5-5", "Claude Haiku 5.5 (中转)"), + SessionConfigChoice("opus", "Claude Opus 4.6", "最强深度推理与复杂工程"), + SessionConfigChoice("sonnet", "Claude Sonnet 4.6", "日常开发主力 · 均衡高速"), + SessionConfigChoice("haiku", "Claude Haiku 4.5", "轻量极速响应"), + SessionConfigChoice("claude-opus-4-8", "claude-opus-4-8", "自定义 / 中转 Opus"), + SessionConfigChoice("claude-sonnet-5", "claude-sonnet-5", "自定义 / 中转 Sonnet"), + SessionConfigChoice("claude-haiku-5-5", "claude-haiku-5-5", "自定义 / 中转 Haiku"), ), ) lower.contains("codex") || lower.contains("openai") -> SessionConfigOption( @@ -1118,10 +1280,12 @@ fun fallbackModelOptionForAgent(agentId: String): SessionConfigOption { category = "model", value = "gpt-5.4", choices = listOf( - SessionConfigChoice("gpt-5.4", "GPT-5.4"), - SessionConfigChoice("gpt-5.3-codex", "GPT-5.3-Codex"), - SessionConfigChoice("gpt-5.4-mini", "GPT-5.4-Mini"), - SessionConfigChoice("gpt-6-sol", "GPT-6-Sol (中转)"), + SessionConfigChoice("gpt-5.4", "GPT-5.4", "OpenAI 旗舰代码与推理模型"), + SessionConfigChoice("gpt-5.3-codex", "GPT-5.3 Codex", "专为软件工程优化的 Codex 模型"), + SessionConfigChoice("gpt-5.2-codex", "GPT-5.2 Codex", "稳健高速代码生成"), + SessionConfigChoice("gpt-6-sol", "gpt-6-sol", "自定义 / 中转旗舰模型"), + SessionConfigChoice("o3", "o3", "深度推理模型"), + SessionConfigChoice("o4-mini", "o4-mini", "高性价比快速推理"), ), ) lower.contains("gemini") || lower.contains("antigravity") -> SessionConfigOption( @@ -1130,8 +1294,10 @@ fun fallbackModelOptionForAgent(agentId: String): SessionConfigOption { category = "model", value = "gemini-2.5-pro", choices = listOf( - SessionConfigChoice("gemini-2.5-pro", "Gemini 2.5 Pro"), - SessionConfigChoice("gemini-2.5-flash", "Gemini 2.5 Flash"), + SessionConfigChoice("gemini-2.5-pro", "Gemini 2.5 Pro", "旗舰多模态与深度长上下文推理"), + SessionConfigChoice("gemini-2.5-flash", "Gemini 2.5 Flash", "高速低延迟日常主力"), + SessionConfigChoice("gemini-3.8-flash", "Gemini 3.8 Flash", "新一代高速推理"), + SessionConfigChoice("gemini-4-argon", "Gemini 4 Argon", "前沿旗舰推理"), ), ) lower.contains("kimi") -> SessionConfigOption( @@ -1140,18 +1306,30 @@ fun fallbackModelOptionForAgent(agentId: String): SessionConfigOption { category = "model", value = "kimi-k2", choices = listOf( - SessionConfigChoice("kimi-k2", "Kimi K2"), - SessionConfigChoice("kimi-latest", "Kimi Latest"), + SessionConfigChoice("kimi-k2", "Kimi K2", "Moonshot 旗舰代码与推理"), + SessionConfigChoice("kimi-latest", "Kimi Latest", "最新默认模型"), + SessionConfigChoice("moonshot-v1-128k", "Moonshot v1 128K", "长上下文模型"), ), ) lower.contains("deepseek") -> SessionConfigOption( key = "model", label = "模型", category = "model", - value = "deepseek-reasoner", + value = "deepseek-chat", + choices = listOf( + SessionConfigChoice("deepseek-chat", "DeepSeek V3", "高效日常对话与编码"), + SessionConfigChoice("deepseek-reasoner", "DeepSeek R1", "深度思考推理模型"), + ), + ) + lower.contains("grok") -> SessionConfigOption( + key = "model", + label = "模型", + category = "model", + value = "grok-4", choices = listOf( - SessionConfigChoice("deepseek-reasoner", "DeepSeek R1"), - SessionConfigChoice("deepseek-chat", "DeepSeek V3"), + SessionConfigChoice("grok-4", "Grok 4", "xAI 旗舰推理模型"), + SessionConfigChoice("grok-3", "Grok 3", "标准主力模型"), + SessionConfigChoice("grok-3-mini", "Grok 3 Mini", "轻量快速思考"), ), ) else -> SessionConfigOption( @@ -1160,47 +1338,48 @@ fun fallbackModelOptionForAgent(agentId: String): SessionConfigOption { category = "model", value = "default", choices = listOf( - SessionConfigChoice("default", "默认模型"), + SessionConfigChoice("default", "默认模型 (跟随电脑端配置)", "使用电脑端当前配置的默认模型"), + SessionConfigChoice("claude-sonnet-4-6", "Claude Sonnet 4.6", "通用主力代码模型"), + SessionConfigChoice("claude-opus-4-6", "Claude Opus 4.6", "深度推理旗舰"), + SessionConfigChoice("gpt-5.4", "GPT-5.4", "OpenAI 旗舰模型"), + SessionConfigChoice("gemini-2.5-pro", "Gemini 2.5 Pro", "Google 旗舰模型"), ), ) } } -private fun ensureAgentDefaultOptions( - agentId: String, - options: List, -): List { - val result = options.toMutableList() - val hasModel = result.any { - val k = it.key.lowercase() - val c = it.category.lowercase() - (c == "model" || k == "model" || k.contains("model")) && it.choices.isNotEmpty() - } - if (!hasModel) { - result.add(0, fallbackModelOptionForAgent(agentId)) - } - val hasEffort = result.any { - val k = it.key.lowercase() - val c = it.category.lowercase() - c.contains("thought") || c.contains("effort") || c.contains("reason") || - k.contains("thought") || k.contains("effort") || k.contains("thinking") || k.contains("reason") - } - if (!hasEffort) { - result.add( - SessionConfigOption( - key = "reasoning_effort", - label = "推理强度", - category = "thought_level", - value = "medium", - choices = listOf( - SessionConfigChoice("low", "低"), - SessionConfigChoice("medium", "中"), - SessionConfigChoice("high", "高"), - ), - ), - ) +private val SQLITE_UTC_FORMATTER: DateTimeFormatter = DateTimeFormatterBuilder() + .appendPattern("yyyy-MM-dd HH:mm:ss") + .optionalStart() + .appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true) + .optionalEnd() + .toFormatter() + +fun parseHostTimestampEpochMillis(raw: String?): Long? { + val trimmed = raw?.trim().orEmpty() + if (trimmed.isEmpty()) return null + runCatching { return Instant.parse(trimmed).toEpochMilli() } + runCatching { return OffsetDateTime.parse(trimmed).toInstant().toEpochMilli() } + runCatching { + val normalized = trimmed.removeSuffix("Z").removeSuffix("z").trim() + return LocalDateTime.parse(normalized, SQLITE_UTC_FORMATTER) + .toInstant(ZoneOffset.UTC) + .toEpochMilli() } - return result + return null +} + +val KanbanSessionSummary.updatedEpochMs: Long? + get() = parseHostTimestampEpochMillis(updatedAt) ?: parseHostTimestampEpochMillis(createdAt) + +fun KanbanSessionSummary.isRecentlyActiveReadSession( + manuallyCompletedIds: Set, + nowMs: Long = System.currentTimeMillis(), +): Boolean { + if (status != KanbanSessionStatus.Done || isRunning) return false + if (id in manuallyCompletedIds) return false + val epochMs = updatedEpochMs ?: return false + return (nowMs - epochMs) <= 24L * 3600_000L } fun encodeObject(map: Map): String = encodeValue(map).encode() diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt b/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt index ceefc33..f494112 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt @@ -59,7 +59,20 @@ data class DiscoveredLanHost( val origin: String, val hostId: String?, val name: String, -) +) { + val id: String + get() = hostId ?: origin + + val isCloudService: Boolean + get() = origin.contains("/t/") || origin.contains("dimo-ai.com") || origin.contains("vibex.xforever.xin") + + val displayName: String + get() { + val trimmed = name.trim() + if (trimmed.isNotEmpty() && !trimmed.startsWith("http")) return trimmed + return origin.removePrefix("http://").removePrefix("https://") + } +} data class DeviceConnectRequestResult( val requestId: String, @@ -231,20 +244,65 @@ class PairingClient( companion object { const val CLIENT_PROTOCOL_VERSION = "1.0" - const val PROTOCOL_HEADER = "x-vibex-protocol-version" + const val PROTOCOL_HEADER = "x-dimo-protocol-version" const val DEFAULT_OFFICIAL_RELAY_PORT = 443 + private const val OFFICIAL_DOMAIN_BASE = "https://dimo-ai.com" + private val LEGACY_RELAY_TENANT_REGEX = + Regex("""^https?://vibex\.xforever\.xin(?::(?:80|443))?/t/(.+)$""", RegexOption.IGNORE_CASE) + private val IGNORED_INTERFACE_PREFIXES = listOf( + "rmnet", "ccmni", "pdp", "clat", "v4-", "dummy", "lo", + "utun", "tun", "tap", "ppp", "ipsec", "wg", "tailscale", + "clash", "mihomo", "surge", + ) + private val ALLOWED_LAN_INTERFACE_PREFIXES = listOf( + "wlan", "eth", "en", "ap", "swlan", "wifi", "rndis", "usb", + ) + val DEFAULT_OFFICIAL_RELAY_BASE: String = - System.getenv("VIBEX_RELAY_URL")?.trim()?.takeIf { it.isNotEmpty() } ?: "https://vibex.xforever.xin" + (System.getenv("DIMO_RELAY_URL") ?: System.getenv("VIBEX_RELAY_URL")) + ?.trim() + ?.trimEnd('/') + ?.takeIf { it.isNotEmpty() } + ?.let { raw -> + if (raw.contains("vibex.xforever.xin", ignoreCase = true)) OFFICIAL_DOMAIN_BASE else raw + } + ?: OFFICIAL_DOMAIN_BASE const val HAPPY_EYEBALLS_LAN_WINDOW_MS = 250L private val rememberedRelayBases = java.util.concurrent.CopyOnWriteArraySet( listOf(DEFAULT_OFFICIAL_RELAY_BASE).filter { it.isNotBlank() }, ) + fun migrateLegacyRelayOrigin(url: String): String { + val trimmed = url.trim() + val match = LEGACY_RELAY_TENANT_REGEX.matchEntire(trimmed) + if (match != null) { + val rest = match.groupValues[1].trimEnd('/') + if (rest.isNotEmpty()) { + return "$OFFICIAL_DOMAIN_BASE/t/$rest" + } + } + return url + } + + fun isScannableLanInterfaceName(rawName: String?): Boolean { + val name = rawName?.trim()?.lowercase().orEmpty() + if (name.isEmpty()) return false + if ( + IGNORED_INTERFACE_PREFIXES.any { prefix -> + name.startsWith(prefix) || + ((prefix == "clash" || prefix == "mihomo" || prefix == "surge") && name.contains(prefix)) + } + ) { + return false + } + return ALLOWED_LAN_INTERFACE_PREFIXES.any { name.startsWith(it) } + } + fun rememberRelayBase(originOrBaseUrl: String) { - val trimmed = originOrBaseUrl.trim().trimEnd('/') + val trimmed = migrateLegacyRelayOrigin(originOrBaseUrl.trim()).trimEnd('/') if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return - val base = if (trimmed.contains("/t/")) { + val rawBase = if (trimmed.contains("/t/")) { trimmed.substringBefore("/t/") } else { val uri = runCatching { URI(trimmed) }.getOrNull() ?: return @@ -252,6 +310,11 @@ class PairingClient( val port = if (uri.port == -1) "" else ":${uri.port}" "${uri.scheme}://$host$port" } + val base = if (rawBase.contains("vibex.xforever.xin", ignoreCase = true)) { + OFFICIAL_DOMAIN_BASE + } else { + rawBase + } if ( base.isNotBlank() && !base.contains("127.0.0.1") && @@ -269,16 +332,21 @@ class PairingClient( } } val bases = LinkedHashSet() - System.getProperty("vibex.relay.url")?.trim()?.takeIf { it.isNotEmpty() }?.let { - rememberRelayBase(it) - } - bases.addAll(rememberedRelayBases) + (System.getProperty("dimo.relay.url") ?: System.getProperty("vibex.relay.url")) + ?.trim() + ?.takeIf { it.isNotEmpty() } + ?.let { rememberRelayBase(it) } + bases.addAll( + rememberedRelayBases.map { + if (it.contains("vibex.xforever.xin", ignoreCase = true)) OFFICIAL_DOMAIN_BASE else it + }, + ) return bases.toList() } fun probeHostHealth( originUrl: String, - timeoutMs: Int = 350, + timeoutMs: Int = 800, expectedHostId: String? = null, ): DiscoveredLanHost? { return runCatching { @@ -321,31 +389,25 @@ class PairingClient( }.getOrNull() } - fun discoverLanHosts(port: Int = 17891): List { + fun discoverLanHosts( + port: Int = 17891, + includeEmulatorLoopback: Boolean = false, + ): List { val candidates = LinkedHashSet() - val localPorts = (listOf(port, 17899) + (17891..17899)).distinct() - for (localPort in localPorts) { - candidates.add("http://127.0.0.1:$localPort") - candidates.add("http://10.0.2.2:$localPort") + if (includeEmulatorLoopback) { + val localPorts = (listOf(port, 17899) + (17891..17899)).distinct() + for (localPort in localPorts) { + candidates.add("http://127.0.0.1:$localPort") + candidates.add("http://10.0.2.2:$localPort") + } } val lanPorts = listOf(port, 17899).distinct() runCatching { val interfaces = NetworkInterface.getNetworkInterfaces()?.toList().orEmpty() for (iface in interfaces) { - val name = iface.name?.lowercase().orEmpty() if (!iface.isUp || iface.isLoopback) continue - if ( - name.startsWith("utun") || - name.startsWith("tun") || - name.startsWith("tap") || - name.startsWith("ppp") || - name.contains("clash") || - name.contains("mihomo") || - name.contains("surge") - ) { - continue - } + if (!isScannableLanInterfaceName(iface.name)) continue for (addr in iface.inetAddresses.toList()) { if (addr !is Inet4Address || addr.isLoopbackAddress) continue val raw = addr.address @@ -370,7 +432,9 @@ class PairingClient( } } - val pool = Executors.newFixedThreadPool(64) + if (candidates.isEmpty()) return emptyList() + + val pool = Executors.newFixedThreadPool(minOf(64, candidates.size)) val localFound = try { val tasks = candidates.map { url -> Callable { probeHostHealth(url, timeoutMs = 280) } @@ -403,7 +467,7 @@ class PairingClient( fun resolveHostRendezvous( hostId: String, knownOrigins: Collection = emptyList(), - timeoutMs: Int = 2000, + @Suppress("UNUSED_PARAMETER") timeoutMs: Int = 2000, ): List { val cleanId = hostId.trim() if (cleanId.isEmpty() || cleanId.startsWith("host:")) return emptyList() @@ -411,18 +475,9 @@ class PairingClient( if (bases.isEmpty()) return emptyList() val resolved = LinkedHashSet() - // 1. Deterministic multi-tenant path on every known domestic relay base (0ms) for (base in bases) { resolved.add("${base.trimEnd('/')}/t/$cleanId") } - // 2. Domestic beacon lookup on each relay base - val topicHash = sha256Hex("vibex-host-v1:$cleanId").take(32) - val topic = "vbx-h-$topicHash" - for (base in bases) { - for (origin in queryDomesticBeaconOrigins(base, topic, expectedHostId = cleanId, timeoutMs = timeoutMs)) { - resolved.add(origin) - } - } return resolved.toList() } @@ -483,6 +538,10 @@ class PairingClient( } } +/** Mutating requests (message submit, input) can be slow behind E2EE/relay; give them more time than reads. */ +fun requestReadTimeoutMs(method: String, isPrivateLan: Boolean): Int = + if (!method.equals("GET", ignoreCase = true)) 60_000 else if (isPrivateLan) 15_000 else 20_000 + class UrlConnectionTransport : HttpTransport { override fun execute( method: String, @@ -490,9 +549,11 @@ class UrlConnectionTransport : HttpTransport { headers: Map, body: String?, ): HttpExchange { + val hadActiveE2ee = E2eeSessionManager.isE2eeActive(url) val first = executeOnce(method, url, headers, body, allowBootstrap = true) - if (first.status == 412) { - return executeOnce(method, url, headers, body, allowBootstrap = false) + if (first.status == 412 || (first.status == 401 && hadActiveE2ee)) { + E2eeSessionManager.clearSession(url) + return executeOnce(method, url, headers, body, allowBootstrap = true) } return first } @@ -528,8 +589,8 @@ class UrlConnectionTransport : HttpTransport { } val connection = URI(url).toURL().openConnection() as HttpURLConnection - connection.connectTimeout = if (isPrivateLan) 2_200 else 10_000 - connection.readTimeout = if (isPrivateLan) 4_000 else 20_000 + connection.connectTimeout = if (isPrivateLan) 2_500 else 10_000 + connection.readTimeout = requestReadTimeoutMs(method, isPrivateLan) connection.requestMethod = method connection.doInput = true val mutableHeaders = LinkedHashMap(headers) diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/PairingCoordinator.kt b/companion-core/src/main/kotlin/dev/vibex/companion/PairingCoordinator.kt index a7d85e7..3976886 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/PairingCoordinator.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/PairingCoordinator.kt @@ -10,7 +10,7 @@ data class PairingResult( /** Every invitation origin is on the computer's LAN and none answered, e.g. the phone is on cellular data. */ class LocalNetworkUnreachableException : - RuntimeException("电脑未开启云服务。请连接与电脑相同的 Wi-Fi,或在电脑上登录 VibeX 账号") + RuntimeException("电脑未开启云服务。请连接与电脑相同的 Wi-Fi,或在电脑上登录 Dimo 账号") class PairingCoordinator( private val client: PairingClient = PairingClient(), diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/PairingInvitation.kt b/companion-core/src/main/kotlin/dev/vibex/companion/PairingInvitation.kt index 77158cd..fa7797d 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/PairingInvitation.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/PairingInvitation.kt @@ -25,11 +25,12 @@ object PairingInvitationParser { val trimmed = raw.trim() val payload = when { trimmed.startsWith("vibex-pairing:") -> trimmed.removePrefix("vibex-pairing:") + trimmed.startsWith("dimo-pairing:") -> trimmed.removePrefix("dimo-pairing:") trimmed.startsWith("{") -> trimmed - else -> throw PairingException("这不是 VibeX 邀请") + else -> throw PairingException("这不是 Dimo 邀请") } val root = runCatching { JsonValue.parse(payload) as JsonValue.Object } - .getOrElse { throw PairingException("这不是 VibeX 邀请") } + .getOrElse { throw PairingException("这不是 Dimo 邀请") } val token = root.textOrNull("pairing_token") ?: throw PairingException("邀请缺少 pairing token") if (token.startsWith("vbx_device_") || token.length > 400 && !token.startsWith("vbx_pair_")) { @@ -49,7 +50,7 @@ object PairingInvitationParser { fun parseManual(origin: String, pairingToken: String): PairingInvitation { val raw = pairingToken.trim() if (raw.isEmpty()) throw PairingException("需要连接码") - if (raw.startsWith("vibex-pairing:") || raw.startsWith("{")) { + if (raw.startsWith("vibex-pairing:") || raw.startsWith("dimo-pairing:") || raw.startsWith("{")) { return parse(raw) } if (raw.startsWith("vbx_device_", ignoreCase = true)) { diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/QuestionForm.kt b/companion-core/src/main/kotlin/dev/vibex/companion/QuestionForm.kt index 91bdf01..984e919 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/QuestionForm.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/QuestionForm.kt @@ -66,7 +66,7 @@ object QuestionForm { ): JsonValue { val schemaObj = request.schema?.asObject()?.value val hasSchemaProps = (schemaObj?.get("properties")?.asObject()?.value?.isNotEmpty() == true) || - (schemaObj?.get("x-vibex-questions")?.asArray()?.value?.isNotEmpty() == true) + (schemaObj?.get("x-dimo-questions")?.asArray()?.value?.isNotEmpty() == true) if (!hasSchemaProps && questions.size == 1 && questions.first().id == "answer") { val answer = answers["answer"] ?: QuestionAnswer() @@ -93,7 +93,7 @@ object QuestionForm { payload[question.id] = JsonValue.Text(trimmed) } else if (answer.selected.isNotEmpty()) { val first = answer.selected.first() - if (request.options.isNotEmpty() && schemaObj?.get("x-vibex-questions") == null) { + if (request.options.isNotEmpty() && schemaObj?.get("x-dimo-questions") == null) { payload["option_id"] = JsonValue.Text(first) } payload[question.id] = JsonValue.Text(first) @@ -104,7 +104,7 @@ object QuestionForm { fun parseQuestions(schema: JsonValue): List { val root = schema.asObject()?.value ?: return emptyList() - val vibexQuestions = root["x-vibex-questions"]?.asArray()?.value + val vibexQuestions = root["x-dimo-questions"]?.asArray()?.value if (!vibexQuestions.isNullOrEmpty()) { val requiredSet = root["required"]?.asArray()?.value ?.mapNotNull { it.asText() } diff --git a/companion-core/src/main/kotlin/dev/vibex/companion/TimelineModels.kt b/companion-core/src/main/kotlin/dev/vibex/companion/TimelineModels.kt index b3ee86d..7c1417c 100644 --- a/companion-core/src/main/kotlin/dev/vibex/companion/TimelineModels.kt +++ b/companion-core/src/main/kotlin/dev/vibex/companion/TimelineModels.kt @@ -391,7 +391,7 @@ data class TimelineItem( val streaming: Boolean = false, val modelName: String? = null, ) { - enum class Role { User, Assistant } + enum class Role { User, Assistant, Divider } } object ToolInput { @@ -486,7 +486,7 @@ object ToolInput { private fun extractQuestions(dict: Map): List { val list = dict["questions"]?.asArray()?.value if (!list.isNullOrEmpty()) { - val wrapped = JsonValue.Object(mapOf("x-vibex-questions" to JsonValue.Array(list))) + val wrapped = JsonValue.Object(mapOf("x-dimo-questions" to JsonValue.Array(list))) val parsed = QuestionForm.parseQuestions(wrapped) if (parsed.isNotEmpty()) return parsed } @@ -661,6 +661,15 @@ data class QueuedInput( val sortKey: Long = 0, ) +/** Rate-limit recovery state derived from a `rate_limited` turn error (host push channel is not on the remote WS). */ +data class RateLimitBanner( + val rowId: String, + val engine: String, + val resetAtMs: Long? = null, + val retryAfterSeconds: Long? = null, + val message: String = "", +) + data class SessionNotice( val id: String, val severity: NoticeSeverity, @@ -672,6 +681,7 @@ data class SessionNotice( data class SessionConfigChoice( val value: String, val label: String, + val description: String? = null, ) data class SessionConfigOption( @@ -700,7 +710,10 @@ data class ConversationView( val pendingQuestion: PendingQuestion? = null, val queued: List, val inFlightTurnId: String?, + val isThinkingOrRunning: Boolean = inFlightTurnId != null, val canSteer: Boolean, + val steeringKnown: Boolean = false, + val rateLimit: RateLimitBanner? = null, val lastSequence: Long, val usageLabel: String?, val planLines: List, @@ -722,7 +735,13 @@ class TimelineSession { var workspaceId: String = "" var lastSequence: Long = 0 var inFlightTurnId: String? = null + var optimisticUserText: String? = null + var optimisticBaselineUserCount: Int = 0 + var optimisticThinkingUntilMs: Long = 0L var canSteer: Boolean = false + /** True once the host told us the binding's steering capability (conversation_detail). */ + var steeringKnown: Boolean = false + var rateLimit: RateLimitBanner? = null var usageLabel: String? = null var fileChangeLabel: String? = null var agentStatus: String = "" @@ -742,8 +761,32 @@ class TimelineSession { val availableCommands: MutableList = mutableListOf() val skillCommands: MutableList = mutableListOf() - fun snapshot(): ConversationView { + fun beginOptimisticSend(text: String, nowMs: Long = System.currentTimeMillis()) { + val trimmed = text.trim() + if (trimmed.isEmpty()) return + optimisticUserText = trimmed + optimisticBaselineUserCount = rows.count { it.kind == "user" && it.id.startsWith("tx:user:") } + optimisticThinkingUntilMs = nowMs + 15_000L + notices.removeAll { it.id.startsWith("end:") } + rows.removeAll { it.id.startsWith("end:") || it.id.startsWith("local:") } + rows += TimelineRow( + id = "local:$nowMs", + kind = "user", + title = "", + body = text, + tone = TimelineTone.Quiet, + ) + } + + fun clearOptimisticSend() { + optimisticUserText = null + optimisticThinkingUntilMs = 0L + rows.removeAll { it.id.startsWith("local:") } + } + + fun snapshot(nowMs: Long = System.currentTimeMillis()): ConversationView { val builtItems = TimelineBuilder.buildItems(this) + val thinkingOrRunning = inFlightTurnId != null || optimisticThinkingUntilMs > nowMs return ConversationView( conversationId = conversationId, title = title.ifBlank { "会话" }, @@ -757,7 +800,10 @@ class TimelineSession { pendingQuestion = pendingQuestion, queued = queued.toList(), inFlightTurnId = inFlightTurnId, + isThinkingOrRunning = thinkingOrRunning, canSteer = canSteer, + steeringKnown = steeringKnown, + rateLimit = rateLimit, lastSequence = lastSequence, usageLabel = usageLabel, planLines = planLines.toList(), @@ -918,6 +964,10 @@ object TimelineBuilder { val combinedText = if (asst.text.isBlank()) row.body else "${asst.text}\n\n${row.body}" currentAssistant = asst.copy(text = combinedText, segments = segments) } + "agent_handoff" -> { + flushAssistant() + result += TimelineItem(id = row.id, role = TimelineItem.Role.Divider, text = row.body) + } "turn_failed", "agent_binding_recovery_failed", "agent_binding_load_failed" -> { if (row.body.isBlank()) continue val asst = ensureAssistant(row.turnId, false, row.modelName) diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/AccountAuthTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/AccountAuthTest.kt index 46b855e..76d1a8f 100644 --- a/companion-core/src/test/kotlin/dev/vibex/companion/AccountAuthTest.kt +++ b/companion-core/src/test/kotlin/dev/vibex/companion/AccountAuthTest.kt @@ -54,11 +54,11 @@ class AccountAuthTest { @Test fun oauthStartReturnsToTheAuthorizePage() { assertEquals( - "https://vibex.xforever.xin/api/auth/oauth/github/start?next=%2Fdesktop%2Fauthorize%3Frequest%3Dreq-1", + "https://dimo-ai.com/api/auth/oauth/github/start?next=%2Fdesktop%2Fauthorize%3Frequest%3Dreq-1", AccountAuthRequests.oauthStartUrl( - "https://vibex.xforever.xin", + "https://dimo-ai.com", "github", - "https://vibex.xforever.xin/desktop/authorize?request=req-1", + "https://dimo-ai.com/desktop/authorize?request=req-1", ), ) } diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/AccountDesktopsTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/AccountDesktopsTest.kt index 04ac54f..6035697 100644 --- a/companion-core/src/test/kotlin/dev/vibex/companion/AccountDesktopsTest.kt +++ b/companion-core/src/test/kotlin/dev/vibex/companion/AccountDesktopsTest.kt @@ -38,14 +38,87 @@ class AccountDesktopsTest { @Test fun skipsDeviceLoginsWithoutAHost() { val root = JsonValue.parse( - """ - {"records": [ - {"hostId":"session:42","hostName":"iPhone","kind":"local","lastSeenAt":"2026-11-12T11:00:00Z","configSynced":false}, - {"hostId":"host:mac","hostName":"Mac","kind":"local","lastSeenAt":"2026-11-12T10:00:00Z","configSynced":true} - ]} - """.trimIndent(), + """ + {"records": [ + {"hostId":"session:42","hostName":"iPhone","kind":"local","lastSeenAt":"2026-11-12T11:00:00Z","configSynced":false}, + {"hostId":"host:local-desktop","hostName":"Local Host","kind":"local","osType":"macos","osArch":"aarch64","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"host:remote-desktop","hostName":"Local Host","kind":"local","osType":"linux","osArch":"x86_64","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"web:browser-1","hostName":"Web","kind":"local","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"profile:abc","hostName":"Profile","kind":"local","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"origin:http://localhost","hostName":"Origin","kind":"local","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"default","hostName":"Default","kind":"local","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"localhost","hostName":"Localhost","kind":"local","lastSeenAt":"2026-11-12T12:00:00Z"}, + {"hostId":"host:mac","hostName":"Mac","kind":"local","lastSeenAt":"2026-11-12T10:00:00Z","configSynced":true} + ]} + """.trimIndent(), ) as JsonValue.Object - assertEquals(listOf("mac"), AccountDesktops.parse(root).map { it.hostId }) + assertEquals(listOf("mac"), AccountDesktops.parse(root).map { it.hostId }) + } + + @Test + fun deduplicatesGenericLocalHostEntriesKeepingOnlineOrMostRecent() { + val staleInstall = AccountDesktop( + hostId = "uuid-old-vibex", + hostName = "Local Host", + osType = "macos", + osArch = "aarch64", + lastSeenAt = "2026-11-10T08:00:00Z", + cloudOnline = false, + ) + val liveInstall = AccountDesktop( + hostId = "uuid-live-dimo", + hostName = "Local Host", + osType = "macos", + osArch = "aarch64", + lastSeenAt = "2026-11-11T08:00:00Z", + cloudOnline = true, + ) + val offlineNewerGhost = AccountDesktop( + hostId = "uuid-ghost", + hostName = "Local Host", + osType = "macos", + osArch = "aarch64", + lastSeenAt = "2026-11-12T08:00:00Z", + cloudOnline = false, + ) + + val withLive = AccountDesktops.deduplicate(listOf(staleInstall, liveInstall, offlineNewerGhost)) + assertEquals(listOf("uuid-live-dimo"), withLive.map { it.hostId }) + + val allOffline = AccountDesktops.deduplicate( + listOf(staleInstall, liveInstall.copy(cloudOnline = false), offlineNewerGhost), + ) + assertEquals(listOf("uuid-ghost"), allOffline.map { it.hostId }) + + val allOfflineWithPaired = AccountDesktops.deduplicate( + desktops = listOf(staleInstall, liveInstall.copy(cloudOnline = false), offlineNewerGhost), + pairedHostIds = setOf("uuid-live-dimo"), + ) + assertEquals(listOf("uuid-live-dimo"), allOfflineWithPaired.map { it.hostId }) + } + + @Test + fun displayNameMapsGenericNamesToPlatformFriendlyLabelAndPreservesCustomNames() { + assertEquals( + "Dimo 桌面端 (Mac)", + AccountDesktop(hostId = "h1", hostName = "Local Host", osType = "macos", osArch = "aarch64").displayName, + ) + assertEquals( + "Dimo 桌面端 (Windows)", + AccountDesktop(hostId = "h2", hostName = "VibeX 电脑", osType = "windows", osArch = "x86_64").displayName, + ) + assertEquals( + "Dimo 桌面端 (Linux)", + AccountDesktop(hostId = "h3", hostName = "localhost", osType = "linux", osArch = "x86_64").displayName, + ) + assertEquals( + "Alpha", + AccountDesktop(hostId = "h4", hostName = "Alpha", osType = "macos", osArch = "arm64").displayName, + ) + assertEquals( + "Studio-MacBook", + AccountDesktop(hostId = "h5", hostName = "Studio-MacBook.local", osType = "macos", osArch = "arm64").displayName, + ) } @Test @@ -56,9 +129,9 @@ class AccountDesktopsTest { @Test fun tenantOriginUsesAssignedRelayOrDefault() { - val fallback = "https://vibex.xforever.xin" + val fallback = "https://dimo-ai.com" assertEquals( - "https://vibex.xforever.xin/t/alpha", + "https://dimo-ai.com/t/alpha", AccountDesktops.tenantOrigin(AccountDesktops.relayBase(null, fallback), "host:alpha"), ) assertEquals( diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/CollabLongConversationTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/CollabLongConversationTest.kt new file mode 100644 index 0000000..bc5a9bc --- /dev/null +++ b/companion-core/src/test/kotlin/dev/vibex/companion/CollabLongConversationTest.kt @@ -0,0 +1,333 @@ +package dev.vibex.companion + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class CollabLongConversationTest { + private val origin = HostOrigin.parse("http://127.0.0.1:17891") + + @Test + fun collabMessagesSendsExpectedPaginationPayloadsAndParsesPageMetadata() { + val latestTransport = CollabRecordingTransport( + 200, + """ + {"data":{ + "messages":[ + {"id":"m-101","seq":101,"origin":"user","operationId":"op-101","envelope":{"id":"m-101","sender":"Person","content":"hello"}}, + {"id":"draft:t-1","seq":0,"streaming":true,"turn_id":"t-1","envelope":{"sender":"ArchBot","content":"streaming..."}} + ], + "scheduled":[], + "cards":[], + "hasMoreBefore":true, + "oldestSeq":101 + }} + """.trimIndent(), + ) + val latestPage = HostApi(latestTransport).collabMessages(origin, "token", spaceId = "sp-1") + assertTrue(latestTransport.lastBody!!.contains("\"spaceId\":\"sp-1\"")) + assertTrue(latestTransport.lastBody!!.contains("\"latest\":true")) + assertTrue(latestTransport.lastBody!!.contains("\"limit\":80")) + assertFalse(latestTransport.lastBody!!.contains("sinceSeq")) + assertFalse(latestTransport.lastBody!!.contains("beforeSeq")) + assertTrue(latestPage.hasMoreBefore) + assertEquals(101L, latestPage.oldestSeq) + assertEquals(2, latestPage.messages.size) + assertEquals("op-101", latestPage.messages[0].operationId) + assertEquals("t-1", latestPage.messages[1].effectiveTurnId) + assertTrue(latestPage.messages[1].isStreamingDraft) + + val sinceTransport = CollabRecordingTransport( + 200, + """{"data":{"messages":[],"scheduled":[],"cards":[]}}""", + ) + val sincePage = HostApi(sinceTransport).collabMessages( + origin = origin, + token = "token", + spaceId = "sp-1", + limit = 80, + sinceSeq = 101L, + ) + assertTrue(sinceTransport.lastBody!!.contains("\"sinceSeq\":101")) + assertTrue(sinceTransport.lastBody!!.contains("\"limit\":80")) + assertFalse(sinceTransport.lastBody!!.contains("\"latest\"")) + assertFalse(sinceTransport.lastBody!!.contains("beforeSeq")) + assertFalse(sincePage.hasMoreBefore) + assertNull(sincePage.oldestSeq) + + val beforeTransport = CollabRecordingTransport( + 200, + """{"data":{"messages":[{"id":"m-50","seq":50,"envelope":{"sender":"Coder","content":"earlier"}}],"has_more_before":false,"oldest_seq":50}}""", + ) + val beforePage = HostApi(beforeTransport).collabMessages( + origin = origin, + token = "token", + spaceId = "sp-1", + limit = 80, + beforeSeq = 101L, + ) + assertTrue(beforeTransport.lastBody!!.contains("\"beforeSeq\":101")) + assertTrue(beforeTransport.lastBody!!.contains("\"limit\":80")) + assertFalse(beforeTransport.lastBody!!.contains("\"latest\"")) + assertFalse(beforeTransport.lastBody!!.contains("sinceSeq")) + assertFalse(beforePage.hasMoreBefore) + assertEquals(50L, beforePage.oldestSeq) + assertEquals(listOf(50), beforePage.messages.map { it.seq }) + } + + @Test + fun mergeCollabMessagesDeduplicatesByIdRawIdOperationIdAndPositiveSeq() { + val existing = listOf( + CollabSpaceMessage( + rawId = "vibex://space-message/m-1", + seq = 1, + operationId = "op-1", + envelope = CollabMessageEnvelope(id = "m-1", sender = "Person", content = "init"), + ), + CollabSpaceMessage( + rawId = null, + seq = 0, + operationId = "op-pending", + envelope = CollabMessageEnvelope(sender = "Person", content = "optimistic retry"), + ), + CollabSpaceMessage( + rawId = "m-3", + seq = 3, + envelope = CollabMessageEnvelope(id = "m-3", sender = "BotA", content = "v1"), + ), + ) + val incoming = listOf( + // Matches m-1 by id & seq, updates reactions + CollabSpaceMessage( + rawId = "m-1", + seq = 1, + envelope = CollabMessageEnvelope( + id = "m-1", + sender = "Person", + content = "init", + reactions = listOf(CollabReaction("👍", "user")), + ), + ), + // Matches optimistic message by operationId and assigns seq=2 + CollabSpaceMessage( + rawId = "m-2", + seq = 2, + operationId = "op-pending", + envelope = CollabMessageEnvelope(id = "m-2", sender = "Person", content = "optimistic retry"), + ), + // Matches m-3 by positive seq + CollabSpaceMessage( + rawId = "m-3-updated", + seq = 3, + envelope = CollabMessageEnvelope(id = "m-3-updated", sender = "BotA", content = "v2"), + ), + ) + + val merged = mergeCollabMessages(existing, incoming) + assertEquals(listOf(1, 2, 3), merged.map { it.seq }) + assertEquals(1, merged[0].envelope.reactions.size) + assertEquals("op-pending", merged[1].operationId) + assertEquals("v2", merged[2].envelope.content) + } + + @Test + fun mergeCollabMessagesReplacesStreamingDraftsOnUpdateAndFinalization() { + val initial = listOf( + CollabSpaceMessage( + rawId = "m-10", + seq = 10, + envelope = CollabMessageEnvelope(id = "m-10", sender = "Person", content = "Design this"), + ), + CollabSpaceMessage( + rawId = "draft:turn-99", + seq = 0, + streaming = true, + turnId = "turn-99", + envelope = CollabMessageEnvelope(sender = "Architect", content = "Step 1"), + ), + ) + + // Newer streaming chunk for the same turn + val afterChunk = mergeCollabMessages( + initial, + listOf( + CollabSpaceMessage( + rawId = "draft:turn-99", + seq = 0, + streaming = true, + turnId = "turn-99", + envelope = CollabMessageEnvelope(sender = "Architect", content = "Step 1\nStep 2"), + ), + ), + ) + assertEquals(2, afterChunk.size) + assertEquals("Step 1\nStep 2", afterChunk.last().envelope.content) + assertTrue(afterChunk.last().isStreamingDraft) + + // Finalized message arrives in group space (even without turnId, matched by sender + seq > 10) + val finalized = mergeCollabMessages( + afterChunk, + listOf( + CollabSpaceMessage( + rawId = "m-11", + seq = 11, + streaming = false, + envelope = CollabMessageEnvelope(id = "m-11", sender = "Architect", content = "Step 1\nStep 2\nDone!"), + ), + ), + ) + assertEquals(2, finalized.size) + assertFalse(finalized.any { it.isStreamingDraft }) + assertEquals(listOf(10, 11), finalized.map { it.seq }) + assertEquals("Step 1\nStep 2\nDone!", finalized.last().envelope.content) + } + + @Test + fun mergeCollabMessagesSupportsBeforeSeqPrependAndSinceSeqAppendWhileKeepingDraftsAtTail() { + val window = listOf( + CollabSpaceMessage(rawId = "m-11", seq = 11, envelope = CollabMessageEnvelope(sender = "BotA", content = "11")), + CollabSpaceMessage(rawId = "m-12", seq = 12, envelope = CollabMessageEnvelope(sender = "BotB", content = "12")), + CollabSpaceMessage( + rawId = "draft:botA", + seq = 0, + streaming = true, + envelope = CollabMessageEnvelope(sender = "BotA", content = "Live tail draft"), + ), + ) + + // Prepend older messages via beforeSeq=11 (including an older message from BotA that must NOT clobber active tail draft!) + val earlier = listOf( + CollabSpaceMessage(rawId = "m-9", seq = 9, envelope = CollabMessageEnvelope(sender = "BotA", content = "Old message 9")), + CollabSpaceMessage(rawId = "m-10", seq = 10, envelope = CollabMessageEnvelope(sender = "Person", content = "10")), + ) + val afterPrepend = mergeCollabMessages(window, earlier) + assertEquals(listOf(9, 10, 11, 12, 0), afterPrepend.map { it.seq }) + assertTrue(afterPrepend.last().isStreamingDraft) + assertEquals("Live tail draft", afterPrepend.last().envelope.content) + + // Append newer confirmed message via sinceSeq=12 from BotB; BotA's draft still stays at tail + val afterAppend = mergeCollabMessages( + afterPrepend, + listOf( + CollabSpaceMessage(rawId = "m-13", seq = 13, envelope = CollabMessageEnvelope(sender = "BotB", content = "13")), + ), + ) + assertEquals(listOf(9, 10, 11, 12, 13, 0), afterAppend.map { it.seq }) + assertEquals("draft:botA", afterAppend.last().id) + + // Reconciling against an empty active tail draft set removes cancelled draft + val reconciled = reconcileCollabStreamingDrafts(afterAppend, emptyList()) + assertEquals(listOf(9, 10, 11, 12, 13), reconciled.map { it.seq }) + } + + @Test + fun parseCollabStructuredMessageExtractsCardsAndHandoffsWithoutLeakingRawXml() { + val approvalMsg = """ + 请求审批:合并 PR + + + + 合并 PR #42 + + + git merge <feature/long-conv> + + + 全部单测已通过 + + + """.trimIndent() + + val parsedApproval = parseCollabStructuredMessage(approvalMsg) + assertEquals("请求审批:合并 PR", parsedApproval.cleanText) + assertFalse(parsedApproval.cleanText.contains("", apprCard.command) + assertEquals("全部单测已通过", apprCard.reason) + + val askAndHandoffMsg = """ + 已完成接口拆分,请确认下一步: + + + space.listMessages beforeSeq & hasMoreBefore + 不要改动协议外字段 + 在 Android 端接入分页与折叠长消息 + + + + 默认分页条数用多少? + 40|80|120 + + """.trimIndent() + + val parsedCombo = parseCollabStructuredMessage(askAndHandoffMsg) + assertEquals("已完成接口拆分,请确认下一步:", parsedCombo.cleanText) + assertFalse(parsedCombo.cleanText.contains(" 480) + assertTrue(shouldCollapseLongMessage(longSingleParagraph)) + + val lookup = buildCollabMessageLookup( + listOf( + CollabSpaceMessage( + rawId = "vibex://space-message/abc-123", + seq = 5, + envelope = CollabMessageEnvelope(id = "abc-123", sender = "Bot", content = "target"), + ), + ), + ) + assertEquals(5, lookupCollabReplyMessage(lookup, "abc-123")?.seq) + assertEquals(5, lookupCollabReplyMessage(lookup, "vibex://space-message/abc-123")?.seq) + } +} + +private class CollabRecordingTransport( + private val status: Int, + private val body: String, +) : HttpTransport { + var lastBody: String? = null + + override fun execute( + method: String, + url: String, + headers: Map, + body: String?, + ): HttpExchange { + lastBody = body + return HttpExchange(status, this.body) + } +} diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/ConnectionPolicyTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/ConnectionPolicyTest.kt new file mode 100644 index 0000000..351e2c4 --- /dev/null +++ b/companion-core/src/test/kotlin/dev/vibex/companion/ConnectionPolicyTest.kt @@ -0,0 +1,52 @@ +package dev.vibex.companion + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ConnectionPolicyTest { + @Test + fun backoffDoublesAndCaps() { + assertEquals(800L, ConnectionPolicy.backoffBaseMs(0)) + assertEquals(1600L, ConnectionPolicy.backoffBaseMs(1)) + assertEquals(3200L, ConnectionPolicy.backoffBaseMs(2)) + assertEquals(15_000L, ConnectionPolicy.backoffBaseMs(10)) + assertEquals(15_000L, ConnectionPolicy.backoffBaseMs(1000)) + } + + @Test + fun jitterStaysInBand() { + assertEquals(640L, ConnectionPolicy.backoffMs(0, 0.0)) + assertTrue(ConnectionPolicy.backoffMs(0, 0.999) <= 960L) + assertTrue(ConnectionPolicy.backoffMs(30, 1.0) <= 18_000L) + } + + @Test + fun recoveringIsDebounced() { + assertFalse(ConnectionPolicy.shouldShowRecovering(null, 10_000)) + assertFalse(ConnectionPolicy.shouldShowRecovering(9_000, 10_000)) + assertTrue(ConnectionPolicy.shouldShowRecovering(8_000, 10_000)) + } + + @Test + fun singlePollFailureIsNotDegraded() { + assertFalse(ConnectionPolicy.pollDegraded(1)) + assertTrue(ConnectionPolicy.pollDegraded(3)) + } + + @Test + fun httpRefreshGating() { + assertFalse(ConnectionPolicy.shouldRunHttpRefresh(false, ConnectionState.Online, 99_999)) + assertFalse(ConnectionPolicy.shouldRunHttpRefresh(true, ConnectionState.Offline, 99_999)) + assertFalse(ConnectionPolicy.shouldRunHttpRefresh(true, ConnectionState.Online, 5_000)) + assertTrue(ConnectionPolicy.shouldRunHttpRefresh(true, ConnectionState.Online, 12_000)) + } + + @Test + fun logIsBounded() { + val log = ConnectionLog(3) + repeat(10) { log.add("e$it") } + assertEquals(listOf("e7", "e8", "e9"), log.snapshot()) + } +} diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/HandoffSideChatTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/HandoffSideChatTest.kt new file mode 100644 index 0000000..70c5d04 --- /dev/null +++ b/companion-core/src/test/kotlin/dev/vibex/companion/HandoffSideChatTest.kt @@ -0,0 +1,83 @@ +package dev.vibex.companion + +import dev.vibex.remote.v1.JsonValue +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class HandoffSideChatTest { + @Test + fun parsesProviderInstancesAndFiltersByAgent() { + val data = JsonValue.parse( + """[{"id":"1","instanceId":"work","agentId":"claude_code","displayName":"Work","isDefault":true}, + {"instanceId":"p","agent_id":"codex","display_name":"P"},{"agentId":"x"}]""", + ) + val all = parseProviderInstances(data) + assertEquals(2, all.size) + assertEquals(listOf("work"), instancesForAgent(all, "claude-code").map { it.instanceId }) + assertTrue(all[0].isDefault) + assertFalse(all[1].isDefault) + } + + @Test + fun parsesPreview() { + val p = parseEngineHandoffPreview( + JsonValue.parse( + """{"sourceEngine":"codex","targetEngine":"claude_code","packedMessages":[{"id":"a"},{"id":"b"}], + "omittedIds":["c"],"totalTokens":120,"tokenBudget":8000,"handoffPromptText":"hi"}""", + ), + ) + assertNotNull(p) + assertEquals(2, p.packedCount) + assertEquals(1, p.omittedCount) + assertEquals(8000, p.tokenBudget) + assertEquals("hi", p.promptText) + assertNull(parseEngineHandoffPreview(JsonValue.Null)) + } + + @Test + fun handoffArgsOmitBlankInstanceAndBudget() { + val a = handoffArgs("c1", "codex", " ", null) + assertEquals(setOf("conversationId", "targetEngine"), a.keys) + val b = handoffArgs("c1", "codex", "work", 100) + assertEquals("work", b["targetProviderInstanceId"]) + assertEquals(100.0, b["tokenBudget"]) + } + + @Test + fun parsesSideChatReplyWithDoneFallback() { + val r = parseSideChatReply( + JsonValue.parse("""{"content":"ok","toolCalls":[{"id":"t","name":"Read","status":"completed","summary":"s"}],"events":[]}"""), + ) + assertNotNull(r) + assertEquals("ok", r.content) + assertEquals("Read", r.toolCalls.single().name) + val f = parseSideChatReply(JsonValue.parse("""{"events":[{"type":"delta","text":"x"},{"type":"done","content":"final"}]}""")) + assertEquals("final", f?.content) + assertNull(parseSideChatReply(JsonValue.parse("""{"events":[]}"""))) + } + + @Test + fun buildsContextTurnsAndSkipsErroredHistory() { + val items = listOf( + TimelineItem("1", TimelineItem.Role.User, "q1"), + TimelineItem("2", TimelineItem.Role.Assistant, "a1"), + TimelineItem("3", TimelineItem.Role.Assistant, "a1b"), + TimelineItem("4", TimelineItem.Role.User, "q2"), + ) + val ctx = buildSideChatContext(items, maxTurns = 1) + assertEquals(1, ctx.size) + assertEquals("q2", ctx[0].userText) + assertEquals(1, ctx[0].turnNumber) + val full = buildSideChatContext(items) + assertEquals("a1\n\na1b", full[0].assistantText) + val args = sideChatArgs( + "c", "s", "p", full, + listOf(SideChatMessage("1", "user", "hi"), SideChatMessage("2", "assistant", "err", isError = true)), + ) + assertEquals(1, (args["history"] as List<*>).size) + } +} diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/HostApiCatalogTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/HostApiCatalogTest.kt index 3933a43..f478307 100644 --- a/companion-core/src/test/kotlin/dev/vibex/companion/HostApiCatalogTest.kt +++ b/companion-core/src/test/kotlin/dev/vibex/companion/HostApiCatalogTest.kt @@ -221,6 +221,78 @@ class HostApiCatalogTest { assertEquals("skill:/tmp/office-xlsx:office-xlsx", commands.single().key) assertEquals("/skill:/tmp/office-xlsx:office-xlsx", commands.single().value) } + + @Test + fun catalogMarksUninstalledBuiltInAgentsUnusableViaManagementBarAndLifecycleFallback() { + val catalogBody = """{"data":{"projects":[],"workspaces":[],"agents":[ + {"id":"claude_code","ready":true,"usable":true,"lifecycle":"ready","displayName":"Claude Code"}, + {"id":"codex","ready":true,"usable":true,"lifecycle":"not_installed","displayName":"Codex"}, + {"id":"kimi","ready":true,"usable":true,"lifecycle":"ready","displayName":"Kimi"} + ]}}""" + val barBody = """{"data":[ + {"agent_id":"kimi","position":0,"enabled":true,"retired":false,"lifecycle":"ready"}, + {"agent_id":"claude_code","position":1,"enabled":true,"retired":false,"lifecycle":"ready"}, + {"agent_id":"codex","position":2,"enabled":true,"retired":false,"lifecycle":"not_installed"} + ]}""" + val routed = HostApi( + CommandRoutedTransport( + mapOf( + "conversation_catalog" to (200 to catalogBody), + "agent_management_bar" to (200 to barBody), + ), + ), + ).catalog(HostOrigin.parse("http://127.0.0.1:17891"), "token") + assertEquals(listOf("kimi", "claude_code", "codex"), routed.agents.map { it.id }) + assertEquals(true, routed.agents[0].usable) + assertEquals(true, routed.agents[1].usable) + assertEquals(false, routed.agents[2].usable) + + val fallback = HostApi( + CommandRoutedTransport( + mapOf( + "conversation_catalog" to (200 to catalogBody), + "agent_management_bar" to (500 to """{"message":"unsupported"}"""), + ), + ), + ).catalog(HostOrigin.parse("http://127.0.0.1:17891"), "token") + assertEquals(true, fallback.agents.first { it.id == "claude_code" }.usable) + assertEquals(false, fallback.agents.first { it.id == "codex" }.usable) + assertTrue(fallback.agents.first { it.id == "claude_code" }.modelOptions.single().choices.isNotEmpty()) + } + + @Test + fun hostTimestampParserSupportsIsoAndSqliteUtcAndRecentReadWindow() { + val isoMs = parseHostTimestampEpochMillis(" 2026-11-14T12:00:00Z ") + val sqliteMs = parseHostTimestampEpochMillis("2026-11-14 12:00:00.123456") + assertTrue(isoMs != null) + assertTrue(sqliteMs != null) + assertEquals(isoMs!! + 123L, sqliteMs!!) + + val summary = KanbanSessionSummary( + id = "s1", + workspaceId = "w1", + status = KanbanSessionStatus.Done, + updatedAt = "2026-11-14 12:00:00", + ) + assertEquals(true, summary.isRecentlyActiveReadSession(emptySet(), nowMs = isoMs + 3600_000L)) + assertEquals(false, summary.isRecentlyActiveReadSession(setOf("s1"), nowMs = isoMs + 3600_000L)) + assertEquals(false, summary.isRecentlyActiveReadSession(emptySet(), nowMs = isoMs + 25L * 3600_000L)) + } +} + +private class CommandRoutedTransport( + private val routes: Map>, +) : HttpTransport { + override fun execute( + method: String, + url: String, + headers: Map, + body: String?, + ): HttpExchange { + val hit = routes.entries.firstOrNull { (cmd, _) -> url.endsWith("/$cmd") }?.value + ?: (404 to """{"message":"not found"}""") + return HttpExchange(hit.first, hit.second) + } } private class OneShotTransport( diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/MentionAndTimeoutTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/MentionAndTimeoutTest.kt new file mode 100644 index 0000000..26db6e7 --- /dev/null +++ b/companion-core/src/test/kotlin/dev/vibex/companion/MentionAndTimeoutTest.kt @@ -0,0 +1,29 @@ +package dev.vibex.companion + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class MentionAndTimeoutTest { + @Test + fun detectsTokenAtCaret() { + assertEquals(MentionToken(0, 1, ""), mentionTokenAt("@", 1)) + assertEquals(MentionToken(3, 6, "ab"), mentionTokenAt("hi @ab cd", 6).let { it?.copy(end = 6) }) + assertNull(mentionTokenAt("a@b", 3)) + assertNull(mentionTokenAt("@ab cd", 6)) + assertNull(mentionTokenAt("hello", 5)) + } + + @Test + fun applyReplacesToken() { + val token = mentionTokenAt("hi @ab", 6)!! + assertEquals("hi @Bot " to 8, applyMention("hi @ab", token, "Bot")) + } + + @Test + fun postTimeoutsAreLonger() { + assertEquals(60_000, requestReadTimeoutMs("POST", true)) + assertEquals(15_000, requestReadTimeoutMs("GET", true)) + assertEquals(20_000, requestReadTimeoutMs("GET", false)) + } +} diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt index d5c7761..237c1a0 100644 --- a/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt +++ b/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt @@ -81,6 +81,27 @@ class PairingClientTest { assertTrue(transport.requests.single().url.endsWith("/api/v1/auth/connect-requests/req-1")) } + @Test + fun requestConnectReturnsImmediateCredentialWhenSameAccountAutoApproved() { + val transport = ScriptedTransport( + listOf( + HttpExchange( + 201, + """{"request_id":"req-auto","host_id":"host-1","host_name":"Mac Studio","sas_code":"7392","status":"approved","expires_at":"2026-11-14T12:05:00Z","credential":{"device_id":"22222222-2222-2222-2222-222222222222","access_token":"instant-device-token","scopes":["conversation.read","conversation.write"]}}""", + ), + ), + ) + val result = PairingClient(transport).requestConnect( + HostOrigin.parse("http://192.168.1.5:17891"), + deviceName = "Pixel 9", + accountToken = "same-account-jwt", + ) + assertEquals("approved", result.status) + assertEquals("7392", result.sasCode) + assertEquals("Mac Studio", result.hostName) + assertEquals("instant-device-token", result.credential?.access_token) + } + @Test fun redeemStoresCompanionCredentialAndNegotiatesV1() { val transport = ScriptedTransport( @@ -131,15 +152,15 @@ class PairingClientTest { @Test fun requestConnectReportsAnOfflineDesktopBehindTheRelay() { - for (status in listOf(502, 503, 504)) { - val transport = ScriptedTransport(listOf(HttpExchange(status, ""))) - assertFailsWith { - PairingClient(transport).requestConnect( - HostOrigin.parse("https://vibex.xforever.xin/t/host-1"), - accountToken = "acct-token", - ) - } - } + for (status in listOf(502, 503, 504)) { + val transport = ScriptedTransport(listOf(HttpExchange(status, ""))) + assertFailsWith { + PairingClient(transport).requestConnect( + HostOrigin.parse("https://dimo-ai.com/t/host-1"), + accountToken = "acct-token", + ) + } + } } @Test @@ -150,8 +171,8 @@ class PairingClientTest { } @Test - fun e2eeHandshakeAndAesGcmRoundTripSucceeds() { - val origin = "https://relay.example.com/t/host-e2ee-android" + fun e2eeHandshakeAesGcmAndClearSessionSucceed() { + val origin = "https://dimo-ai.com/t/host-e2ee-android" val session = E2eeSessionManager.ingestHandshake( origin, "sess-android-01", @@ -164,6 +185,99 @@ class PairingClientTest { val cipherB64 = E2eeSessionManager.encryptString(session.aesKey, E2eeSessionManager.AAD_REQ, plain) val decrypted = E2eeSessionManager.decryptString(session.aesKey, E2eeSessionManager.AAD_REQ, cipherB64) assertEquals(plain, decrypted) + + E2eeSessionManager.clearSession("$origin/api/v1/capabilities") + assertFalse(E2eeSessionManager.isE2eeActive(origin)) + assertEquals(null, E2eeSessionManager.session(origin)) + + val rehandshaken = E2eeSessionManager.ingestHandshake( + origin, + "sess-android-02", + E2eeSessionManager.clientPublicKeyBase64, + ) + assertEquals("sess-android-02", rehandshaken?.sessionId) + assertTrue(E2eeSessionManager.isE2eeActive(origin)) + } + + @Test + fun migratesLegacyRelayOriginsAndRedirectsRememberedBases() { + assertEquals( + "https://dimo-ai.com/t/host-123", + PairingClient.migrateLegacyRelayOrigin("https://vibex.xforever.xin/t/host-123"), + ) + assertEquals( + "https://dimo-ai.com/t/host-123", + PairingClient.migrateLegacyRelayOrigin("http://vibex.xforever.xin/t/host-123/"), + ) + assertEquals( + "https://dimo-ai.com/t/host-123", + PairingClient.migrateLegacyRelayOrigin("https://dimo-ai.com/t/host-123"), + ) + assertEquals( + "https://custom-relay.example.com/t/host-123", + PairingClient.migrateLegacyRelayOrigin("https://custom-relay.example.com/t/host-123"), + ) + assertEquals( + "http://192.168.1.8:17891", + PairingClient.migrateLegacyRelayOrigin("http://192.168.1.8:17891"), + ) + + PairingClient.rememberRelayBase("https://vibex.xforever.xin/t/host-123") + PairingClient.rememberRelayBase("http://vibex.xforever.xin") + val bases = PairingClient.knownRelayBases(listOf("https://vibex.xforever.xin/t/host-456")) + assertTrue(bases.contains("https://dimo-ai.com")) + assertTrue(bases.none { it.contains("vibex.xforever.xin") }) + + val rendezvous = PairingClient.resolveHostRendezvous("host-abc") + assertTrue(rendezvous.contains("https://dimo-ai.com/t/host-abc")) + assertTrue(DiscoveredLanHost("https://dimo-ai.com", "h1", "Mac").isCloudService) + assertTrue(DiscoveredLanHost("https://vibex.xforever.xin", "h1", "Mac").isCloudService) + } + + @Test + fun filtersCellularAndVirtualNetworkInterfacesFromLanScan() { + val blocked = listOf( + null, + "", + "lo", + "lo0", + "rmnet0", + "rmnet_data0", + "ccmni0", + "ccmni1", + "pdp_ip0", + "clat4", + "v4-rmnet_data0", + "dummy0", + "utun0", + "tun0", + "tap0", + "ppp0", + "ipsec0", + "wg0", + "tailscale0", + "clash0", + "en_mihomo", + "surge-utun", + ) + for (iface in blocked) { + assertFalse(PairingClient.isScannableLanInterfaceName(iface), "expected blocked: $iface") + } + + val allowed = listOf( + "wlan0", + "wlan1", + "eth0", + "en0", + "ap0", + "swlan0", + "wifi0", + "rndis0", + "usb0", + ) + for (iface in allowed) { + assertTrue(PairingClient.isScannableLanInterfaceName(iface), "expected allowed: $iface") + } } } diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/PairingCoordinatorTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/PairingCoordinatorTest.kt index 146f849..1304927 100644 --- a/companion-core/src/test/kotlin/dev/vibex/companion/PairingCoordinatorTest.kt +++ b/companion-core/src/test/kotlin/dev/vibex/companion/PairingCoordinatorTest.kt @@ -27,14 +27,14 @@ class PairingCoordinatorTest { val error = assertFailsWith { coordinator(offline).redeemInvitation(invitation("http://192.168.1.5:17891", "http://10.0.0.8:17891"), "Pixel") } - assertEquals("电脑未开启云服务。请连接与电脑相同的 Wi-Fi,或在电脑上登录 VibeX 账号", error.message) + assertEquals("电脑未开启云服务。请连接与电脑相同的 Wi-Fi,或在电脑上登录 Dimo 账号", error.message) } @Test fun unreachableCloudOriginKeepsTheGenericFailure() { val error = assertFailsWith { coordinator(offline).redeemInvitation( - invitation("http://192.168.1.5:17891", "https://vibex.xforever.xin/t/host-1"), + invitation("http://192.168.1.5:17891", "https://dimo-ai.com/t/host-1"), "Pixel", ) } @@ -64,7 +64,7 @@ class PairingCoordinatorTest { ) local.forEach { assertTrue(HostOrigin.parse(it).isLocalNetwork, it) } val public = listOf( - "https://vibex.xforever.xin/t/host-1", + "https://dimo-ai.com/t/host-1", "http://172.32.0.4:17891", "http://100.101.1.2:17891", "http://203.0.113.9:17891", diff --git a/companion-core/src/test/kotlin/dev/vibex/companion/PairingInvitationTest.kt b/companion-core/src/test/kotlin/dev/vibex/companion/PairingInvitationTest.kt index 71072eb..694028d 100644 --- a/companion-core/src/test/kotlin/dev/vibex/companion/PairingInvitationTest.kt +++ b/companion-core/src/test/kotlin/dev/vibex/companion/PairingInvitationTest.kt @@ -34,7 +34,17 @@ class PairingInvitationTest { @Test fun rejectsNonInvitation() { - assertFailsWith { PairingInvitationParser.parse("http://192.168.1.1:3080") } + val err = assertFailsWith { PairingInvitationParser.parse("http://192.168.1.1:3080") } + assertEquals("这不是 Dimo 邀请", err.message) + } + + @Test + fun parsesDimoPairingPayload() { + val invitation = PairingInvitationParser.parse( + """dimo-pairing:{"host_id":"h2","preset":"companion","pairing_token":"vbx_pair_xyz","reachability":[{"origin":"http://192.168.1.9:17891","kind":"lan"}]}""", + ) + assertEquals("h2", invitation.hostId) + assertEquals(listOf("http://192.168.1.9:17891"), invitation.reachability.map { it.origin.value }) } @Test