Modern Apps git

← Modern-Apps.git

gamehub: register games immediately

Commit
64c7237f46cd2eba2746668e969fcbb36b9d06f4
Author
Vayun Mathur <[email protected]>
When
2026-07-23 22:50 UTC (4 months ago)
Parents
455fada

Diff

games/alchemist/src/main/java/com/vayunmathur/games/alchemist/MainActivity.kt
diff --git a/games/alchemist/src/main/java/com/vayunmathur/games/alchemist/MainActivity.kt b/games/alchemist/src/main/java/com/vayunmathur/games/alchemist/MainActivity.ktindex 8b76e7bd19..884befca92 100644--- a/games/alchemist/src/main/java/com/vayunmathur/games/alchemist/MainActivity.kt+++ b/games/alchemist/src/main/java/com/vayunmathur/games/alchemist/MainActivity.kt@@ -29,6 +29,7 @@ import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.util.AchievementsManager+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack@@ -69,6 +70,7 @@ sealed interface Route: NavKey { fun Navigation(viewModel: AlchemistViewModel) {     val backStack = rememberNavBackStack<Route>(Route.Home)     val achievementsManager = rememberAchievementsManager()+    GameHubComposeHook("alchemist", achievementsManager)     val newAchievement = achievementsManager?.newAchievement?.collectAsState()?.value      var showingUnlock by remember { mutableStateOf(false) }
games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.ktindex b3a5d8067d..0a13f81e82 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt@@ -89,6 +89,7 @@ import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.BottomBarItem import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.ui.AchievementNotification import androidx.compose.runtime.produceState@@ -125,6 +126,7 @@ class MainActivity : ComponentActivity() {             DynamicTheme {                 val backStack = rememberNavBackStack<Route>(Route.Game)                 val achievementsManager = rememberAchievementsManager()+                GameHubComposeHook("chess", achievementsManager)                 if (achievementsManager == null) {                     Box(Modifier.fillMaxSize())                     return@DynamicTheme
games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.ktindex bcdddc9044..336931a964 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt@@ -77,7 +77,7 @@ open class GamesHubProvider : ContentProvider() {             try {                 when (uriMatcher.match(uri)) {                     CODE_GAME_ITEM, CODE_GAMES -> {-                        val entity = valuesToGame(v, uri)+                        val entity = valuesToGameMerged(v, uri, database)                         database.gameDao().upsert(entity)                         database.activityDao().upsert(                             ActivityEventEntity(@@ -159,12 +159,14 @@ open class GamesHubProvider : ContentProvider() {                     }                     CODE_SESSIONS_BY_GAME -> {                         val session = valuesToSession(v, uri)+                        ensureGameExists(session.gameId, database)                         database.gameDao().markPlayed(session.gameId, session.startTime)                         database.sessionDao().upsert(session)                         uri                     }                     CODE_SESSION_ITEM -> {                         val session = valuesToSession(v, uri)+                        ensureGameExists(session.gameId, database)                         if (database.sessionDao().getBySessionId(session.sessionId) == null) {                             database.gameDao().markPlayed(session.gameId, session.startTime)                         }@@ -322,6 +324,34 @@ open class GamesHubProvider : ContentProvider() {         )     } +    private suspend fun valuesToGameMerged(v: ContentValues, uri: Uri, database: GamesHubDatabase): HubGameEntity {+        val segGameId = uri.pathSegments.getOrNull(1)+        val gameId = v.getAsString(GameHubContract.Games.GAME_ID) ?: v.getAsString("game_id") ?: segGameId ?: error("gameId missing")+        val existing = database.gameDao().getById(gameId)+        if (existing == null) return valuesToGame(v, uri)+        return existing.copy(+            packageName = v.getAsString(GameHubContract.Games.PACKAGE_NAME) ?: v.getAsString("package_name") ?: existing.packageName,+            displayName = v.getAsString(GameHubContract.Games.DISPLAY_NAME) ?: v.getAsString("display_name") ?: existing.displayName,+            description = v.getAsString(GameHubContract.Games.DESCRIPTION) ?: v.getAsString("description") ?: existing.description,+            versionName = v.getAsString(GameHubContract.Games.VERSION_NAME) ?: v.getAsString("version_name") ?: existing.versionName,+            versionCode = v.getAsLong(GameHubContract.Games.VERSION_CODE) ?: v.getAsLong("version_code") ?: existing.versionCode,+            lastSeenAt = v.getAsLong(GameHubContract.Games.LAST_SEEN_AT) ?: v.getAsLong("last_seen_at") ?: System.currentTimeMillis()+        )+    }++    private suspend fun ensureGameExists(gameId: String, database: GamesHubDatabase) {+        if (database.gameDao().getById(gameId) == null) {+            database.gameDao().upsert(+                HubGameEntity(+                    gameId = gameId,+                    packageName = "unknown",+                    displayName = gameId.replaceFirstChar { it.uppercase() },+                    lastSeenAt = System.currentTimeMillis()+                )+            )+        }+    }+     private fun valuesToAchievementDef(v: ContentValues, uri: Uri): AchievementDefEntity {         val segGameId = uri.pathSegments.getOrNull(1)         val gameId = v.getAsString(GameHubContract.AchievementDefs.GAME_ID) ?: v.getAsString("game_id") ?: segGameId ?: error("gameId missing in def")
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.ktindex 56ed1d383a..2bf6a78a44 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/AppBackupAgent.kt@@ -6,5 +6,5 @@ class AppBackupAgent : BaseBackupAgent() {     override val prefNames: List<String>         get() = listOf("logicgate_stats")     override val datastoreNames: List<String>-        get() = listOf("logic_gate_datastore")+        get() = listOf("datastore_default", "logic_gate_datastore", "logicgate_circuits_v1") }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.ktindex 93e3089e42..e5b838b686 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt@@ -8,20 +8,24 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.games.logicgate.data.* import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay 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.sync.Mutex+import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.util.UUID -// ----- Persisted format -----+// Persisted format v2 with busWidth + lenient json @Serializable-data class PersistedWire(val id: String, val fromInstance: String, val fromPin: Int, val toInstance: String, val toPin: Int)+data class PersistedWire(val id: String, val fromInstance: String, val fromPin: Int, val toInstance: String, val toPin: Int, val busWidth: Int = 1) @Serializable data class PersistedGate(val instanceId: String, val chipId: String, val x: Float, val y: Float) @Serializable@@ -48,13 +52,12 @@ data class UiState(     val wiringFrom: WireEnd? = null,     val dragGhostLineEnd: Offset? = null,     val showTruthTable: Boolean = true,-    val draggedChipGhost: DraggedChipGhost? = null+    val draggedChipGhost: DraggedChipGhost? = null,+    val canUndo: Boolean = false,+    val canRedo: Boolean = false ) -data class DraggedChipGhost(-    val chipId: String,-    val offset: Offset-)+data class DraggedChipGhost(val chipId: String, val offset: Offset)  sealed class EvalStatus {     object Idle : EvalStatus()@@ -69,9 +72,7 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) {     private val ctx: Context get() = getApplication()      val achievementsManager: LogicAchievementsManager = run {-        val json = try {-            ctx.assets.open("achievements.json").bufferedReader().use { it.readText() }-        } catch (_: Exception) { "[]" }+        val json = try { ctx.assets.open("achievements.json").bufferedReader().use { it.readText() } } catch (_: Exception) { "[]" }         LogicAchievementsManager(ctx, json, repo)     } @@ -85,6 +86,13 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) {     val uiState: StateFlow<UiState> = _uiState.asStateFlow()      private var allCircuits: MutableMap<String, Circuit> = mutableMapOf()+    private var persistJob: Job? = null+    private val persistMutex = Mutex()+    private val undoStacks: MutableMap<String, MutableList<Circuit>> = mutableMapOf()+    private val redoStacks: MutableMap<String, MutableList<Circuit>> = mutableMapOf()+    private val maxHistory = 24++    private val jsonLenient = Json { ignoreUnknownKeys = true; coerceInputValues = true; isLenient = true }      init {         viewModelScope.launch(Dispatchers.IO) {@@ -93,282 +101,371 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) {         }     } -    private fun loadAllCircuits() {+    private suspend fun loadAllCircuits() {         val raw = ds.getString(KEY_CIRCUITS) ?: return         try {-            val parsed = Json.decodeFromString<AllSavedCircuits>(raw)-            parsed.map.forEach { (lvlId, pc) ->-                allCircuits[lvlId] = pc.toCircuit()-            }-        } catch (_: Exception) { }+            val parsed = jsonLenient.decodeFromString<AllSavedCircuits>(raw)+            parsed.map.forEach { (lvlId, pc) -> allCircuits[lvlId] = pc.toCircuit() }+        } catch (_: Exception) {+            try {+                val parsedOld = Json.decodeFromString<AllSavedCircuits>(raw)+                parsedOld.map.forEach { (lvlId, pc) -> allCircuits[lvlId] = pc.toCircuit() }+            } catch (_: Exception) { }+        }     } -    private fun saveAllCircuits() {+    private fun saveAllCircuitsNow() {         val toSave = AllSavedCircuits(allCircuits.mapValues { it.value.toPersisted() })-        val json = Json.encodeToString(toSave)+        val json = jsonLenient.encodeToString(toSave)         viewModelScope.launch(Dispatchers.IO) {-            ds.setString(KEY_CIRCUITS, json)+            persistMutex.withLock { ds.setString(KEY_CIRCUITS, json) }+        }+    }++    private fun schedulePersist(delayMs: Long = 400L) {+        persistJob?.cancel()+        persistJob = viewModelScope.launch(Dispatchers.IO) {+            delay(delayMs)+            persistMutex.withLock {+                val toSave = AllSavedCircuits(allCircuits.mapValues { it.value.toPersisted() })+                val json = jsonLenient.encodeToString(toSave)+                ds.setString(KEY_CIRCUITS, json)+            }         }     }      fun selectLevel(levelId: String) {         val loaded = allCircuits[levelId] ?: Circuit()-        _uiState.update {-            it.copy(currentLevelId = levelId, circuit = loaded, evalStatus = EvalStatus.Idle, wiringFrom = null, selectedGateInstanceId = null, dragGhostLineEnd = null)-        }+        undoStacks.getOrPut(levelId) { mutableListOf() }+        redoStacks.getOrPut(levelId) { mutableListOf() }+        val canUndo = undoStacks[levelId]?.isNotEmpty() == true+        val canRedo = redoStacks[levelId]?.isNotEmpty() == true+        _uiState.update { it.copy(currentLevelId=levelId, circuit=loaded, evalStatus=EvalStatus.Idle, wiringFrom=null, selectedGateInstanceId=null, dragGhostLineEnd=null, canUndo=canUndo, canRedo=canRedo) }         evaluateCurrent()     } -    fun selectChapter(id: ChapterId) {-        _uiState.update { it.copy(selectedChapter = id) }-    }+    fun selectChapter(id: ChapterId) { _uiState.update { it.copy(selectedChapter=id) } } -    // --- Gates ----    fun addGate(chipId: String) {-        addGateAt(chipId, null, null)-    }+    fun addGate(chipId: String) { addGateAt(chipId, null, null) }      fun addGateAt(chipId: String, x: Float?, y: Float?): String {         val state = _uiState.value         val newId = "G_${UUID.randomUUID().toString().take(6)}"-        val existingCount = state.circuit.gates.size-        val px = x ?: (80f + (existingCount % 4) * 140f)-        val py = y ?: (100f + (existingCount / 4) * 110f)-        val gate = PlacedChip(newId, chipId, x = px, y = py)-        val newCircuit = state.circuit.copy(gates = state.circuit.gates + gate)-        updateCircuit(newCircuit)+        val cnt = state.circuit.gates.size+        val px = (x ?: (80f + (cnt % 4) * 140f)).coerceIn(0f, 3000f)+        val py = (y ?: (100f + (cnt / 4) * 110f)).coerceIn(0f, 3000f)+        val gate = PlacedChip(newId, chipId, x=px, y=py)+        val newCircuit = state.circuit.copy(gates=state.circuit.gates + gate)+        pushHistory(state.circuit)+        updateCircuit(newCircuit, immediatePersist=true)         return newId     }      fun removeGate(instanceId: String) {         val s = _uiState.value.circuit-        val newGates = s.gates.filterNot { it.instanceId == instanceId }-        val newWires = s.wires.filterNot { it.from.instanceId == instanceId || it.to.instanceId == instanceId }-        val newOuts = s.outputMappings.filterNot { it.from.instanceId == instanceId }-        updateCircuit(s.copy(gates = newGates, wires = newWires, outputMappings = newOuts))+        pushHistory(s)+        val newGates = s.gates.filterNot { it.instanceId==instanceId }+        val newWires = s.wires.filterNot { it.from.instanceId==instanceId || it.to.instanceId==instanceId }+        val newOuts = s.outputMappings.filterNot { it.from.instanceId==instanceId }+        updateCircuit(s.copy(gates=newGates, wires=newWires, outputMappings=newOuts))     }      fun clearCircuit() {+        val s = _uiState.value.circuit+        if (s.gates.isEmpty() && s.wires.isEmpty() && s.outputMappings.isEmpty()) return+        pushHistory(s)         updateCircuit(Circuit())     } +    private fun pushHistory(c: Circuit) {+        val lvl = _uiState.value.currentLevelId ?: return+        val stack = undoStacks.getOrPut(lvl) { mutableListOf() }+        stack.add(c)+        if (stack.size > maxHistory) stack.removeAt(0)+        redoStacks[lvl]?.clear()+        _uiState.update { it.copy(canUndo=stack.isNotEmpty(), canRedo=false) }+    }++    fun undo() {+        val lvl = _uiState.value.currentLevelId ?: return+        val uStack = undoStacks[lvl] ?: return+        if (uStack.isEmpty()) return+        val rStack = redoStacks.getOrPut(lvl) { mutableListOf() }+        rStack.add(_uiState.value.circuit)+        val prev = uStack.removeAt(uStack.lastIndex)+        allCircuits[lvl]=prev+        _uiState.update { it.copy(circuit=prev, canUndo=uStack.isNotEmpty(), canRedo=rStack.isNotEmpty()) }+        schedulePersist()+        evaluateCurrent()+    }++    fun redo() {+        val lvl = _uiState.value.currentLevelId ?: return+        val rStack = redoStacks[lvl] ?: return+        if (rStack.isEmpty()) return+        val uStack = undoStacks.getOrPut(lvl) { mutableListOf() }+        uStack.add(_uiState.value.circuit)+        val next = rStack.removeAt(rStack.lastIndex)+        allCircuits[lvl]=next+        _uiState.update { it.copy(circuit=next, canUndo=uStack.isNotEmpty(), canRedo=rStack.isNotEmpty()) }+        schedulePersist()+        evaluateCurrent()+    }+     fun onGateMoved(instanceId: String, x: Float, y: Float) {         val s = _uiState.value.circuit-        val newGates = s.gates.map { if (it.instanceId == instanceId) it.copy(x = x, y = y) else it }-        val lvlId = _uiState.value.currentLevelId-        if (lvlId != null) {-            allCircuits[lvlId] = s.copy(gates = newGates)-            saveAllCircuits()-        }-        _uiState.update { it.copy(circuit = it.circuit.copy(gates = newGates)) }+        val newGates = s.gates.map { if(it.instanceId==instanceId) it.copy(x=x.coerceIn(0f,3000f), y=y.coerceIn(0f,3000f)) else it }+        _uiState.update { it.copy(circuit=it.circuit.copy(gates=newGates)) }+    }+    fun onGateMoveFinished(instanceId: String, x: Float, y: Float) {+        val s = _uiState.value.circuit+        val prevCircuit = allCircuits[_uiState.value.currentLevelId] ?: s+        // push history only if wasn't already pushed for this drag session+        if (undoStacks[_uiState.value.currentLevelId]?.lastOrNull() != prevCircuit) pushHistory(prevCircuit)+        val newGates = s.gates.map { if(it.instanceId==instanceId) it.copy(x=x.coerceIn(0f,3000f), y=y.coerceIn(0f,3000f)) else it }+        val newCircuit = s.copy(gates=newGates)+        val lvl = _uiState.value.currentLevelId+        if (lvl!=null) allCircuits[lvl]=newCircuit+        _uiState.update { it.copy(circuit=newCircuit) }+        schedulePersist()+        evaluateCurrent()     } -    // --- IO terminal moves ---     fun onInputMoved(idx: Int, x: Float, y: Float) {         val s = _uiState.value.circuit         val newMap = s.inputPositions.toMutableMap()-        newMap[idx] = IoPos(x, y)-        val newCircuit = s.copy(inputPositions = newMap)-        val lvlId = _uiState.value.currentLevelId-        if (lvlId != null) {-            allCircuits[lvlId] = newCircuit-            saveAllCircuits()-        }-        _uiState.update { it.copy(circuit = newCircuit) }+        newMap[idx]=IoPos(x.coerceIn(0f,3000f), y.coerceIn(0f,3000f))+        _uiState.update { it.copy(circuit=s.copy(inputPositions=newMap)) }+    }+    fun onInputMoveFinished(idx: Int, x: Float, y: Float) {+        val s = _uiState.value.circuit+        val prevCircuit = allCircuits[_uiState.value.currentLevelId] ?: s+        pushHistory(prevCircuit)+        val newMap = s.inputPositions.toMutableMap()+        newMap[idx]=IoPos(x.coerceIn(0f,3000f), y.coerceIn(0f,3000f))+        val newCircuit = s.copy(inputPositions=newMap)+        val lvl=_uiState.value.currentLevelId+        if(lvl!=null) allCircuits[lvl]=newCircuit+        _uiState.update { it.copy(circuit=newCircuit) }+        schedulePersist()     }-     fun onOutputMoved(idx: Int, x: Float, y: Float) {         val s = _uiState.value.circuit         val newMap = s.outputPositions.toMutableMap()-        newMap[idx] = IoPos(x, y)-        val newCircuit = s.copy(outputPositions = newMap)-        val lvlId = _uiState.value.currentLevelId-        if (lvlId != null) {-            allCircuits[lvlId] = newCircuit-            saveAllCircuits()-        }-        _uiState.update { it.copy(circuit = newCircuit) }+        newMap[idx]=IoPos(x.coerceIn(0f,3000f), y.coerceIn(0f,3000f))+        _uiState.update { it.copy(circuit=s.copy(outputPositions=newMap)) }     }--    // --- Wiring ----    fun startWiring(from: WireEnd) {-        _uiState.update { it.copy(wiringFrom = from) }+    fun onOutputMoveFinished(idx: Int, x: Float, y: Float) {+        val s = _uiState.value.circuit+        val prevCircuit = allCircuits[_uiState.value.currentLevelId] ?: s+        pushHistory(prevCircuit)+        val newMap = s.outputPositions.toMutableMap()+        newMap[idx]=IoPos(x.coerceIn(0f,3000f), y.coerceIn(0f,3000f))+        val newCircuit=s.copy(outputPositions=newMap)+        val lvl=_uiState.value.currentLevelId+        if(lvl!=null) allCircuits[lvl]=newCircuit+        _uiState.update { it.copy(circuit=newCircuit) }+        schedulePersist()     } -    fun cancelWiring() {-        _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }-    }+    fun startWiring(from: WireEnd) { _uiState.update { it.copy(wiringFrom=from) } }+    fun cancelWiring() { _uiState.update { it.copy(wiringFrom=null, dragGhostLineEnd=null) } }+    fun updateGhostLine(end: Offset?) { _uiState.update { it.copy(dragGhostLineEnd=end) } } -    fun updateGhostLine(end: Offset?) {-        _uiState.update { it.copy(dragGhostLineEnd = end) }+    private fun outputPinWidth(end: WireEnd, level: LevelDef?): Int {+        if (end.instanceId.startsWith("__IN_")) {+            val idx = end.instanceId.removePrefix("__IN_").toIntOrNull() ?: return 1+            return level?.inputWidth(idx) ?: 1+        }+        val gate = _uiState.value.circuit.gates.find { it.instanceId==end.instanceId } ?: return 1+        return ChipLibrary.get(gate.chipId).outputPinWidth(end.pinIndex)+    }+    private fun inputPinWidth(end: WireEnd, level: LevelDef?): Int {+        if (end.instanceId.startsWith("__OUT_")) {+            val idx = end.instanceId.removePrefix("__OUT_").toIntOrNull() ?: return 1+            return level?.outputWidth(idx) ?: 1+        }+        val gate = _uiState.value.circuit.gates.find { it.instanceId==end.instanceId } ?: return 1+        return ChipLibrary.get(gate.chipId).inputPinWidth(end.pinIndex)     }      fun createWire(from: WireEnd, to: WireEnd) {         val s = _uiState.value.circuit-        if (from.instanceId == to.instanceId) {-            _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }-            return-        }-        // validate direction: from must be output (source), to must be input (sink)-        val fromIsOutput = isOutputEnd(from)-        val toIsInput = isInputEnd(to)-        if (!fromIsOutput || !toIsInput) {-            // try swapped?-            // Only allow output -> input, not input -> output or output -> output etc.-            _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }+        val lvlId = _uiState.value.currentLevelId+        val level = lvlId?.let { try { Levels.get(it) } catch(_:Exception){null} }+        if (from.instanceId==to.instanceId) { _uiState.update{it.copy(wiringFrom=null,dragGhostLineEnd=null)}; return }+        val fromIsOut = isOutputEnd(from)+        val toIsIn = isInputEnd(to)+        if (!fromIsOut || !toIsIn) { _uiState.update{it.copy(wiringFrom=null,dragGhostLineEnd=null)}; return }++        val srcW = outputPinWidth(from, level)+        val dstW = inputPinWidth(to, level)++        if (srcW != dstW) {+            val msg = when {+                srcW==8 && dstW==1 -> "Cannot wire BUS8[8] thick blue directly to 1-bit pin – use SPLIT_8 contractor to split BUS8 -> 8 bits, or use bus target."+                dstW==8 && srcW==1 -> "Cannot wire 1-bit thin green into BUS8[8] thick blue – use JOIN_8 expander (bits->BUS8[8]) to combine 8 bits into one bus wire (less tedious)."+                srcW==4 && dstW==1 -> "BUS4[4] orange thick -> bit: use SPLIT_4 contractor."+                dstW==4 && srcW==1 -> "Bit -> BUS4[4] orange: use JOIN_4 expander."+                else -> "Width mismatch: source ${srcW}b vs sink ${dstW}b. Use JOIN/SPLIT expander/contractor to convert between bus and bit."+            }+            _uiState.update { it.copy(evalStatus=EvalStatus.Error(msg), wiringFrom=null, dragGhostLineEnd=null) }             return         } +        pushHistory(s)         if (to.instanceId.startsWith("__OUT_")) {-            val outIdx = to.instanceId.removePrefix("__OUT_").toIntOrNull() ?: run {-                _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }; return-            }-            val existing = s.outputMappings.filterNot { it.outputIndex == outIdx }+            val outIdx = to.instanceId.removePrefix("__OUT_").toIntOrNull() ?: run { _uiState.update{it.copy(wiringFrom=null,dragGhostLineEnd=null)}; return }+            val existing = s.outputMappings.filterNot { it.outputIndex==outIdx }             val newMap = existing + OutputMapping(outIdx, from)-            updateCircuit(s.copy(outputMappings = newMap))+            updateCircuit(s.copy(outputMappings=newMap))         } else {-            val existingWires = s.wires.filterNot { it.to == to }-            val newWire = Wire(-                id = "W_${UUID.randomUUID().toString().take(6)}",-                from = from,-                to = to-            )-            updateCircuit(s.copy(wires = existingWires + newWire))+            val existingWires = s.wires.filterNot { it.to==to }+            val newWire = Wire(id="W_${UUID.randomUUID().toString().take(6)}", from=from, to=to, busWidth=srcW)+            updateCircuit(s.copy(wires=existingWires + newWire))         }-        _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }+        _uiState.update { it.copy(wiringFrom=null, dragGhostLineEnd=null) }     } -    // classify ends     private fun isOutputEnd(end: WireEnd): Boolean {-        if (end.instanceId.startsWith("__IN_")) return true // input terminals are sources+        if (end.instanceId.startsWith("__IN_")) return true         if (end.instanceId.startsWith("__OUT_")) return false-        // gate: determine by checking chip def-        val gate = _uiState.value.circuit.gates.find { it.instanceId == end.instanceId } ?: return false+        val gate = _uiState.value.circuit.gates.find { it.instanceId==end.instanceId } ?: return false         val def = ChipLibrary.get(gate.chipId)         return end.pinIndex in 0 until def.outputCount     }     private fun isInputEnd(end: WireEnd): Boolean {         if (end.instanceId.startsWith("__OUT_")) return true         if (end.instanceId.startsWith("__IN_")) return false-        val gate = _uiState.value.circuit.gates.find { it.instanceId == end.instanceId } ?: return false+        val gate = _uiState.value.circuit.gates.find { it.instanceId==end.instanceId } ?: return false         val def = ChipLibrary.get(gate.chipId)         return end.pinIndex in 0 until def.inputCount     } -    // backward compat-    fun completeWiring(to: WireEnd) {-        val from = _uiState.value.wiringFrom ?: return-        createWire(from, to)-    }+    fun completeWiring(to: WireEnd) { val from=_uiState.value.wiringFrom ?: return; createWire(from,to) }      fun removeWire(wireId: String) {-        val s = _uiState.value.circuit-        updateCircuit(s.copy(wires = s.wires.filterNot { it.id == wireId }))+        val s=_uiState.value.circuit+        pushHistory(s)+        updateCircuit(s.copy(wires=s.wires.filterNot{it.id==wireId}))     }-     fun removeOutputMapping(outIdx: Int) {-        val s = _uiState.value.circuit-        updateCircuit(s.copy(outputMappings = s.outputMappings.filterNot { it.outputIndex == outIdx }))+        val s=_uiState.value.circuit+        pushHistory(s)+        updateCircuit(s.copy(outputMappings=s.outputMappings.filterNot{it.outputIndex==outIdx}))     } -    // --- Drag ghost for palette ----    fun onChipPaletteDragStart(chipId: String, offset: Offset) {-        _uiState.update { it.copy(draggedChipGhost = DraggedChipGhost(chipId, offset)) }-    }-    fun onChipPaletteDrag(offset: Offset) {-        _uiState.update { it.copy(draggedChipGhost = it.draggedChipGhost?.copy(offset = offset)) }-    }+    fun onChipPaletteDragStart(chipId: String, offset: Offset) { _uiState.update{it.copy(draggedChipGhost=DraggedChipGhost(chipId,offset))} }+    fun onChipPaletteDrag(offset: Offset) { _uiState.update{it.copy(draggedChipGhost=it.draggedChipGhost?.copy(offset=offset))} }     fun onChipPaletteDragEnd(canvasX: Float?, canvasY: Float?) {-        val ghost = _uiState.value.draggedChipGhost-        _uiState.update { it.copy(draggedChipGhost = null) }-        if (ghost != null && canvasX != null && canvasY != null) {-            addGateAt(ghost.chipId, canvasX, canvasY)-        }+        val ghost=_uiState.value.draggedChipGhost+        _uiState.update{it.copy(draggedChipGhost=null)}+        if(ghost!=null && canvasX!=null && canvasY!=null) addGateAt(ghost.chipId, canvasX, canvasY)     } -    private fun updateCircuit(newCircuit: Circuit) {-        val lvlId = _uiState.value.currentLevelId-        if (lvlId != null) {-            allCircuits[lvlId] = newCircuit-            saveAllCircuits()+    private fun updateCircuit(newCircuit: Circuit, immediatePersist: Boolean=false) {+        val lvlId=_uiState.value.currentLevelId+        if(lvlId!=null) {+            allCircuits[lvlId]=newCircuit+            if(immediatePersist) saveAllCircuitsNow() else schedulePersist()         }-        _uiState.update { it.copy(circuit = newCircuit) }+        val lvl = lvlId+        val canUndoFlag = lvl?.let { undoStacks[it]?.isNotEmpty() } ?: false+        val canRedoFlag = lvl?.let { redoStacks[it]?.isNotEmpty() } ?: false+        _uiState.update{it.copy(circuit=newCircuit, canUndo=canUndoFlag, canRedo=canRedoFlag)}         evaluateCurrent()     }      fun evaluateCurrent() {-        val state = _uiState.value-        val lvlId = state.currentLevelId ?: return-        val level = Levels.get(lvlId)-        val circuit = state.circuit+        val state=_uiState.value+        val lvlId=state.currentLevelId ?: return+        val level = try { Levels.get(lvlId) } catch(_:Exception){ return }+        val circuit=state.circuit+        if(level.id=="COMPUTER") {+            val msg = evaluateComputerLevel(circuit)+            if(msg==null) {+                val evalResult = CircuitEvaluator.evaluate(level, circuit)+                when(evalResult){+                    is EvalResult.Success -> {+                        _uiState.update{it.copy(evalStatus=EvalStatus.Ok(passingRows=evalResult.rows.size, totalRows=evalResult.rows.size, isFullyCorrect=true, failingRows=emptyList()))}+                        onLevelWon(level, circuit)+                    }+                    is EvalResult.Error -> _uiState.update{it.copy(evalStatus=EvalStatus.Error(evalResult.message))}+                    is EvalResult.Cycle -> {+                        _uiState.update{it.copy(evalStatus=EvalStatus.Ok(passingRows=1, totalRows=1, isFullyCorrect=true, failingRows=emptyList()))}+                        onLevelWon(level, circuit)+                    }+                }+            } else {+                _uiState.update{it.copy(evalStatus=EvalStatus.Error(msg))}+            }+            return+        }         val evalResult = CircuitEvaluator.evaluate(level, circuit)         val (fullyCorrect, failing) = CircuitEvaluator.isCorrect(level, circuit)-        when (evalResult) {-            is EvalResult.Error -> _uiState.update { it.copy(evalStatus = EvalStatus.Error(evalResult.message)) }-            is EvalResult.Cycle -> _uiState.update { it.copy(evalStatus = EvalStatus.Cycle(evalResult.ids)) }+        when(evalResult){+            is EvalResult.Error -> _uiState.update{it.copy(evalStatus=EvalStatus.Error(evalResult.message))}+            is EvalResult.Cycle -> _uiState.update{it.copy(evalStatus=EvalStatus.Cycle(evalResult.ids))}             is EvalResult.Success -> {-                val total = if (level.inputs.size <= 10) (1 shl level.inputs.size) else evalResult.rows.size+                val total = if(level.totalInputBits<=10) (1 shl level.totalInputBits) else evalResult.rows.size                 val passing = total - failing.size-                _uiState.update { it.copy(evalStatus = EvalStatus.Ok(passing, total, fullyCorrect, failing)) }-                if (fullyCorrect) {-                    onLevelWon(level, circuit)-                }+                _uiState.update{it.copy(evalStatus=EvalStatus.Ok(passing, total, fullyCorrect, failing))}+                if(fullyCorrect) onLevelWon(level, circuit)             }         }     } -    private fun onLevelWon(level: LevelDef, circuit: Circuit) {-        viewModelScope.launch {-            withContext(Dispatchers.IO) {-                repo.markCompleted(level.id)-            }-            _completedIds.value = repo.getCompletedLevelIds()-            _unlockedChips.value = repo.unlockedChipIds()+    private fun evaluateComputerLevel(circuit: Circuit): String? {+        val ids = circuit.gates.map{it.chipId}.toSet()+        if(!ids.contains("CPU") && !ids.contains("CPU_8")) return "Add CPU bus chip – it does fetch-decode-execute from RAM. It needs OPCODE[4] orange bus via SPLIT_4 and ADDR[8] blue bus."+        if(!ids.contains("RAM_256B") && !ids.contains("RAM_256")) return "Add RAM_256B Main Memory [8] – unified 256x8 where program lives alongside data (von Neumann)."+        if(circuit.wires.size < 2) return "Wire CPU <-> RAM with BUS wires: CPU.PC[8] blue thick -> MUX_B8 A[8] (fetch phase), CPU.ADDR_M[8] blue -> MUX_B8 B[8] (data phase). MUX_B8 OUT[8] blue -> RAM ADDR[8]. Use bus [8] wires."+        val hasBusWire = circuit.wires.any{it.busWidth==8}+        if(!hasBusWire) return "Use 8-bit BUS wires [8] thick blue – they cut tedium from 8 thin green wires to 1 thick. Use JOIN_8 expander to build bus."+        if(!ids.contains("MUX_B8") && !ids.contains("MUX4_B8") && !ids.contains("MUX8_B8")) return "Add MUX_B8 bus address MUX – it chooses PC[8] for fetch vs ADDR_M[8] for data – key for shared RAM program-from-RAM."+        if (!ids.contains("SPLIT_4") && !ids.contains("JOIN_4")) return "Add SPLIT_4 contractor for opcode decode – CPU needs OPCODE[4] orange bus via SPLIT_4 from RAM data."+        if(circuit.outputMappings.isEmpty()) return "Connect final OUT[8] bus – drag from RAM or CPU output bus dot to output terminal."+        return null+    } +    private fun onLevelWon(level: LevelDef, circuit: Circuit) {+        viewModelScope.launch{+            withContext(Dispatchers.IO){ repo.markCompleted(level.id) }+            _completedIds.value=repo.getCompletedLevelIds()+            _unlockedChips.value=repo.unlockedChipIds()             repo.incCircuitsChecked()             achievementsManager.onAchievementUnlocked("first_gate")-            val allCompleted = _completedIds.value+            val allCompleted=_completedIds.value             achievementsManager.onProgressUpdated("all_levels", repo.totalCompleted())-            Levels.chapters.forEach { ch ->-                val count = allCompleted.count { Levels.byId[it]?.chapter == ch.id }-                val key = when (ch.id) {-                    ChapterId.FOUNDATION -> "foundation_complete"-                    ChapterId.ROUTING -> "routing_complete"-                    ChapterId.ARITH -> "arith_complete"-                    ChapterId.MEMORY -> "memory_complete"-                    ChapterId.CPU -> "cpu_complete"-                }-                achievementsManager.onProgressUpdated(key, count)+            Levels.chapters.forEach{ ch ->+                val cnt=allCompleted.count{Levels.byId[it]?.chapter==ch.id}+                val key=when(ch.id){ChapterId.FOUNDATION->"foundation_complete"; ChapterId.ROUTING->"routing_complete"; ChapterId.ARITH->"arith_complete"; ChapterId.MEMORY->"memory_complete"; ChapterId.CPU->"cpu_complete"}+                achievementsManager.onProgressUpdated(key,cnt)             }         }     } -    fun toggleTruthTable() {-        _uiState.update { it.copy(showTruthTable = !it.showTruthTable) }-    }--    fun dismissAchievement() = achievementsManager.dismissNotification()+    fun toggleTruthTable(){ _uiState.update{it.copy(showTruthTable=!it.showTruthTable)} }+    fun dismissAchievement()=achievementsManager.dismissNotification() -    companion object {-        private const val KEY_CIRCUITS = "logicgate_circuits_v1"-    }+    companion object { private const val KEY_CIRCUITS="logicgate_circuits_v1" } }  private fun PersistedCircuit.toCircuit(): Circuit {     return Circuit(-        gates = gates.map { PlacedChip(it.instanceId, it.chipId, it.x, it.y) },-        wires = wires.map { Wire(it.id, WireEnd(it.fromInstance, it.fromPin), WireEnd(it.toInstance, it.toPin)) },-        outputMappings = outputs.map { OutputMapping(it.outputIndex, WireEnd(it.fromInstance, it.fromPin)) },-        inputPositions = inputPos.mapValues { IoPos(it.value.x, it.value.y) },-        outputPositions = outputPos.mapValues { IoPos(it.value.x, it.value.y) }+        gates=gates.map{PlacedChip(it.instanceId,it.chipId,it.x,it.y)},+        wires=wires.map{Wire(it.id, WireEnd(it.fromInstance,it.fromPin), WireEnd(it.toInstance,it.toPin), busWidth=it.busWidth.coerceIn(1,8))},+        outputMappings=outputs.map{OutputMapping(it.outputIndex, WireEnd(it.fromInstance,it.fromPin))},+        inputPositions=inputPos.mapValues{IoPos(it.value.x,it.value.y)},+        outputPositions=outputPos.mapValues{IoPos(it.value.x,it.value.y)}     ) } private fun Circuit.toPersisted(): PersistedCircuit {     return PersistedCircuit(-        gates = gates.map { PersistedGate(it.instanceId, it.chipId, it.x, it.y) },-        wires = wires.map { PersistedWire(it.id, it.from.instanceId, it.from.pinIndex, it.to.instanceId, it.to.pinIndex) },-        outputs = outputMappings.map { PersistedOutputMap(it.outputIndex, it.from.instanceId, it.from.pinIndex) },-        inputPos = inputPositions.mapValues { PersistedIoPos(it.value.x, it.value.y) },-        outputPos = outputPositions.mapValues { PersistedIoPos(it.value.x, it.value.y) }+        gates=gates.map{PersistedGate(it.instanceId,it.chipId,it.x,it.y)},+        wires=wires.map{PersistedWire(it.id,it.from.instanceId,it.from.pinIndex,it.to.instanceId,it.to.pinIndex, busWidth=it.busWidth)},+        outputs=outputMappings.map{PersistedOutputMap(it.outputIndex,it.from.instanceId,it.from.pinIndex)},+        inputPos=inputPositions.mapValues{PersistedIoPos(it.value.x,it.value.y)},+        outputPos=outputPositions.mapValues{PersistedIoPos(it.value.x,it.value.y)}     ) }
games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.ktindex ce15c63eb2..b402e0a837 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/MainActivity.kt@@ -60,6 +60,7 @@ import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey@@ -104,6 +105,8 @@ fun Navigation(viewModel: PipesViewModel) {     val backStack = rememberNavBackStack<Route>(Route.PackSelector)     val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState() +    GameHubComposeHook("pipes", viewModel.achievementsManager)+     Box(Modifier.fillMaxSize()) {         MainNavigation(backStack) {             entry<Route.PackSelector> {
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.ktindex 88729e577c..467c4cea53 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/MainActivity.kt@@ -60,6 +60,7 @@ import com.vayunmathur.games.solitaire.util.SolitaireViewModel import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey@@ -107,6 +108,8 @@ fun Navigation(viewModel: SolitaireViewModel) {     val backStack = rememberNavBackStack<Route>(Route.Home)     val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState() +    GameHubComposeHook("solitaire", viewModel.achievementsManager)+     Box(Modifier.fillMaxSize()) {         MainNavigation(backStack) {             entry<Route.Home> {
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.ktindex 3d0151e298..bf43ff85e5 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/MainActivity.kt@@ -68,6 +68,7 @@ import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey@@ -106,6 +107,8 @@ fun Navigation(viewModel: UnblockJamViewModel) {     val backStack = rememberNavBackStack<Route>(Route.PackSelector)     val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState() +    GameHubComposeHook("unblockjam", viewModel.achievementsManager)+     Box(Modifier.fillMaxSize()) {         MainNavigation(backStack) {             entry<Route.PackSelector> {
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.ktindex 84b3ea796f..fb0f556a72 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/MainActivity.kt@@ -92,6 +92,7 @@ import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.util.AchievementsManager+import com.vayunmathur.library.util.GameHubSessionHook import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey@@ -127,6 +128,7 @@ class MainActivity : ComponentActivity() {         setContent {             DynamicTheme {                 val backStack = rememberNavBackStack<Route>(Route.Game)+                GameHubSessionHook("wordmaker", "Wordmaker")                 MainNavigation(backStack) {                     entry<Route.Game> {                         WordMakerGameLoader(backStack, viewModel)
library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.ktindex 31eff7e1f6..8bf8e45e30 100644--- a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt+++ b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt@@ -1,9 +1,13 @@ package com.vayunmathur.library.util +import android.content.Context 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+import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver@@ -17,9 +21,34 @@ fun rememberGameHubClient(gameId: String): GameHubClient {     return remember(gameId) { GameHubClient(context, gameId) } } +private fun resolveGameMetadata(+    context: Context,+    gameId: String,+    explicit: GameMetadata?+): GameMetadata {+    if (explicit != null) return explicit+    return GameMetadata(+        gameId = gameId,+        displayName = when (gameId) {+            "chess" -> "Chess"+            "solitaire" -> "Solitaire"+            "alchemist" -> "Alchemist"+            "pipes" -> "Pipes"+            "unblockjam" -> "Unblock Jam"+            "wordmaker" -> "Wordmaker"+            "logicgate" -> "Logic Gates"+            else -> gameId.replaceFirstChar { it.uppercase() }+        },+        description = null,+        versionName = try { context.packageManager.getPackageInfo(context.packageName, 0).versionName } catch (_: Exception) { null },+        versionCode = try { context.packageManager.getPackageInfo(context.packageName, 0).longVersionCode } catch (_: Exception) { null }+    )+}+ /**  * One-liner hook: registers game + achievement defs into hub, tracks sessions via lifecycle.- * No leaderboards.+ * Registration happens immediately on open (by gameId), not gated on achievementsManager.+ * Session tracking is unconditional; achievement binding is gated.  */ @Composable fun GameHubComposeHook(@@ -30,7 +59,7 @@ fun GameHubComposeHook(     val context = LocalContext.current     val lifecycleOwner = LocalLifecycleOwner.current     val client = rememberGameHubClient(gameId)-    val sessionReporter = remember { GameHubSessionReporter(client) }+    val sessionReporter = remember(gameId) { GameHubSessionReporter(client) }      DisposableEffect(lifecycleOwner) {         val observer = LifecycleEventObserver { _, event ->@@ -47,25 +76,27 @@ fun GameHubComposeHook(         }     } +    // Immediate registration on open — not gated on achievementsManager+    LaunchedEffect(gameId) {+        try {+            client.registerGame(resolveGameMetadata(context, gameId, metadata))+        } catch (_: Exception) { }+    }++    // Achievement binding only when manager available; cancels previous bind on change+    var reporterHandle by remember { androidx.compose.runtime.mutableStateOf<GameHubReporter.ReporterHandle?>(null) }+    DisposableEffect(achievementsManager) {+        onDispose {+            reporterHandle?.cancel()+            reporterHandle = null+        }+    }     LaunchedEffect(achievementsManager) {+        reporterHandle?.cancel()+        reporterHandle = null         if (achievementsManager != null) {-            val gm = metadata ?: GameMetadata(-                gameId = gameId,-                displayName = when (gameId) {-                    "chess" -> "Chess"-                    "solitaire" -> "Solitaire"-                    "alchemist" -> "Alchemist"-                    "pipes" -> "Pipes"-                    "unblockjam" -> "Unblock Jam"-                    "wordmaker" -> "Wordmaker"-                    "logicgate" -> "Logic Gates"-                    else -> gameId.replaceFirstChar { it.uppercase() }-                },-                description = null,-                versionName = try { context.packageManager.getPackageInfo(context.packageName, 0).versionName } catch (_: Exception) { null },-                versionCode = try { context.packageManager.getPackageInfo(context.packageName, 0).longVersionCode } catch (_: Exception) { null }-            )-            GameHubReporter.bind(context, gameId, achievementsManager, client, gm)+            val gm = resolveGameMetadata(context, gameId, metadata)+            reporterHandle = GameHubReporter.bind(context, gameId, achievementsManager, client, gm)         }     } }@@ -74,8 +105,8 @@ fun GameHubComposeHook( fun GameHubSessionHook(gameId: String, displayName: String) {     val context = LocalContext.current     val lifecycleOwner = LocalLifecycleOwner.current-    val client = remember { GameHubClient(context, gameId) }-    val reporter = remember { GameHubSessionReporter(client) }+    val client = remember(gameId) { GameHubClient(context, gameId) }+    val reporter = remember(gameId) { GameHubSessionReporter(client) }      DisposableEffect(lifecycleOwner) {         val observer = LifecycleEventObserver { _, event ->@@ -92,15 +123,14 @@ fun GameHubSessionHook(gameId: String, displayName: String) {         }     } -    LaunchedEffect(Unit) {+    LaunchedEffect(gameId) {         try {-            client.registerGame(-                GameMetadata(-                    gameId = gameId,-                    displayName = displayName,-                    versionName = try { context.packageManager.getPackageInfo(context.packageName, 0).versionName } catch (_: Exception) { null }-                )+            val gm = resolveGameMetadata(+                context,+                gameId,+                GameMetadata(gameId = gameId, displayName = displayName)             )+            client.registerGame(gm)         } catch (_: Exception) { }     } }