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
35 changes: 33 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
name: CI

# Build + unit-test every push and PR to the production and beta branches.
# Uses an unsigned debug build, so it needs no secrets.
# Signed with the committed pinned debug keystore (app/debug.keystore) so debug
# APKs keep a stable signature — still no secrets required.
on:
push:
branches: [main, dev]
Expand All @@ -19,5 +20,35 @@ jobs:
java-version: '21'
- uses: android-actions/setup-android@v4
- run: chmod +x ./gradlew
- name: Build & unit test (unsigned debug)
- name: Build & unit test (debug)
run: ./gradlew :app:assembleDebug :app:testDebugUnitTest --no-daemon
- name: Verify debug APK is signed with the pinned debug key
run: |
set -uo pipefail
EXPECTED="d243d7b6247feb0d119ffb1171b086c14dd21c827b42c6d1efb8275f7ad0d4e6"
APK=app/build/outputs/apk/debug/app-debug.apk
SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-/usr/local/lib/android/sdk}}"
APKSIGNER="$(ls -1 "$SDK"/build-tools/*/apksigner 2>/dev/null | sort -V | tail -n1)"
echo "apksigner: ${APKSIGNER:-<none>} ($("${APKSIGNER:-false}" --version 2>&1 || true))"
# Merge stderr: some apksigner builds log cert details there.
if ! OUT="$("$APKSIGNER" verify --print-certs "$APK" 2>&1)"; then
printf '%s\n' "$OUT"
echo "::error::apksigner verify failed for $APK"
exit 1
fi
printf '%s\n' "$OUT"
# Tolerate label casing/indentation differences across build-tools versions.
ACTUAL="$(printf '%s\n' "$OUT" | grep -i 'certificate SHA-256 digest' | head -n1 \
| sed 's/.*[Dd]igest:[[:space:]]*//' | tr -d ':\r' | tr 'A-F' 'a-f')"
echo "APK signer SHA-256: [${ACTUAL}]"
if [ "$ACTUAL" != "$EXPECTED" ]; then
echo "::error::debug APK is not signed with the pinned debug key (got '${ACTUAL:-none}', expected $EXPECTED)"
exit 1
fi
echo "OK: debug APK signed with the pinned debug key"
- name: Upload debug APK
uses: actions/upload-artifact@v4
with:
name: hermes-debug-apk
path: app/build/outputs/apk/debug/app-debug.apk
if-no-files-found: error
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ keystore.properties
keystore/
*.jks
*.keystore
# Exception: the pinned DEBUG key is committed on purpose so local and CI debug APKs
# share one signature. Debug-only, well-known password — not a release secret.
!app/debug.keystore

