Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ captures/
keystore.properties
*.jks
*.keystore
keystore/
.git-commit-helper.sh
9 changes: 6 additions & 3 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ android {
applicationId = "dev.vibex.companion"
minSdk = 26
targetSdk = 35
versionCode = 18
versionName = "0.4.5"
versionCode = 20
versionName = "0.4.7"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
Expand All @@ -24,7 +24,10 @@ android {
isMinifyEnabled = false
}
}
buildFeatures { compose = true }
buildFeatures {
compose = true
buildConfig = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
Expand Down
13 changes: 12 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature android:name="android.hardware.camera" android:required="false" />

<application
Expand All @@ -24,7 +26,7 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:windowSoftInputMode="adjustResize">
android:windowSoftInputMode="stateHidden|adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
Expand All @@ -41,5 +43,14 @@
android:name=".monitor.CompanionMonitorService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/update_file_paths" />
</provider>
</application>
</manifest>
1,046 changes: 840 additions & 206 deletions app/src/main/java/dev/vibex/companion/app/CompanionModel.kt

Large diffs are not rendered by default.

67 changes: 51 additions & 16 deletions app/src/main/java/dev/vibex/companion/app/DesktopConnect.kt
Original file line number Diff line number Diff line change
@@ -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.hostName
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(
Expand All @@ -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 -> "这台电脑登录的是其他 VibeX 账号"
AccountLinkFailure.HostAccountSignedOut -> "这台电脑未登录 VibeX 账号"
AccountLinkFailure.AccountTokenInvalid,
AccountLinkFailure.VerificationUnavailable,
-> ACCOUNT_VERIFICATION_UNAVAILABLE
}
is HostUnreachableException, is IOException -> HOST_UNREACHABLE
is PairingException -> error.message ?: HOST_UNREACHABLE
else -> error.message ?: HOST_UNREACHABLE
}
13 changes: 13 additions & 0 deletions app/src/main/java/dev/vibex/companion/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
) {}
Expand All @@ -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() {
Expand All @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Set<String>> = _favoriteIds

private val _hiddenIds = MutableStateFlow(loadSet(KEY_HIDDEN))
val hiddenIds: StateFlow<Set<String>> = _hiddenIds

private val _customModelsByAgent = MutableStateFlow(loadCustomMap())
val customModelsByAgent: StateFlow<Map<String, List<String>>> = _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<String> =
prefs.getStringSet(key, emptySet()).orEmpty().filter { it.isNotBlank() }.toSet()

private fun saveSet(key: String, values: Set<String>) {
prefs.edit().putStringSet(key, values).apply()
}

private fun loadCustomMap(): Map<String, List<String>> {
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<String, List<String>>) {
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"
}
}
25 changes: 24 additions & 1 deletion app/src/main/java/dev/vibex/companion/app/data/ProfileStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 ->
Expand All @@ -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
Expand All @@ -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(
Expand All @@ -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 = "",
)
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ 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 订阅会员"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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 {
Expand Down
Loading