Skip to content

Commit a4c0fb8

Browse files
committed
fix: ZERO/HERO messages were dropped after the model changes
- clear a stored OpenCode selection so it can no longer block the picker - remember a manual model pick and auto-select the keyless model only on first run - re-inject the hidden page bridge when returning to ZERO/HERO - report a missing internal page instead of silently dropping the message
1 parent ad2b4c6 commit a4c0fb8

1 file changed

Lines changed: 45 additions & 14 deletions

File tree

‎app/src/main/java/com/example/ui/MainScreen.kt‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ private const val SAVED_CHATS_KEY = "saved_chats"
168168
private const val MODEL_PREFS = "codein_model_state"
169169
private const val MODEL_CATALOG_KEY = "provider_models"
170170
private const val SELECTED_MODEL_KEY = "selected_model"
171+
private const val USER_PICKED_MODEL_KEY = "model_picked_by_user"
171172
private const val SELECTED_PROVIDER_KEY = "selected_provider"
172173

173174
private data class ChatMessage(
@@ -277,7 +278,8 @@ private val codeinModels = listOf(
277278
private val pollinationsFreeModels = listOf("openai", "openai-fast")
278279
private const val DEFAULT_AI_PROVIDER = "pollinations"
279280
private const val AI_PROVIDER_CATALOG_KEY = "ai_provider_catalog"
280-
// Pollinations is the keyless default; OpenCode stays available but needs its free key.
281+
private val retiredAiProviders = setOf("opencode")
282+
// Pollinations is the keyless default; ZERO/HERO keep using the built-in chat page.
281283

282284
private fun aiProviderCatalog(): Pair<List<Pair<String, String>>, Map<String, String>> {
283285
val labels = mutableListOf(
@@ -443,11 +445,17 @@ private fun MainChatScreen(
443445
val availableModels = remember(modelPrefs) {
444446
mutableStateListOf<CodeinModel>().apply {
445447
addAll(codeinModels)
448+
// An old save could point at a provider this build no longer ships (OpenCode).
449+
// Resetting it lets ZERO/HERO and the keyless model answer again instead of failing silently.
450+
if (modelPrefs.getString(SELECTED_PROVIDER_KEY, "").orEmpty() in retiredAiProviders) {
451+
modelPrefs.edit().remove(SELECTED_MODEL_KEY).remove(SELECTED_PROVIDER_KEY).remove(MODEL_CATALOG_KEY)
452+
.remove(USER_PICKED_MODEL_KEY).apply()
453+
}
446454
val stored = runCatching { JSONArray(modelPrefs.getString(MODEL_CATALOG_KEY, "[]")) }.getOrDefault(JSONArray())
447455
for (index in 0 until stored.length()) {
448456
val item = stored.optJSONObject(index) ?: continue
449457
val id = item.optString("id").takeIf { it.isNotBlank() } ?: continue
450-
val provider = item.optString("provider").takeIf { it.isNotBlank() }
458+
val provider = item.optString("provider").takeIf { it.isNotBlank() && it !in retiredAiProviders }
451459
val model = CodeinModel(id, item.optString("suffix", id), provider)
452460
if (none { it.id == model.id && it.providerId == model.providerId }) add(model)
453461
}
@@ -548,19 +556,33 @@ private fun MainChatScreen(
548556
}
549557
}
550558

551-
// First connection: make the keyless free model the default chat model,
552-
// unless the user already picked one (including the offline ZERO mode).
553-
LaunchedEffect(termuxConnected) {
559+
// First run: pick the keyless free model as soon as the local bridge connects, so the
560+
// chat works without saving a key. A model the user picked by hand is never replaced.
561+
LaunchedEffect(termuxConnected, isConnected) {
554562
if (!termuxConnected) return@LaunchedEffect
555-
if (modelPrefs.getString(SELECTED_MODEL_KEY, null) != null) return@LaunchedEffect
563+
if (modelPrefs.getBoolean(USER_PICKED_MODEL_KEY, false)) return@LaunchedEffect
556564
val model = availableModels.firstOrNull { it.providerId == DEFAULT_AI_PROVIDER } ?: return@LaunchedEffect
565+
if (selectedModel.id == model.id && selectedModel.providerId == model.providerId) return@LaunchedEffect
557566
selectedModel = model
558567
modelPrefs.edit()
559568
.putString(SELECTED_MODEL_KEY, model.id)
560569
.putString(SELECTED_PROVIDER_KEY, model.providerId.orEmpty())
561570
.apply()
562571
}
563572

573+
// Coming back from a local model to ZERO/HERO needs the built-in page to be alive;
574+
// re-inject its bridge instead of dropping every message.
575+
LaunchedEffect(selectedModel.providerId, isConnected) {
576+
if (selectedModel.providerId != null || isConnected) return@LaunchedEffect
577+
var attempt = 0
578+
while (attempt < 6 && !isConnected) {
579+
delay(1500)
580+
webView?.evaluateJavascript(CODEIN_JS_BRIDGE, null)
581+
if (attempt == 2) webView?.reload()
582+
attempt++
583+
}
584+
}
585+
564586
// Track Termux independently of the selected chat provider so all screens
565587
// report the same bridge state.
566588
LaunchedEffect(termuxClient) {
@@ -626,6 +648,7 @@ private fun MainChatScreen(
626648
}
627649
modelPrefs.edit()
628650
.putString(MODEL_CATALOG_KEY, catalog.toString())
651+
.putBoolean(USER_PICKED_MODEL_KEY, true)
629652
.putString(SELECTED_MODEL_KEY, model.id)
630653
.putString(SELECTED_PROVIDER_KEY, model.providerId ?: "")
631654
.apply()
@@ -910,15 +933,25 @@ private fun MainChatScreen(
910933
}
911934
if (target == null) {
912935
isStreaming = false
913-
messages.add(ChatMessage(user = false, text = "Internal connection is not ready. Try again."))
936+
liveAgentEvents = (liveAgentEvents + AgentTraceEvent("error", "صفحهٔ داخلی آماده نیست؛ پیام ارسال نشد.")).takeLast(60)
937+
messages.add(ChatMessage(user = false, text = "صفحهٔ داخلی آماده نیست. یک لحظه صبر کن یا گفت‌وگوی جدید بساز و دوباره بفرست."))
914938
return
915939
}
916940
val script = "if (typeof window.CodeinNativeSend === 'function') " +
917941
"window.CodeinNativeSend(${JSONObject.quote(requestMessages.toString())}," +
918942
"${JSONObject.quote(selectedModel.id)},${JSONObject.quote("logical")}," +
919943
"${JSONObject.quote(effectiveSystemPrompt)});" +
920-
" else CodeinBridge.error('Internal bridge is not ready');"
921-
target.evaluateJavascript(script, null)
944+
" else CodeinBridge.error('codein_bridge_missing: internal bridge is not ready');"
945+
target.evaluateJavascript(script) { result ->
946+
if (result != null && result.contains("codein_bridge_missing", ignoreCase = true)) {
947+
isStreaming = false
948+
isConnected = false
949+
connectionFailed = true
950+
liveAgentEvents = (liveAgentEvents + AgentTraceEvent("error", "پل داخلی صفحه از دست رفت؛ صفحه در حال بازنشانی است.")).takeLast(60)
951+
messages.add(ChatMessage(user = false, text = "ارتباط داخلی صفحه قطع شده بود؛ صفحه بازنشانی شد. یک لحظه بعد پیام را دوباره بفرست."))
952+
webView?.reload()
953+
}
954+
}
922955
}
923956

924957
LaunchedEffect(showBrowser, isStreaming, pendingBrowserAction, pendingComposioVerification, composioOAuthLinkOpened) {
@@ -2013,9 +2046,7 @@ private fun ModelPicker(selectedModel: CodeinModel, models: List<CodeinModel>, o
20132046
overflow = TextOverflow.Clip
20142047
)
20152048
Spacer(Modifier.width(6.dp))
2016-
Box(Modifier.weight(1f, fill = false)) {
2017-
ModelSuffixText(selectedModel.suffix, Modifier.align(Alignment.CenterStart))
2018-
}
2049+
ModelSuffixText(selectedModel.suffix)
20192050
Spacer(Modifier.width(4.dp))
20202051
Text("⌄", color = TextMuted, fontSize = 16.sp, maxLines = 1, softWrap = false)
20212052
}
@@ -2039,7 +2070,7 @@ private fun ModelPicker(selectedModel: CodeinModel, models: List<CodeinModel>, o
20392070
}
20402071

20412072
@Composable
2042-
private fun ModelSuffixText(suffix: String, modifier: Modifier = Modifier) {
2073+
private fun ModelSuffixText(suffix: String) {
20432074
val alpha = remember { Animatable(1f) }
20442075
val jitter = remember { Animatable(0f) }
20452076
LaunchedEffect(Unit) {
@@ -2064,7 +2095,7 @@ private fun ModelSuffixText(suffix: String, modifier: Modifier = Modifier) {
20642095
maxLines = 1,
20652096
softWrap = false,
20662097
overflow = TextOverflow.Ellipsis,
2067-
modifier = modifier.graphicsLayer { translationX = jitter.value }
2098+
modifier = Modifier.graphicsLayer { translationX = jitter.value }
20682099
)
20692100
}
20702101

0 commit comments

Comments
 (0)