# Local tooling
.claude/
Expand Down
17 changes: 17 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ android {
manifestPlaceholders["appLabel"] = "Hermes"
}
signingConfigs {
// Committed on purpose, debug-only, so local and CI debug builds share one signature;
// password is the public Android debug default; never used for release/beta.
getByName("debug").apply {
storeFile = file("debug.keystore") // resolves to app/debug.keystore
storePassword = "android"
keyAlias = "androiddebugkey"
keyPassword = "android"
storeType = "PKCS12"
}
if (keystorePropsFile.exists()) {
create("release") {
storeFile = rootProject.file(keystoreProps.getProperty("storeFile"))
Expand Down Expand Up @@ -76,6 +85,14 @@ kotlin {
}
}

// CI runs `testDebugUnitTest`; without this a failing assertion only logs "AssertionError at Foo.kt:24".
tasks.withType<Test>().configureEach {
testLogging {
events("failed")
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
}
}

dependencies {
implementation(libs.core.ktx)
implementation(libs.lifecycle.runtime)
Expand Down
Binary file added app/debug.keystore
Binary file not shown.
143 changes: 143 additions & 0 deletions app/src/androidTest/java/com/hermes/client/ui/ModelSelectorUiTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package com.hermes.client.ui

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onAllNodesWithContentDescription
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onFirst
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.unit.dp
import com.hermes.client.data.network.ModelProviderDto
import com.hermes.client.data.repository.favKey
import com.hermes.client.ui.chat.ModelChip
import com.hermes.client.ui.models.ModelScope
import com.hermes.client.ui.models.ModelSelectorContent
import com.hermes.client.ui.models.modelSelectorRows
import com.hermes.client.ui.theme.HermesTheme
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test

class ModelSelectorUiTest {
@get:Rule val rule = createComposeRule()

@Test fun displays_full_long_model_names_40_to_80_chars_without_clipping() {
val model45 = "anthropic/claude-3.7-sonnet-20250219:thinking"
val model64 = "openrouter:anthropic/claude-3.7-sonnet-20250219:thinking-preview"
val model80 = "huggingface:meta-llama/Llama-3.3-70B-Instruct-Turbo-Free-FP8-Quantized-v2-202607"
val providerSlug = "openrouter-enterprise-gateway-us-east-prod"
assertTrue(model45.length in 40..80)
assertTrue(model64.length in 40..80)
assertTrue(model80.length in 40..80)

val providers = listOf(
ModelProviderDto(
slug = providerSlug,
name = providerSlug,
isCurrent = false,
models = listOf(model45, model64, model80),
),
)
val items = modelSelectorRows(
providers = providers,
favorites = emptySet(),
query = "",
currentProvider = providerSlug,
currentModel = model80,
)

rule.setContent {
HermesTheme {
Box(Modifier.width(320.dp)) {
ModelSelectorContent(
items = items,
query = "",
onQueryChange = {},
scope = ModelScope.SESSION,
onScopeChange = {},
onToggleFavorite = { _, _ -> },
onSelect = { _, _ -> },
pending = false,
error = null,
)
}
}
}

// All 40-80 char names and the current indicator must be displayed and fit within 320.dp.
listOf(model45, model64, model80).forEach { name ->
val node = rule.onNodeWithText(name)
node.assertIsDisplayed()
val bounds = node.getUnclippedBoundsInRoot()
assertTrue("Expected $name to fit inside 320.dp, got right=${bounds.right}", bounds.right <= 320.dp)
}
rule.onNodeWithText("$providerSlug · current").assertIsDisplayed()
val favButton = rule.onAllNodesWithContentDescription("Favorite").onFirst()
favButton.assertIsDisplayed()
assertTrue(favButton.getUnclippedBoundsInRoot().right <= 320.dp)
}

@Test fun displays_favorited_long_model_row_with_unfavorite_action_within_bounds() {
val model64 = "openrouter:anthropic/claude-3.7-sonnet-20250219:thinking-preview"
val providerSlug = "openrouter-enterprise-gateway-us-east-prod"
val providers = listOf(
ModelProviderDto(slug = providerSlug, name = providerSlug, models = listOf(model64)),
)
val items = modelSelectorRows(
providers = providers,
favorites = setOf(favKey(providerSlug, model64)),
query = "",
currentProvider = providerSlug,
currentModel = model64,
)

rule.setContent {
HermesTheme {
Box(Modifier.width(320.dp)) {
ModelSelectorContent(
items = items,
query = "",
onQueryChange = {},
scope = null,
onScopeChange = {},
onToggleFavorite = { _, _ -> },
onSelect = { _, _ -> },
pending = false,
error = null,
)
}
}
}

rule.onAllNodesWithText(model64).onFirst().assertIsDisplayed()
rule.onAllNodesWithText("$providerSlug · current").onFirst().assertIsDisplayed()
rule.onAllNodesWithContentDescription("Unfavorite").onFirst().assertIsDisplayed()
}

@Test fun model_chip_constrains_width_for_long_80_char_name_and_stays_clickable() {
val model80 = "huggingface:meta-llama/Llama-3.3-70B-Instruct-Turbo-Free-FP8-Quantized-v2-202607"
var clicked = false

rule.setContent {
HermesTheme {
ModelChip(
currentProvider = "openrouter",
currentModel = model80,
onClick = { clicked = true },
)
}
}

val chip = rule.onNodeWithText(model80)
chip.assertIsDisplayed()
val chipWidth = chip.getUnclippedBoundsInRoot().width
assertTrue("chip must stay bounded, got width=$chipWidth", chipWidth <= 140.dp)
chip.performClick()
assertTrue(clicked)
}
}
64 changes: 64 additions & 0 deletions app/src/main/java/com/hermes/client/data/network/Dtos.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
package com.hermes.client.data.network

import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

@Serializable data class StatusDto(val ok: Boolean = true)

Expand Down Expand Up @@ -73,6 +83,60 @@ data class ModelOptionDto(
)
@Serializable data class ModelOptionsDto(val providers: List<ModelProviderDto> = emptyList())

/**
* One model entry as the gateway publishes it: an object with a stable `id` and a human
* `label`. Older gateways sent a bare string, so the serializer accepts both shapes — a
* strict List<String> made the whole provider list fail to decode on current servers.
*/
@Serializable(with = ModelIdSerializer::class)
data class ModelIdDto(val id: String, val label: String? = null)

object ModelIdSerializer : KSerializer<ModelIdDto> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("ModelIdDto", PrimitiveKind.STRING)

override fun deserialize(decoder: Decoder): ModelIdDto {
val input = decoder as? JsonDecoder ?: return ModelIdDto(decoder.decodeString())
return when (val element = input.decodeJsonElement()) {
is JsonPrimitive -> ModelIdDto(element.content)
is JsonObject -> ModelIdDto(
id = (element["id"] as? JsonPrimitive)?.contentOrNull.orEmpty(),
label = (element["label"] as? JsonPrimitive)?.contentOrNull,
)
else -> ModelIdDto("")
}
}

override fun serialize(encoder: Encoder, value: ModelIdDto) {
// Only ever read from the API; write the id so an accidental re-encode stays valid.
encoder.encodeString(value.id)
}
}

/**
* GET /api/providers — the real catalog on current servers (replaces /api/model/options).
* `models` holds objects ({id,label}); older servers sent plain strings.
*/
@Serializable data class ProviderDto(
val id: String = "",
@SerialName("display_name") val displayName: String? = null,
@SerialName("has_key") val hasKey: Boolean = false,
val models: List<ModelIdDto> = emptyList(),
@SerialName("models_total") val modelsTotal: Int = 0,
)
@Serializable data class ProvidersDto(
val providers: List<ProviderDto> = emptyList(),
@SerialName("active_provider") val activeProvider: String? = null,
)

/** GET /api/models/live?provider=<slug> — the provider's live model entries ({id,label} objects,
* or plain strings from an older server). */
@Serializable data class LiveModelsDto(
val provider: String? = null,
val models: List<ModelIdDto> = emptyList(),
val count: Int = 0,
)

@Serializable data class SessionStatsDto(
val total: Int = 0,
@SerialName("active_store") val activeStore: Int = 0,
Expand Down
58 changes: 54 additions & 4 deletions app/src/main/java/com/hermes/client/data/network/HermesRestApi.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.hermes.client.data.network

import com.hermes.client.data.auth.GatewayConfig
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
Expand Down Expand Up @@ -102,14 +106,55 @@ class HermesRestApi(
suspend fun activeProfile(): String? =
get<ActiveProfileDto>("/api/profiles/active").let { it.current ?: it.active }

/** Live model ids for [provider] from /api/models/live. */
suspend fun liveModels(provider: String): List<String> {
val encoded = java.net.URLEncoder.encode(provider, "UTF-8")
return modelIds(get<LiveModelsDto>("/api/models/live?provider=$encoded").models)
}

/**
* Provider catalog from /api/providers enriched concurrently with /api/models/live.
*
* The live lookup is per-provider and can be slow on a cache miss, so each one is bounded:
* a provider that does not answer within [LIVE_MODELS_TIMEOUT_MS] keeps its static list
* rather than holding up the whole picker.
*/
suspend fun providers(): List<ModelProviderDto> {
val dto = get<ProvidersDto>("/api/providers")
val liveByProvider = coroutineScope {
providersNeedingLiveModels(dto.providers, dto.activeProvider)
.associateWith { id ->
// Dispatchers.IO (not the caller's dispatcher) so the budget below is real
// wall-clock time rather than a virtual-clock jump under runTest.
async(Dispatchers.IO) {
withTimeoutOrNull(LIVE_MODELS_TIMEOUT_MS) {
runCatching { liveModels(id) }
.onFailure { if (it is CancellationException) throw it }
.getOrDefault(emptyList())
}.orEmpty()
}
}
.mapValues { (_, deferred) -> deferred.await() }
}
return dto.providers.map { row ->
val base = providerToDto(row, dto.activeProvider)
val live = liveByProvider[row.id].orEmpty()
base.copy(models = mergeModels(base.models, live))
}
}

/** Raw provider list (each provider carries its model strings + an is_current flag). */
suspend fun modelProviders(): List<ModelProviderDto> =
get<ModelOptionsDto>("/api/model/options").providers
try {
providers()
} catch (e: HermesApiException) {
if (shouldFallBackToModelOptions(e.code)) get<ModelOptionsDto>("/api/model/options").providers
else throw e
}

/** Flattened list of (provider, model) options derived from [modelProviders]. */
suspend fun modelOptions(): List<ModelOptionDto> =
get<ModelOptionsDto>("/api/model/options").providers.flatMap { p ->
p.models.map { m -> ModelOptionDto(provider = p.slug, model = m, label = m) }
}
modelProviders().flatMap { p -> p.models.map { m -> ModelOptionDto(provider = p.slug, model = m, label = m) } }

suspend fun setModel(provider: String, model: String) = withContext(Dispatchers.IO) {
val obj: JsonObject = buildJsonObject {
Expand Down Expand Up @@ -360,4 +405,9 @@ class HermesRestApi(
if (!resp.isSuccessful) throw HermesApiException(resp.code, "set active profile failed")
}
}

private companion object {
/** Per-provider budget for the live model lookup; static models are the fallback. */
const val LIVE_MODELS_TIMEOUT_MS = 8_000L
}
}
Loading
Loading