Skip to content
Merged
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
8 changes: 4 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Set up JDK 21
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
java-version: '21'
distribution: 'temurin'
Expand Down Expand Up @@ -175,7 +175,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Set up JDK 21
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
java-version: '21'
distribution: 'temurin'
Expand Down Expand Up @@ -227,7 +227,7 @@ jobs:
ref: ${{ needs.version.outputs.tag }}

- name: Set up JDK 21
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
java-version: '21'
distribution: 'temurin'
Expand Down Expand Up @@ -475,7 +475,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Set up JDK 21
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
java-version: '21'
distribution: 'temurin'
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/preview-comment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:
steps:
- name: Resolve PR number and artifact
id: resolve
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
// Resolve workflow run (either the triggering run or a manual run_id)
Expand Down Expand Up @@ -207,7 +207,7 @@ jobs:

- name: Create or update comment (idempotent)
if: steps.resolve.outputs.pr != ''
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const pr = parseInt('${{ steps.resolve.outputs.pr }}', 10);
Expand Down
2 changes: 1 addition & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ dependencies {
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
implementation("androidx.activity:activity-compose:1.13.0")
implementation(platform("androidx.compose:compose-bom:2026.06.01"))
implementation(platform("androidx.compose:compose-bom:2026.08.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.material3:material3")
Expand Down
107 changes: 107 additions & 0 deletions app/src/main/java/com/musheer360/swiftslate/api/GeminiClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,56 @@ import java.net.ConnectException
import java.net.HttpURLConnection
import java.net.SocketTimeoutException
import java.net.URL
import java.net.URLEncoder
import java.net.UnknownHostException

class GeminiClient {

companion object {
private val HTTP_PREFIX_REGEX = Regex("^HTTP_\\d+:\\s*")
private const val MODELS_URL = "https://generativelanguage.googleapis.com/v1beta/models"
// The listing paginates; pageSize caps at 1000. Three pages is far beyond any
// realistic catalog — a bound so a hostile/broken nextPageToken loop cannot spin.
private const val MAX_LIST_PAGES = 3

/**
* Extracts chat-capable model ids from a v1beta/models response page. An entry
* is kept when either documented capability array names "generateContent";
* entries carrying neither array are kept (fail-open: a renamed field must not
* empty the whole dropdown). The leading "models/" path prefix is stripped;
* ids are de-duplicated in first-seen order; non-JSON bodies yield an empty list.
*
* Exposed for unit tests — the network path around it is not JVM-testable.
*/
internal fun parseModelsJson(json: String): List<String> {
if (json.isBlank()) return emptyList()
return try {
val arr = JSONObject(json).optJSONArray("models") ?: return emptyList()
val out = LinkedHashSet<String>()
for (i in 0 until arr.length()) {
val obj = arr.optJSONObject(i) ?: continue
val methods = obj.optJSONArray("supportedGenerationMethods")
val actions = obj.optJSONArray("supportedActions")
if (methods != null || actions != null) {
val supportsChat = arrayContains(methods, "generateContent") ||
arrayContains(actions, "generateContent")
if (!supportsChat) continue
}
obj.optString("name").trim()
.takeIf { it.isNotBlank() }
?.let { out.add(it.removePrefix("models/")) }
}
out.toList()
} catch (_: Exception) {
emptyList()
}
}

private fun arrayContains(arr: JSONArray?, value: String): Boolean {
if (arr == null) return false
for (i in 0 until arr.length()) if (arr.optString(i) == value) return true
return false
}
}

suspend fun validateKey(apiKey: String): Result<String> = withContext(Dispatchers.IO) {
Expand Down Expand Up @@ -56,6 +100,69 @@ class GeminiClient {
}
}

/**
* Lists the chat-capable models available to [apiKey] via GET v1beta/models,
* powering the Settings screen's dynamic model dropdown (issue #148). Follows
* nextPageToken for up to [MAX_LIST_PAGES] pages; non-chat entries are dropped
* by [parseModelsJson]. Error mapping mirrors [validateKey].
*/
suspend fun fetchModels(apiKey: String): Result<List<String>> = withContext(Dispatchers.IO) {
val collected = LinkedHashSet<String>()
var pageToken: String? = null
try {
var pages = 0
while (true) {
// Opaque tokens may contain '+', '/' or '=' — raw interpolation corrupts
// the query string ('+' decodes to a space server-side), so encode it.
val pageSuffix = if (pageToken.isNullOrEmpty()) ""
else "&pageToken=" + URLEncoder.encode(pageToken, "UTF-8")
var connection: HttpURLConnection? = null
val responseCode: Int
val body: String
try {
connection = URL("$MODELS_URL?pageSize=1000$pageSuffix")
.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("x-goog-api-key", apiKey)
connection.connectTimeout = 15_000
connection.readTimeout = 15_000

responseCode = connection.responseCode
body = if (responseCode in 200..299) {
ApiClientUtils.readResponseBounded(connection)
} else {
ApiClientUtils.readErrorBody(connection)
}
} finally {
connection?.disconnect()
}

if (responseCode !in 200..299) {
val apiMessage = ApiClientUtils.extractApiErrorMessage(body)
return@withContext when (responseCode) {
429 -> Result.failure(Exception("Rate limited. Please try again later."))
400, 403 -> Result.failure(Exception(
apiMessage.ifEmpty { "Invalid API key" }))
else -> Result.failure(Exception(
"Error $responseCode: ${apiMessage.ifEmpty { "Unexpected error" }}"))
}
}

collected.addAll(parseModelsJson(body))
pages++
pageToken = try {
JSONObject(body).optString("nextPageToken", "")
} catch (_: Exception) {
""
}
if (pageToken.isNullOrEmpty() || pages >= MAX_LIST_PAGES) break
}
Result.success(collected.toList())
} catch (e: Exception) {
Result.failure(e)
}
}

suspend fun generate(
prompt: String,
text: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ class CommandManager(context: Context) {
"copy" to "Copy the text to clipboard.",
"cut" to "Cut the text to clipboard.",
"paste" to "Paste from clipboard.",
"replace" to "Replace text with clipboard content."
"replace" to "Replace text with clipboard content.",
"translate:xx" to "Translate text to any language code (e.g. ?translate:es, ?translate:fr)."
)

// Default AI commands — seeded into custom commands on first run so users can edit/delete them
Expand Down Expand Up @@ -311,6 +312,7 @@ class CommandManager(context: Context) {
fun findCommand(text: String): Command? {
val commands = getCommands()
for (cmd in commands) { // Already sorted by trigger length in getCommands()
if (cmd.trigger.endsWith("translate:xx")) continue
if (text.endsWith(cmd.trigger)) {
return cmd
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.musheer360.swiftslate.manager

import com.musheer360.swiftslate.model.ProviderType

/**
* Process-lifetime cache of the model lists fetched from the Gemini and Groq
* /models endpoints for the dynamic Settings dropdowns (issue #148).
*
* Session-only by design — never written to prefs — so a stale provider catalog
* can never outlive this app process, matching how the Custom provider keeps its
* fetched list in composition state. [Entry.attempted] records whether a real
* fetch already ran this session (success or failure), so entering Settings
* again never auto-refires it; only lack of an API key leaves [attempted] false,
* letting the automatic fetch run once a key is added.
*/
object ProviderModelsCache {
data class Entry(val models: List<String>, val attempted: Boolean)

@Volatile private var gemini: Entry? = null
@Volatile private var groq: Entry? = null

fun get(type: String): Entry? = when (type) {
ProviderType.GEMINI -> gemini
ProviderType.GROQ -> groq
else -> null
}

fun put(type: String, entry: Entry) {
when (type) {
ProviderType.GEMINI -> gemini = entry
ProviderType.GROQ -> groq = entry
}
}
}
32 changes: 22 additions & 10 deletions app/src/main/java/com/musheer360/swiftslate/model/GeminiModels.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package com.musheer360.swiftslate.model

/**
* Catalog of the Gemini models SwiftSlate offers and how each is tuned. Mirrors
* [GroqModels]: each model is defined once in [SPECS] together with its thinking
* level, and the dropdown list, default, validation, and per-model thinking
* level all derive from that single table.
* Catalog of the Gemini models SwiftSlate curates and how each is tuned. Mirrors
* [GroqModels]: each curated model is defined once in [SPECS] together with its
* thinking level, and the default, display labels, and per-model thinking level
* all derive from that single table. Since issue #148 the Settings dropdown no
* longer renders from this table — it lists whatever the provider's /models
* endpoint returns (see [ProviderModelsCache]); SPECS remains the source for
* defaults, friendly names, and thinking levels.
*
* Thinking control on Gemini 3.x is via generationConfig.thinkingConfig.thinkingLevel
* (a string enum), kept per model here (spec-driven) rather than hardcoded in the
Expand Down Expand Up @@ -36,18 +39,27 @@ object GeminiModels {
/** Model IDs, in display order (used for validation and by the provider config). */
val ALL: List<String> = SPECS.map { it.id }

/** (id, label) pairs for the Settings dropdown — shows a friendly name, stores the id. */
val OPTIONS: List<Pair<String, String>> = SPECS.map { it.id to it.label }
/**
* Ids that Google has withdrawn and must migrate to [DEFAULT] rather than pass
* through — requests with them fail for (at least) newer accounts, so keeping
* one selected would break every command (issue #113 precedent). Unknown ids
* that are NOT listed here belong to models fetched dynamically off the live
* /models endpoint (issue #148) and are kept verbatim.
*/
private val RETIRED_IDS: Set<String> = setOf("gemini-2.5-flash-lite")

/** Friendly display label for [model]; falls back to the id if unknown. */
fun label(model: String): String = SPECS.firstOrNull { it.id == model }?.label ?: model

/**
* Coerce a stored/selected model to a currently-supported one. This migrates
* users off retired ids (e.g. gemini-2.5-flash-lite, which is no longer
* available to new users) to [DEFAULT].
* Normalize a stored/selected model value. Dynamic selection (issue #148) means
* any id the API accepts may be stored, so unknown ids pass through trimmed;
* only blank values and known-retired ids coerce to [DEFAULT].
*/
fun sanitize(value: String?): String = if (value in ALL) value!! else DEFAULT
fun sanitize(value: String?): String {
val trimmed = value?.trim().orEmpty()
return if (trimmed.isEmpty() || trimmed in RETIRED_IDS) DEFAULT else trimmed
}

/**
* Thinking level to request for [model] via generationConfig.thinkingConfig,
Expand Down
50 changes: 40 additions & 10 deletions app/src/main/java/com/musheer360/swiftslate/model/GroqModels.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package com.musheer360.swiftslate.model

/**
* Single source of truth for the Groq models SwiftSlate offers and how each one
* Single source of truth for the Groq models SwiftSlate curates and how each one
* is driven with respect to reasoning ("thinking").
*
* Each offered model is defined once in [SPECS] together with the reasoning
* parameters it needs. The dropdown list, the default, validation, and the
* per-model reasoning params all derive from that single table, so adding or
* removing a model is a one-line change that forces you to state its reasoning
* behavior right there.
* Each curated model is defined once in [SPECS] together with the reasoning
* parameters it needs. The default, display labels, and the per-model reasoning
* params all derive from that single table, so adding or removing a model is a
* one-line change that forces you to state its reasoning behavior right there.
* Since issue #148 the Settings dropdown no longer renders from this table — it
* lists whatever Groq's /models endpoint returns (see [ProviderModelsCache]);
* SPECS remains the source for defaults, friendly names, and reasoning params.
* Off-catalog models picked from that dynamic list send no reasoning params
* ([reasoningParams] returns empty for unknown ids), which every model accepts.
*
* Reasoning support on Groq is per-model and strictly validated by the API:
* sending an unsupported reasoning parameter (or an unsupported value) returns
Expand Down Expand Up @@ -60,14 +64,40 @@ object GroqModels {
/** Model IDs, in display order (used for validation and by the provider config). */
val ALL: List<String> = SPECS.map { it.id }

/** (id, label) pairs for the Settings dropdown — shows a friendly name, stores the id. */
val OPTIONS: List<Pair<String, String>> = SPECS.map { it.id to it.label }
/**
* Ids Groq has decommissioned; they must migrate to [DEFAULT] rather than pass
* through, because requests with them always fail. Unknown ids NOT listed here
* come from the dynamic /models list (issue #148) and are kept verbatim.
*/
private val RETIRED_IDS: Set<String> = setOf(
"llama-3.3-70b-versatile",
"llama-4-scout",
"meta-llama/llama-4-scout-17b-16e-instruct"
)

/**
* Groq's /models endpoint also serves entries that cannot run text-transforming
* chat completions: Whisper transcription, PlayAI TTS, and Llama Guard safety
* classifiers. Conservative substring exclusions, verified against the live
* catalog; anything unrecognized stays listed (fail-open).
*/
private val NON_CHAT_SUBSTRINGS = listOf("whisper", "-tts", "guard", "playai")

fun isChatCandidate(id: String): Boolean =
NON_CHAT_SUBSTRINGS.none { id.contains(it, ignoreCase = true) }

/** Friendly display label for [model]; falls back to the id if unknown. */
fun label(model: String): String = SPECS.firstOrNull { it.id == model }?.label ?: model

/** Coerce a stored/selected model to a currently-supported one. */
fun sanitize(value: String?): String = if (value in ALL) value!! else DEFAULT
/**
* Normalize a stored/selected model value. Dynamic selection (issue #148) means
* any id the API accepts may be stored, so unknown ids pass through trimmed;
* only blank values and known-retired ids coerce to [DEFAULT].
*/
fun sanitize(value: String?): String {
val trimmed = value?.trim().orEmpty()
return if (trimmed.isEmpty() || trimmed in RETIRED_IDS) DEFAULT else trimmed
}

/**
* Reasoning parameters to merge into a Groq chat-completions request body for
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ fun CommandsScreen(commandManager: CommandManager) {
var commands by remember { mutableStateOf(commandManager.getCommands()) }
val displayCommands = remember(commands) {
val (builtIn, custom) = commands.partition { it.isBuiltIn }
builtIn + custom
val (translateCmd, otherBuiltIns) = builtIn.partition { it.trigger.endsWith("translate:xx") }
otherBuiltIns + translateCmd + custom
}
var trigger by rememberSaveable { mutableStateOf("") }
var prompt by rememberSaveable { mutableStateOf("") }
Expand Down
Loading
Loading