Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,14 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import zed.rainxch.core.domain.model.AppTheme
import zed.rainxch.core.domain.model.DiscoveryPlatform
import zed.rainxch.core.domain.model.FontTheme
import zed.rainxch.core.domain.model.InstallerType
import zed.rainxch.core.domain.repository.TweaksRepository

class TweaksRepositoryImpl(
private val preferences: DataStore<Preferences>,
) : TweaksRepository {
private val THEME_KEY = stringPreferencesKey("app_theme")
private val AMOLED_KEY = booleanPreferencesKey("amoled_theme")
private val IS_DARK_THEME_KEY = booleanPreferencesKey("is_dark_theme")
private val FONT_KEY = stringPreferencesKey("font_theme")
private val AUTO_DETECT_CLIPBOARD_KEY = booleanPreferencesKey("auto_detect_clipboard_links")
private val INSTALLER_TYPE_KEY = stringPreferencesKey("installer_type")
private val AUTO_UPDATE_KEY = booleanPreferencesKey("auto_update_enabled")
private val UPDATE_CHECK_INTERVAL_KEY = longPreferencesKey("update_check_interval_hours")
private val INCLUDE_PRE_RELEASES_KEY = booleanPreferencesKey("include_pre_releases")
private val LIQUID_GLASS_ENABLED_KEY = booleanPreferencesKey("liquid_glass_enabled")
private val HIDE_SEEN_ENABLED_KEY = booleanPreferencesKey("hide_seen_enabled")

override fun getThemeColor(): Flow<AppTheme> =
preferences.data.map { prefs ->
val themeName = prefs[THEME_KEY]
Expand Down Expand Up @@ -156,7 +145,32 @@ class TweaksRepositoryImpl(
}
}

override fun getDiscoveryPlatform(): Flow<DiscoveryPlatform> =
preferences.data.map { prefs ->
val platform = prefs[DISCOVERY_PLATFORM_KEY]
DiscoveryPlatform.fromName(platform)
}

override suspend fun setDiscoveryPlatform(platform: DiscoveryPlatform) {
preferences.edit { prefs ->
prefs[DISCOVERY_PLATFORM_KEY] = platform.name
}
}

companion object {
const val DEFAULT_UPDATE_CHECK_INTERVAL_HOURS = 6L
private const val DEFAULT_UPDATE_CHECK_INTERVAL_HOURS = 6L

private val THEME_KEY = stringPreferencesKey("app_theme")
private val AMOLED_KEY = booleanPreferencesKey("amoled_theme")
private val IS_DARK_THEME_KEY = booleanPreferencesKey("is_dark_theme")
private val FONT_KEY = stringPreferencesKey("font_theme")
private val DISCOVERY_PLATFORM_KEY = stringPreferencesKey("discovery_platform")
private val AUTO_DETECT_CLIPBOARD_KEY = booleanPreferencesKey("auto_detect_clipboard_links")
private val INSTALLER_TYPE_KEY = stringPreferencesKey("installer_type")
private val AUTO_UPDATE_KEY = booleanPreferencesKey("auto_update_enabled")
private val UPDATE_CHECK_INTERVAL_KEY = longPreferencesKey("update_check_interval_hours")
private val INCLUDE_PRE_RELEASES_KEY = booleanPreferencesKey("include_pre_releases")
private val LIQUID_GLASS_ENABLED_KEY = booleanPreferencesKey("liquid_glass_enabled")
private val HIDE_SEEN_ENABLED_KEY = booleanPreferencesKey("hide_seen_enabled")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,9 @@ enum class DiscoveryPlatform {
Macos,
Windows,
Linux,
;

companion object {
fun fromName(name: String?): DiscoveryPlatform = DiscoveryPlatform.entries.find { it.name == name } ?: All
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package zed.rainxch.core.domain.repository

import kotlinx.coroutines.flow.Flow
import zed.rainxch.core.domain.model.AppTheme
import zed.rainxch.core.domain.model.DiscoveryPlatform
import zed.rainxch.core.domain.model.FontTheme
import zed.rainxch.core.domain.model.InstallerType

Expand Down Expand Up @@ -49,4 +50,8 @@ interface TweaksRepository {
fun getHideSeenEnabled(): Flow<Boolean>

suspend fun setHideSeenEnabled(enabled: Boolean)

fun getDiscoveryPlatform(): Flow<DiscoveryPlatform>

suspend fun setDiscoveryPlatform(platform: DiscoveryPlatform)
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,11 @@ class AuthenticationViewModel(
_events.trySend(AuthenticationEvents.OnNavigateToMain)
}

AuthenticationAction.PollNow,
AuthenticationAction.OnResumed,
-> {
AuthenticationAction.PollNow -> {
forcePollNow()
}

AuthenticationAction.OnResumed -> {
tryPollIfReady()
}
}
Expand Down Expand Up @@ -158,6 +160,20 @@ class AuthenticationViewModel(
}
}

private fun forcePollNow() {
val loginState = _state.value.loginState
if (loginState is AuthLoginState.DevicePrompt) {
val deviceCode = loginState.start.deviceCode
logger.debug("Manual poll requested (isPolling=${_state.value.isPolling}, pollingJobActive=${pollingJob?.isActive})")
// Restart background polling if it died
if (pollingJob?.isActive != true) {
logger.debug("Polling job was dead — restarting background polling")
startPolling(deviceCode)
}
pollOnce(deviceCode)
}
}
Comment on lines +165 to +177
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing isPolling guard allows concurrent poll requests.

Unlike tryPollIfReady() (Line 158), forcePollNow() doesn't check _state.value.isPolling before calling pollOnce(). The UI button is disabled when isPolling is true, but there's a race window—rapid clicks can queue multiple doPoll() calls before the isPolling flag propagates to the UI.

This could lead to redundant API calls against GitHub's device flow endpoint and potentially hit rate limits.

Proposed fix: add isPolling guard
 private fun forcePollNow() {
     val loginState = _state.value.loginState
-    if (loginState is AuthLoginState.DevicePrompt) {
+    if (loginState is AuthLoginState.DevicePrompt && !_state.value.isPolling) {
         val deviceCode = loginState.start.deviceCode
         logger.debug("Manual poll requested (isPolling=${_state.value.isPolling}, pollingJobActive=${pollingJob?.isActive})")
         // Restart background polling if it died
         if (pollingJob?.isActive != true) {
             logger.debug("Polling job was dead — restarting background polling")
             startPolling(deviceCode)
         }
         pollOnce(deviceCode)
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private fun forcePollNow() {
val loginState = _state.value.loginState
if (loginState is AuthLoginState.DevicePrompt) {
val deviceCode = loginState.start.deviceCode
logger.debug("Manual poll requested (isPolling=${_state.value.isPolling}, pollingJobActive=${pollingJob?.isActive})")
// Restart background polling if it died
if (pollingJob?.isActive != true) {
logger.debug("Polling job was dead — restarting background polling")
startPolling(deviceCode)
}
pollOnce(deviceCode)
}
}
private fun forcePollNow() {
val loginState = _state.value.loginState
if (loginState is AuthLoginState.DevicePrompt && !_state.value.isPolling) {
val deviceCode = loginState.start.deviceCode
logger.debug("Manual poll requested (isPolling=${_state.value.isPolling}, pollingJobActive=${pollingJob?.isActive})")
// Restart background polling if it died
if (pollingJob?.isActive != true) {
logger.debug("Polling job was dead — restarting background polling")
startPolling(deviceCode)
}
pollOnce(deviceCode)
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@feature/auth/presentation/src/commonMain/kotlin/zed/rainxch/auth/presentation/AuthenticationViewModel.kt`
around lines 163 - 175, forcePollNow() currently calls pollOnce(deviceCode)
without checking the isPolling flag, which allows concurrent poll requests;
update forcePollNow() to first return early if _state.value.isPolling is true
(same guard used by tryPollIfReady()), and only proceed to restart polling
(startPolling(deviceCode)) and call pollOnce(deviceCode) when isPolling is
false; reference _state.value.isPolling, forcePollNow(), pollOnce(deviceCode),
startPolling(deviceCode) and tryPollIfReady() when making the change.


private fun startLogin() {
viewModelScope.launch {
try {
Expand Down Expand Up @@ -245,6 +261,7 @@ class AuthenticationViewModel(
private suspend fun doPoll(deviceCode: String) {
_state.update { it.copy(isPolling = true) }
try {
logger.debug("Polling device token (code=${deviceCode.take(8)}...)")
val result =
withContext(Dispatchers.IO) {
authenticationRepository.pollDeviceTokenOnce(deviceCode)
Expand All @@ -253,6 +270,7 @@ class AuthenticationViewModel(
result
.onSuccess { token ->
if (token != null) {
logger.debug("Poll success — token received, navigating")
pollingJob?.cancel()
countdownJob?.cancel()
clearSavedState()
Expand All @@ -261,9 +279,11 @@ class AuthenticationViewModel(
}
_events.trySend(AuthenticationEvents.OnNavigateToMain)
} else {
logger.debug("Poll result: still pending")
_state.update { it.copy(isPolling = false) }
}
}.onFailure { error ->
logger.debug("Poll failed terminally: ${error.message}")
pollingJob?.cancel()
countdownJob?.cancel()
clearSavedState()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ sealed interface HomeAction {
val topic: TopicCategory?,
) : HomeAction

data class SwitchFilterPlatform(
data class SwitchDiscoveryPlatform(
val platform: DiscoveryPlatform,
) : HomeAction

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
Expand All @@ -24,7 +26,6 @@ import androidx.compose.foundation.layout.height
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.staggeredgrid.LazyStaggeredGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
Expand All @@ -51,14 +52,10 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
Expand Down Expand Up @@ -241,7 +238,7 @@ fun HomeScreen(
HomeTopAppBar(
currentPlatform = state.currentPlatform,
onChangePlatform = {
onAction(HomeAction.SwitchFilterPlatform(it))
onAction(HomeAction.SwitchDiscoveryPlatform(it))
},
isPlatformPopupVisible = state.isPlatformPopupVisible,
onTogglePlatformPopup = {
Expand Down Expand Up @@ -590,7 +587,11 @@ private fun HomeTopAppBar(
}
}

if (isPlatformPopupVisible) {
AnimatedVisibility(
visible = isPlatformPopupVisible,
enter = slideInVertically(),
exit = slideOutVertically(),
) {
Box {
PlatformsPopup(
onTogglePlatformPopup = onTogglePlatformPopup,
Expand All @@ -606,6 +607,7 @@ private fun HomeTopAppBar(
)
}

@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun PlatformsPopup(
onTogglePlatformPopup: () -> Unit,
Expand All @@ -618,19 +620,20 @@ private fun PlatformsPopup(
Column(
modifier =
Modifier
.clip(RoundedCornerShape(8.dp))
.background(MaterialTheme.colorScheme.surfaceContainerHighest)
.padding(6.dp),
.width(250.dp)
.clip(RoundedCornerShape(24.dp))
.background(MaterialTheme.colorScheme.surfaceContainerHighest),
) {
DiscoveryPlatform.entries.forEach { platform ->
Box(
modifier =
Modifier
.fillMaxWidth()
.clickable(onClick = {
onChangePlatform(platform)
onTogglePlatformPopup()
})
.padding(horizontal = 32.dp, vertical = 8.dp),
.padding(horizontal = 24.dp, vertical = 8.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
Expand All @@ -645,15 +648,14 @@ private fun PlatformsPopup(
imageVector = Icons.Default.Done,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp),
modifier = Modifier.size(20.dp),
)
}

Text(
text = platform.toLabel(),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.onBackground,
style = MaterialTheme.typography.titleMediumEmphasized,
color = MaterialTheme.colorScheme.onSurface,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import zed.rainxch.core.domain.repository.FavouritesRepository
import zed.rainxch.core.domain.repository.InstalledAppsRepository
import zed.rainxch.core.domain.repository.SeenReposRepository
import zed.rainxch.core.domain.repository.StarredRepository
import zed.rainxch.core.domain.use_cases.SyncInstalledAppsUseCase
import zed.rainxch.core.domain.repository.TweaksRepository
import zed.rainxch.core.domain.use_cases.SyncInstalledAppsUseCase
import zed.rainxch.core.domain.utils.ShareManager
import zed.rainxch.core.presentation.model.DiscoveryRepositoryUi
import zed.rainxch.core.presentation.utils.toUi
Expand Down Expand Up @@ -66,6 +66,7 @@ class HomeViewModel(
observeStarredRepos()
observeLiquidGlassEnabled()
observeSeenRepos()
observeDiscoveryPlatform()
observeHideSeenEnabled()

hasLoadedInitialData = true
Expand Down Expand Up @@ -120,6 +121,18 @@ class HomeViewModel(
}
}

private fun observeDiscoveryPlatform() {
viewModelScope.launch {
tweaksRepository.getDiscoveryPlatform().collect { platform ->
_state.update {
it.copy(
currentPlatform = platform,
)
}
}
}
}

private fun loadRepos(
isInitial: Boolean = false,
category: HomeCategory? = null,
Expand Down Expand Up @@ -147,13 +160,17 @@ class HomeViewModel(

return viewModelScope
.launch {
if (platform != null) {
tweaksRepository.setDiscoveryPlatform(targetPlatform)
}

_state.update {
it.copy(
isLoading = isInitial,
isLoadingMore = !isInitial,
errorMessage = null,
currentCategory = targetCategory,
currentPlatform = targetPlatform,
currentCategory = targetCategory,
selectedTopic = targetTopic,
repos = if (isInitial) persistentListOf() else it.repos,
)
Expand Down Expand Up @@ -269,8 +286,9 @@ class HomeViewModel(
val cachedReposWithStatus = mapReposToUi(paginatedRepos.repos)

_state.update { currentState ->
val merged = (currentState.repos + cachedReposWithStatus)
.distinctBy { it.repository.fullName }
val merged =
(currentState.repos + cachedReposWithStatus)
.distinctBy { it.repository.fullName }

currentState.copy(
repos = merged.toImmutableList(),
Expand All @@ -291,8 +309,9 @@ class HomeViewModel(
val newReposWithStatus = mapReposToUi(paginatedRepos.repos)

_state.update { currentState ->
val merged = (currentState.repos + newReposWithStatus)
.distinctBy { it.repository.fullName }
val merged =
(currentState.repos + newReposWithStatus)
.distinctBy { it.repository.fullName }

currentState.copy(
repos = merged.toImmutableList(),
Expand All @@ -309,9 +328,7 @@ class HomeViewModel(
}
}

private suspend fun mapReposToUi(
repos: List<zed.rainxch.core.domain.model.GithubRepoSummary>,
): List<DiscoveryRepositoryUi> {
private suspend fun mapReposToUi(repos: List<zed.rainxch.core.domain.model.GithubRepoSummary>): List<DiscoveryRepositoryUi> {
val installedAppsMap =
installedAppsRepository
.getAllInstalledApps()
Expand Down Expand Up @@ -421,15 +438,15 @@ class HomeViewModel(
}
}

is HomeAction.SwitchFilterPlatform -> {
is HomeAction.SwitchDiscoveryPlatform -> {
if (_state.value.currentPlatform != action.platform) {
nextPageIndex = 1
switchCategoryJob?.cancel()
switchCategoryJob =
viewModelScope.launch {
loadRepos(isInitial = true, platform = action.platform)?.join()
?: return@launch
_events.send(HomeEvent.OnScrollToListTop)
_events.send(OnScrollToListTop)
}
}
}
Expand Down
Loading