Files
aiturk-mobil/app/build.gradle.kts
T
M57andHy4ri 59bcbdfe3c build: Android 17 (API 37) + okhttp 5.5.0 + LAN local-network permission gate (#941)
* build: compileSdk 36 -> 37 + okhttp 5.4.0 -> 5.5.0

Take okhttp 5.5.0 (folds in dependabot PR #940) which hard-requires
compileSdk 37 via AAR metadata. targetSdk stays 36 for now.

* build: targetSdk 36 -> 37 (Android 17) + ACCESS_LOCAL_NETWORK gating

Opt into Android 17 runtime behavior. The app connects to a gateway
(default 127.0.0.1:9119, plus LAN + remote), so targeting 37 forces the
new ACCESS_LOCAL_NETWORK permission for LAN hosts.

- AndroidManifest: declare ACCESS_LOCAL_NETWORK (harmless below API 37)
- LocalNetwork.kt: pure detector + needsLocalNetworkPermission(baseUrl)
  (loopback + public remote exempt; RFC1918/link-local/CGNAT gated)
- ConnectViewModel: requestConnect() gates on the permission; screen
  launches the prompt; onLanPermissionResult proceeds or shows a clear error
- flake.nix: android platform 36 -> 37
- Tests: LocalNetworkTest + ConnectPermissionGateTest (SDK_INT / permission
  branching mocked, no device needed)
- Task 8 finding: assistant services (VoiceInteraction*/Recognition) and the
  remoteMessaging ChatNotificationService do NOT hit the Android 17 mic/
  while-in-use foreground hardening, so no change required.

* fix: ktlint + @Composable LocalContext hoist (was blocking CI)

- ConnectScreen: hoist LocalContext.current out of onClick lambda
  (calling a @Composable inside a non-composable lambda broke compileDebugKotlin)
- ktlint --format: multiline-expression-wrapping, function-signature,
  no-empty-first-line-in-class-body, no-unused-imports
- LocalNetwork.kt: merge consecutive KDocs (no-consecutive-comments)

flake.nix buildToolsVersion/platformToolsVersion intentionally stay 36.0.0
— they are decoupled from compileSdk; only platformVersions needs 37.

* fix: suspend mock (coEvery) + flake toolchain pinned to 37.0.0

- ConnectPermissionGateTest: getStatus() is suspend → use coEvery (was
  breaking compileDebugUnitTestKotlin)
- flake.nix: buildToolsVersion/platformToolsVersion/cmdLineToolsVersion
  pinned to 37.0.0 (verified against pinned nixpkgs 241313f — resolves to
  android-sdk-*-37.0.0 derivations; platformVersions already 37)

* fix(flake): revert cmdLineToolsVersion to 11.0 (not API-aligned)

cmdline-tools uses its own versioning (latest = 21.0, never 37.0.0) —
nixpkgs rejects 37.0.0 with 'version missing'. build-tools + platform-tools
stay 37.0.0 (verified resolve to android-sdk-*-37.0.0). flake now evals
clean against pinned nixpkgs 241313f.

* flake: track nixos-unstable + pin toolchain to latest (cmdline 22.0, platform-tools 37.0.1, build-tools 37.0.0, platform 37.1)

- inputs.nixpkgs -> nixos-unstable, flake.lock bumped to rev ffb3c9b7 (2026-08-19)
- cmdLineToolsVersion 11.0 -> 22.0 (own versioning, not API-aligned; v22_0 confirms)
- platformToolsVersion 37.0.0 -> 37.0.1
- buildToolsVersion stays 37.0.0
- platformVersions 37 -> 37.1
- verified: nix flake check --no-build -> all checks passed on hyari

* fix: unit tests — Uri stub + Build.SDK_INT final-field mock

- LocalNetwork.kt: needsLocalNetworkPermission uses java.net.URI instead of
  android.net.Uri (latter is a non-functional stub in JVM unit tests, its host
  returns null -> gate always false). Added pure requiresLocalNetworkPermission(sdkInt, baseUrl).
- ConnectViewModel: inject sdkVersion (package-private) instead of reading the
  final static Build.VERSION.SDK_INT directly; gate via requiresLocalNetworkPermission.
- ConnectPermissionGateTest: drop mockkStatic(Build.VERSION) (MockKException on
  final static field, and against repo convention); inject sdkVersion; add pure
  gate-decision matrix. Fixes 7 red tests.

* fix(test): remove illegal ':' from test function names (compile error)

* fix(test): order getString mocks so specific resources win over wildcard

* fix(flake): include android-37.0 system image so the emulator can boot

Google only publishes the android-37.0 system image (no 37.1 image exists
yet). With platformVersions=["37.1"] composeAndroidPackages found no matching
system image, leaving system-images/ empty and every AVD FATALing with
'Broken AVD system path'. Adding 37.0 pulls the published image so an AVD boots
(verified: hermes37 AVD boots Android 17 / API 37 on hyari). compileSdk/targetSdk
stay 37.

Also bump AGENTS.md SDK note 36 -> 37 (was stale).

* fix(flake): platformVersions 37.1 -> 37.0

Drop 37.1; 37.0 provides both the SDK platform for compileSdk 37 and the
published android-37.0 system image the emulator needs.

* fix(flake): remove stray tool-scratch line leaked into flake.nix (line 116)

A terminal tool's /tmp scratch rename line got appended to flake.nix, making
it invalid Nix. Removed; flake now parses + 'nix flake check' passes on hyari.

* fix(build): pin buildToolsVersion 37.0.0 to match nix SDK

AGP defaulted build-tools to 36.0.0, which isn't in the nix-managed SDK
(only 37.0.0 is provisioned). Local ./gradlew builds then tried to *install*
36.0.0 into the immutable /nix/store and failed. Pin 37.0.0 so the local
nix devShell builds. CI uses its own SDK so unaffected.

---------

Co-authored-by: Hy4ri <Hy4ri@users.noreply.github.com>
2026-08-20 14:35:42 +03:00

297 lines
11 KiB
Kotlin

import org.gradle.api.tasks.testing.Test
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.room)
alias(libs.plugins.ksp)
}
android {
namespace = "com.m57.hermescontrol"
lint {
disable += "MissingTranslation"
}
compileSdk = 37
buildToolsVersion = "37.0.0"
defaultConfig {
applicationId = "com.m57.hermescontrol"
minSdk = 26
targetSdk = 37
// Version overrides passed from CI via -PversionName / -PversionCode
// Falls back to defaults for local development.
versionCode = (project.findProperty("versionCode") as? String)?.toIntOrNull() ?: 1
versionName = (project.findProperty("versionName") as? String) ?: "1.0-dev"
// Embed git commit SHA for the About card in Settings
val gitSha =
providers.exec {
commandLine("git", "rev-parse", "--short", "HEAD")
}.standardOutput.asText.get().trim()
buildConfigField("String", "GIT_SHA", "\"$gitSha\"")
}
signingConfigs {
create("release") {
val isReleaseBuild =
gradle.startParameter.taskNames.any { name ->
name.contains("Release", ignoreCase = true) || name == "build"
}
if (isReleaseBuild) {
val storePath = System.getenv("KEYSTORE_PATH")
val storePass = System.getenv("KEYSTORE_PASSWORD")
val alias = System.getenv("KEY_ALIAS")
val keyPass = System.getenv("KEY_PASSWORD")
if (storePath != null && storePass != null && alias != null && keyPass != null) {
storeFile = file(storePath)
storePassword = storePass
keyAlias = alias
keyPassword = keyPass
} else {
// Env vars missing — signing deferred to release workflow.
// Don't hard-require(): that would break compileReleaseKotlin
// in CI where keystore secrets aren't set.
logger.warn("Release signing config missing env vars — signing deferred to release workflow")
storeFile = file("dummy.keystore")
storePassword = "dummy"
keyAlias = "dummy"
keyPassword = "dummy"
}
} else {
// Dummy values for evaluation configuration during non-release builds
storeFile = file("dummy.keystore")
storePassword = "dummy"
keyAlias = "dummy"
keyPassword = "dummy"
}
}
}
buildTypes {
debug {
buildConfigField("boolean", "ALLOW_CLEARTEXT", "true")
manifestPlaceholders["usesCleartextTraffic"] = "true"
}
release {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
signingConfig = signingConfigs["release"]
buildConfigField("boolean", "ALLOW_CLEARTEXT", "true")
manifestPlaceholders["usesCleartextTraffic"] = "true"
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
buildFeatures {
compose = true
aidl = false
buildConfig = true
shaders = false
}
dependenciesInfo {
includeInApk = false
}
packaging {
resources {
pickFirsts += "META-INF/AL2.0"
pickFirsts += "META-INF/LGPL2.1"
pickFirsts += "META-INF/LICENSE"
pickFirsts += "META-INF/LICENSE.md"
pickFirsts += "META-INF/LICENSE-notice.md"
pickFirsts += "META-INF/NOTICE"
pickFirsts += "META-INF/NOTICE.md"
}
}
}
// Overwrite version-control-info with empty content for reproducible builds
// F-Droid CI uses detached HEAD (branches: []) while GitHub CI uses main
// (branches: ["main"]) — this field in the generated textproto causes a
// byte-level APK difference. Emptying the file makes both CI environments
// produce identical artifacts.
tasks.matching { it.name.endsWith("VersionControlInfo") }.configureEach {
doLast {
outputs.files.filter { it.exists() }.forEach { it.writeText("") }
}
}
kotlin {
jvmToolchain(21)
}
room {
schemaDirectory("$projectDir/schemas")
}
dependencies {
val composeBom = platform(libs.androidx.compose.bom)
implementation(composeBom)
androidTestImplementation(composeBom)
// Core Android dependencies
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.browser)
// Arch Components
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.viewmodel.compose)
// Compose
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons.extended)
// Tooling
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.leakcanary.android)
// Instrumented tests
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
debugImplementation(libs.androidx.compose.ui.test.manifest)
// Networking
implementation(libs.okhttp)
implementation(libs.okhttp.logging)
implementation(libs.retrofit)
implementation(libs.retrofit.converter.kotlinx.serialization)
implementation(libs.kotlinx.serialization.json)
// Native Compose LaTeX rendering
implementation(libs.latex.base)
implementation(libs.latex.parser)
implementation(libs.latex.renderer)
// Image loading
implementation(libs.coil.compose)
implementation(libs.coil.gif)
// Encrypted storage
implementation(libs.androidx.security.crypto)
implementation(libs.androidx.datastore)
implementation("androidx.startup:startup-runtime:1.1.1")
// Local database (Room) — message persistence
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
implementation(libs.sqlcipher)
ksp(libs.androidx.room.compiler)
// Local tests: jUnit, coroutines, Android runner
testImplementation(libs.junit)
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
testRuntimeOnly(libs.junit.vintage.engine)
testRuntimeOnly(libs.junit.platform.launcher)
testImplementation(libs.okhttp.mockwebserver)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.mockk)
testImplementation(libs.turbine)
// Instrumented tests: jUnit rules and runners
androidTestImplementation(libs.androidx.test.core)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.androidx.test.espresso.core)
androidTestImplementation(libs.mockk.android)
// Navigation
implementation(libs.androidx.navigation3.ui)
implementation(libs.androidx.navigation3.runtime)
implementation(libs.androidx.lifecycle.viewmodel.navigation3)
}
tasks.register<Exec>("ktlintCheck") {
group = "verification"
description = "Runs ktlint check."
workingDir = rootProject.projectDir
commandLine("sh", "-c", "ktlint \"app/src/**/*.kt\"")
}
tasks.register<Exec>("ktlintFormat") {
group = "formatting"
description = "Runs ktlint format."
workingDir = rootProject.projectDir
commandLine("sh", "-c", "ktlint -F \"app/src/**/*.kt\"")
}
// ── Hardcoded Color Guard (issue #622) ────────────────────────────────────
//
// Fails the build if a hardcoded Color literal (Color(0x...) or named
// Color.White/Black/Red/Green/Gray/etc.) is introduced outside the theme
// module, *Preview.kt files, and _test sources. Pairing/Auth screens are
// exempt via the per-path overlay list below.
//
// Acceptable replacements (see docs/color-hardcoded-audit.md):
// - MaterialTheme.colorScheme.<token>
// - LocalHermesStatusColors.current.<semantic>
// - Color.Transparent / Color.Unspecified (intentional)
// Resolve paths at configuration time (config-cache compatible).
val colorGuardSrcDir = layout.projectDirectory
.dir("src/main/java/com/m57/hermescontrol")
val colorGuardExemptions = listOf(
"/theme/",
"PairingScreen.kt",
"AuthLoginScreen.kt",
"Preview.kt",
)
val colorGuardHexPattern = Regex("""Color\(\s*0x[0-9A-Fa-f]{6,8}\s*\)""")
val colorGuardNamedPattern = Regex("""Color\.(White|Black|Red|Green|Gray|LightGray|DarkGray|Yellow|Blue|Cyan|Magenta)\b""")
tasks.register("checkColorLiterals") {
group = "verification"
description = "Fails if hardcoded Color(...) literals appear outside theme/, *Preview.kt, and _test."
val srcDir = colorGuardSrcDir
val exemptions = colorGuardExemptions
val hexPattern = colorGuardHexPattern
val namedPattern = colorGuardNamedPattern
doLast {
val offenders = mutableListOf<Pair<String, Int>>()
srcDir.asFile.walkTopDown().filter { it.isFile && it.extension == "kt" }.forEach { file ->
if (exemptions.any { file.absolutePath.contains(it) }) return@forEach
file.useLines { lines ->
lines.forEachIndexed { idx, raw ->
val line = raw.trim()
if (line.startsWith("import ")) return@forEachIndexed
if (line.startsWith("//") || line.startsWith("*")) return@forEachIndexed
if (hexPattern.containsMatchIn(line) || namedPattern.containsMatchIn(line)) {
offenders.add(file.absolutePath to (idx + 1))
}
}
}
}
if (offenders.isNotEmpty()) {
val report = offenders.joinToString("\n") { (path, line) ->
" - $path:$line"
}
throw GradleException(
"Hardcoded Color literals found outside theme/ + *Preview.kt + _test:\n$report\n\n" +
"Replace with MaterialTheme.colorScheme.<token>, " +
"LocalHermesStatusColors.current.<semantic>, or " +
"Color.Transparent / Color.Unspecified (intentional).\n" +
"See docs/color-hardcoded-audit.md.",
)
}
logger.lifecycle("checkColorLiterals: no hardcoded Color literals found. ✅")
}
}
tasks.named("check") {
dependsOn("checkColorLiterals")
}
tasks.withType<Test> {
useJUnitPlatform()
}