diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/AiStableDiffusionClientApp.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/AiStableDiffusionClientApp.kt index 5a6d6ae1f..c1adabf41 100755 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/AiStableDiffusionClientApp.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/AiStableDiffusionClientApp.kt @@ -5,6 +5,7 @@ import android.app.Application import android.app.ActivityManager import android.os.Build import android.os.Process +import com.shifthackz.aisdv1.app.inference.AndroidCurrentProcessPerformanceReader import com.shifthackz.aisdv1.app.inference.InferenceServiceDependencies import android.database.CursorWindow import android.os.StrictMode @@ -56,6 +57,7 @@ class AiStableDiffusionClientApp : Application() { Timber.plant(Timber.DebugTree()) } inferenceDependencies = InferenceServiceDependencies( + performanceReader = AndroidCurrentProcessPerformanceReader(), engines = createNativeInferenceEngineFactory(this, BuildConfig.BUILD_TYPE == "dev"), files = FileGenerationFileStore(this, CompletePngImageValidator()), ) diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidCurrentProcessPerformanceReader.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidCurrentProcessPerformanceReader.kt new file mode 100644 index 000000000..7b3a1c590 --- /dev/null +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidCurrentProcessPerformanceReader.kt @@ -0,0 +1,24 @@ +package com.shifthackz.aisdv1.app.inference + +import android.os.Process +import android.os.Debug +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading + +/** + * Reads the current process's proportional resident memory through the public Android API. + * Shared pages are apportioned so summing host and worker readings avoids counting them twice. + * @author Dmitriy Moroz + */ +internal class AndroidCurrentProcessPerformanceReader : CurrentProcessPerformanceReader { + override fun read(): ProcessPerformanceReading { + val memory = Debug.MemoryInfo() + Debug.getMemoryInfo(memory) + val residentKilobytes = memory.dalvikPss.toLong() + memory.nativePss + memory.otherPss + check(residentKilobytes > 0) + return ProcessPerformanceReading( + identity = "${Process.myPid()}:${Process.getStartElapsedRealtime()}", + cpuTimeNanos = Process.getElapsedCpuTime() * 1_000_000L, + residentBytes = residentKilobytes * 1024L, + ) + } +} diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidInferenceConnection.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidInferenceConnection.kt index d803336de..b59626921 100644 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidInferenceConnection.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/AndroidInferenceConnection.kt @@ -12,6 +12,7 @@ import android.os.Message import android.os.Messenger import android.os.Process import android.os.SystemClock +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.LocalDiffusionStatus import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine import com.shifthackz.aisdv1.domain.entity.NativeGenerationStage @@ -28,6 +29,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull /** @@ -42,11 +45,16 @@ internal class AndroidInferenceConnection(private val context: Context) : Infere private val ready = CompletableDeferred() private val identityReady = CompletableDeferred() private val result = CompletableDeferred() + private val performanceMutex = Mutex() + private var resourceRequestId = 0L + private var pendingPerformance: CompletableDeferred? = null private val dead = CompletableDeferred() private val reply = Messenger(Handler(Looper.getMainLooper(), ::onMessage)) private var remote: Messenger? = null private var binder: IBinder? = null private var incarnation = "" + + @Volatile private var pid = -1 private var sequence = -1L private var job = "" @@ -156,6 +164,27 @@ internal class AndroidInferenceConnection(private val context: Context) : Infere result.await() } + /** + * Serializes on-demand resource requests on the control dispatcher. A short read deadline affects + * only the overlay; it never interrupts native generation or its heartbeat. + * @author Dmitriy Moroz + */ + override suspend fun readPerformance(): ProcessPerformanceReading? = performanceMutex.withLock { + withContext(Dispatchers.Main.immediate) { + if (!hasSubmitted || result.isCompleted) return@withContext null + val response = CompletableDeferred() + pendingPerformance = response + resourceRequestId++ + try { + send(InferenceProtocol.READ_PERFORMANCE) + withTimeoutOrNull(2_000) { response.await() } + ?: error("Inference resource reading timed out") + } finally { + pendingPerformance = null + } + } + } + private fun onMessage(message: Message): Boolean { val data = message.data if (message.sendingUid != Process.myUid() || data.getInt(InferenceProtocol.VERSION_KEY) != InferenceProtocol.VERSION) return true @@ -178,6 +207,23 @@ internal class AndroidInferenceConnection(private val context: Context) : Infere } if (data.getString(InferenceProtocol.JOB) != job || data.getString(InferenceProtocol.ENGINE_KEY) != expectedEngine?.name) return true when (message.what) { + InferenceProtocol.PERFORMANCE -> { + if (data.getLong(InferenceProtocol.RESOURCE_REQUEST_ID) != resourceRequestId) return true + val cpu = data.getLong(InferenceProtocol.CPU_NANOS, -1) + val rss = data.getLong(InferenceProtocol.RESIDENT_BYTES, -1) + if (cpu >= 0 && rss >= 0) { + pendingPerformance?.complete( + ProcessPerformanceReading( + "$pid:$incarnation", + cpu, + rss + ) + ) + } else { + pendingPerformance?.completeExceptionally(IllegalStateException("Inference resource reading failed")) + } + } + InferenceProtocol.STAGE -> if (!result.isCompleted) { runCatching { NativeGenerationStage.valueOf( @@ -208,6 +254,10 @@ internal class AndroidInferenceConnection(private val context: Context) : Infere private fun send(what: Int) { try { remote?.send(InferenceProtocol.message(what, incarnation, job, replyTo = reply).apply { + if (what == InferenceProtocol.READ_PERFORMANCE) data.putLong( + InferenceProtocol.RESOURCE_REQUEST_ID, + resourceRequestId + ) if (what == InferenceProtocol.SUBMIT) data.putString( InferenceProtocol.ENGINE_KEY, expectedEngine?.name @@ -219,6 +269,7 @@ internal class AndroidInferenceConnection(private val context: Context) : Infere } private fun processDied() { + pendingPerformance?.completeExceptionally(IllegalStateException("Inference process exited")) dead.complete(Unit) fail(NativeGenerationFailure.Category.PROCESS_DIED) } diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/CurrentProcessPerformanceReader.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/CurrentProcessPerformanceReader.kt new file mode 100644 index 000000000..c8eb49dfd --- /dev/null +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/CurrentProcessPerformanceReader.kt @@ -0,0 +1,13 @@ +package com.shifthackz.aisdv1.app.inference + +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading + +/** Reads native-worker counters from inside that worker's sandbox. @author Dmitriy Moroz */ +internal interface CurrentProcessPerformanceReader { + /** + * Reads CPU and resident memory without retaining a sampler; invoke off the control thread. + * File and platform failures propagate to the requesting host as an unavailable reading. + * @author Dmitriy Moroz + */ + fun read(): ProcessPerformanceReading +} diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceConnection.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceConnection.kt index 029237c7c..c0611d276 100644 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceConnection.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceConnection.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.app.inference +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.LocalDiffusionStatus import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine import com.shifthackz.aisdv1.domain.entity.NativeGenerationStage @@ -17,6 +18,13 @@ internal interface InferenceConnection { */ val processId: Int? + /** + * Reads child-owned counters on demand. Returns null before submission or after completion; + * timeout, child death and malformed responses fail this read without cancelling inference. + * @author Dmitriy Moroz + */ + suspend fun readPerformance(): ProcessPerformanceReading? + /** * Binds and validates one child incarnation, persists its identity, then awaits this job completion. * Delivers only matching job events; binding, protocol or child-exit failures propagate to the host. diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceProtocol.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceProtocol.kt index db66f6905..102c4b7a1 100644 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceProtocol.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceProtocol.kt @@ -10,7 +10,7 @@ import android.os.Messenger * @author Dmitriy Moroz */ internal object InferenceProtocol { - const val VERSION = 1 + const val VERSION = 2 const val HELLO = 1 const val READY = 2 const val SUBMIT = 3 @@ -21,6 +21,11 @@ internal object InferenceProtocol { const val PING = 8 const val PONG = 9 const val EXIT = 10 + const val RESOURCE_REQUEST_ID = "resource_request_id" + const val READ_PERFORMANCE = 12 + const val PERFORMANCE = 13 + const val CPU_NANOS = "cpu_nanos" + const val RESIDENT_BYTES = "resident_bytes" const val STAGE = 11 const val STAGE_KEY = "stage" const val ENGINE_KEY = "engine" diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceServiceDependencies.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceServiceDependencies.kt index e88e07c2b..8b7bf1c05 100644 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceServiceDependencies.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/InferenceServiceDependencies.kt @@ -5,11 +5,13 @@ import com.shifthackz.aisdv1.presentation.app.bootstrap.NativeInferenceEngineFac /** * Framework-service composition supplied by the application root without host services. * + * @param performanceReader On-demand resource reader restricted to the worker itself. * @param engines Child-only runtime factory. * @param files Private request/result exchange. * @author Dmitriy Moroz */ internal class InferenceServiceDependencies( val engines: NativeInferenceEngineFactory, - val files: GenerationFileStore + val files: GenerationFileStore, + val performanceReader: CurrentProcessPerformanceReader ) diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationGatewayImpl.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationGatewayImpl.kt index f485ee002..34e4bcc71 100644 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationGatewayImpl.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationGatewayImpl.kt @@ -2,6 +2,7 @@ package com.shifthackz.aisdv1.app.inference import android.util.Base64 import com.shifthackz.aisdv1.app.diagnostics.GenerationAttemptJournal +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.LocalDiffusionStatus import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine import com.shifthackz.aisdv1.domain.entity.NativeGenerationStage @@ -45,6 +46,14 @@ internal class NativeGenerationGatewayImpl( ) : NativeGenerationGateway { private val admission = Mutex() private val active = AtomicReference() + + /** + * Requests counters through the owned connection without starting or binding a service. + * @author Dmitriy Moroz + */ + override suspend fun readProcessPerformance(): ProcessPerformanceReading? = + active.get()?.connection?.readPerformance() + private val initialized = CompletableDeferred() private val progress = NativeGenerationEngine.entries.associateWith { MutableStateFlow( diff --git a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationService.kt b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationService.kt index 08e53b0ae..508a64b57 100644 --- a/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationService.kt +++ b/app/android/src/main/java/com/shifthackz/aisdv1/app/inference/NativeGenerationService.kt @@ -10,6 +10,7 @@ import android.os.Messenger import android.os.Process import com.shifthackz.aisdv1.app.AiStableDiffusionClientApp import com.shifthackz.aisdv1.domain.feature.diffusion.NativeInferenceEngine +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.NativeGenerationStage import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine import java.util.UUID @@ -151,6 +152,21 @@ internal class NativeGenerationService : Service() { } } + InferenceProtocol.READ_PERFORMANCE -> if (job == activeJob) { + val resourceRequestId = message.data.getLong(InferenceProtocol.RESOURCE_REQUEST_ID) + scope.launch { + val reading = withContext(Dispatchers.IO) { + runCatching { dependencies.performanceReader.read() } + } + send( + InferenceProtocol.PERFORMANCE, + job, + performance = reading.getOrNull(), + resourceRequestId = resourceRequestId + ) + } + } + InferenceProtocol.PING -> send(InferenceProtocol.PONG) InferenceProtocol.EXIT -> Process.killProcess(Process.myPid()) } @@ -162,10 +178,12 @@ internal class NativeGenerationService : Service() { job: String = "", current: Int = 0, total: Int = 0, - stage: NativeGenerationStage? = null + stage: NativeGenerationStage? = null, + performance: ProcessPerformanceReading? = null, + resourceRequestId: Long = 0L, ) { if (Looper.myLooper() != Looper.getMainLooper()) { - control.post { send(what, job, current, total, stage) } + control.post { send(what, job, current, total, stage, performance, resourceRequestId) } return } if (what == InferenceProtocol.STAGE) { @@ -174,6 +192,11 @@ internal class NativeGenerationService : Service() { } val reply = host ?: return val message = InferenceProtocol.message(what, incarnation, job, sequence.incrementAndGet()) + message.data.putLong(InferenceProtocol.RESOURCE_REQUEST_ID, resourceRequestId) + performance?.let { + message.data.putLong(InferenceProtocol.CPU_NANOS, it.cpuTimeNanos) + message.data.putLong(InferenceProtocol.RESIDENT_BYTES, it.residentBytes) + } message.data.putInt(InferenceProtocol.PID, Process.myPid()) message.data.putString(InferenceProtocol.ENGINE_KEY, engineKind?.name) message.data.putString(InferenceProtocol.STAGE_KEY, stage?.name) diff --git a/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/AndroidCurrentProcessPerformanceReaderTest.kt b/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/AndroidCurrentProcessPerformanceReaderTest.kt new file mode 100644 index 000000000..142c8c625 --- /dev/null +++ b/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/AndroidCurrentProcessPerformanceReaderTest.kt @@ -0,0 +1,104 @@ +package com.shifthackz.aisdv1.app.inference + +import android.app.Application +import android.os.Debug +import android.os.Process +import io.mockk.every +import io.mockk.mockkStatic +import io.mockk.unmockkStatic +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +/** + * Checks the worker's public OS-counter conversion without reading a sibling process. + * @author Dmitriy Moroz + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, application = Application::class, sdk = [28]) +class AndroidCurrentProcessPerformanceReaderTest { + @Before + fun setUp() { + mockkStatic(Debug::class, Process::class) + every { Debug.getMemoryInfo(any()) } answers { + firstArg().nativePss = 4096 + } + every { Process.myPid() } returns 42 + every { Process.getStartElapsedRealtime() } returns 123L + every { Process.getElapsedCpuTime() } returns 75L + } + + @After + fun tearDown() { + unmockkStatic(Debug::class, Process::class) + } + + @Test + fun `given worker telemetry, Android reports proportional resident kilobytes and CPU milliseconds, expected bytes nanoseconds and lifetime identity`() { + // Given + val reader = AndroidCurrentProcessPerformanceReader() + + // When + val reading = reader.read() + + // Then + assertEquals("42:123", reading.identity) + assertEquals(75_000_000L, reading.cpuTimeNanos) + assertEquals(4_194_304L, reading.residentBytes) + } + + @Test + fun `given worker telemetry, platform memory read fails, expected original failure propagated`() { + // Given + val failure = SecurityException("counter denied") + every { Debug.getMemoryInfo(any()) } throws failure + val reader = AndroidCurrentProcessPerformanceReader() + + // When + val caught = runCatching { reader.read() }.exceptionOrNull() + + // Then + assertSame(failure, caught) + } + + @Test + fun `given worker telemetry, proportional total includes swapped pages, expected only resident bytes counted as RAM`() { + // Given + var reportedTotalPss = 0 + every { Debug.getMemoryInfo(any()) } answers { + val memory = firstArg() + memory.dalvikPss = 1024 + memory.nativePss = 2048 + memory.otherPss = 1024 + ReflectionHelpers.setField(memory, "nativeSwappedOutPss", 2048) + reportedTotalPss = memory.totalPss + } + val reader = AndroidCurrentProcessPerformanceReader() + + // When + val reading = reader.read() + + // Then + assertEquals(6144, reportedTotalPss) + assertEquals(4_194_304L, reading.residentBytes) + } + + @Test + fun `given worker telemetry, Android returns no resident counters, expected failed reading instead of misleading zero`() { + // Given + every { Debug.getMemoryInfo(any()) } returns Unit + val reader = AndroidCurrentProcessPerformanceReader() + + // When + val failure = runCatching { reader.read() }.exceptionOrNull() + + // Then + assertEquals(IllegalStateException::class.java, failure?.javaClass) + } +} diff --git a/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/InferencePerformanceConnectionTest.kt b/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/InferencePerformanceConnectionTest.kt new file mode 100644 index 000000000..db08f9f37 --- /dev/null +++ b/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/InferencePerformanceConnectionTest.kt @@ -0,0 +1,378 @@ +package com.shifthackz.aisdv1.app.inference + +import android.app.Application +import android.content.ComponentName +import android.content.Context +import android.content.ServiceConnection +import android.os.Message +import android.os.Messenger +import android.os.Process +import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.util.ReflectionHelpers +import org.robolectric.util.ReflectionHelpers.ClassParameter +import org.robolectric.annotation.Config +import org.robolectric.annotation.LooperMode +import kotlin.time.Duration.Companion.seconds + +/** + * Exercises the production host connection with controlled protocol envelopes. These unit tests + * check telemetry isolation; Binder transport and native inference are covered by application QA. + * @author Dmitriy Moroz + */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, application = Application::class, sdk = [28]) +@LooperMode(LooperMode.Mode.PAUSED) +class InferencePerformanceConnectionTest { + private val dispatcher = StandardTestDispatcher() + private val sessions = mutableListOf() + + @Before + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @After + fun tearDown() = runTest(timeout = 10.seconds) { + sessions.forEach { + it.disconnect() + it.connection.close() + } + Dispatchers.resetMain() + } + + @Test + fun `given inference telemetry, no generation has submitted, expected absent reading without binding worker`() = + runTest { + // Given + val session = Session().also(sessions::add) + + // When + val reading = session.connection.readPerformance() + + // Then + assertNull(reading) + assertTrue(session.commands.isEmpty()) + assertFalse(session.binding.isCaptured) + } + + @Test + fun `given inference telemetry, matching response arrives, expected CPU RSS and validated incarnation returned`() = + runTest { + // Given + val session = connect() + val read = backgroundScope.async { session.connection.readPerformance() } + pump() + + // When + session.respond(session.requestId()) + pump() + + // Then + assertEquals( + ProcessPerformanceReading("99:${session.incarnation}", 200L, 400L), + read.await() + ) + assertTrue(session.generation.isActive) + } + + @Test + fun `given inference telemetry, counters are missing or negative, expected read failure without failing generation`() = + runTest { + // Given + val session = connect() + val failures = mutableListOf() + + // When + for (hasCounters in listOf(false, true)) { + val read = + backgroundScope.async { runCatching { session.connection.readPerformance() } } + pump() + session.respond(session.requestId()) { + if (hasCounters) data.putLong(InferenceProtocol.CPU_NANOS, -1) + else data.remove(InferenceProtocol.RESIDENT_BYTES) + } + pump() + failures.add(read.await().exceptionOrNull()) + } + + // Then + assertTrue(failures.all { it is IllegalStateException }) + assertTrue(session.generation.isActive) + assertFalse(session.commands.any { it.what == InferenceProtocol.CANCEL }) + } + + @Test + fun `given inference telemetry, peer does not reply before deadline, expected timeout only for resource reading`() = + runTest { + // Given + val session = connect() + val read = + backgroundScope.async { runCatching { session.connection.readPerformance() } } + pump() + + // When + advanceTimeBy(2_000) + pump() + + // Then + assertEquals( + "Inference resource reading timed out", + read.await().exceptionOrNull()?.message + ) + assertTrue(session.generation.isActive) + assertFalse(session.commands.any { it.what == InferenceProtocol.CANCEL || it.what == InferenceProtocol.EXIT }) + } + + @Test + fun `given inference telemetry, late response follows timeout, expected only new request can complete next reading`() = + runTest { + // Given + val session = connect() + val oldRead = + backgroundScope.async { runCatching { session.connection.readPerformance() } } + pump() + val oldRequest = session.requestId() + advanceTimeBy(2_000) + pump() + assertTrue(oldRead.await().isFailure) + val nextRead = backgroundScope.async { session.connection.readPerformance() } + pump() + val nextRequest = session.requestId() + + // When + session.respond(oldRequest) + pump() + val hasAcceptedStaleReply = nextRead.isCompleted + session.respond(nextRequest) + pump() + + // Then + assertFalse(hasAcceptedStaleReply) + assertTrue(nextRequest > oldRequest) + assertEquals(400L, nextRead.await()?.residentBytes) + } + + @Test + fun `given inference telemetry, untrusted or stale envelopes arrive, expected pending reading accepts only validated reply`() = + runTest { + // Given + val session = connect() + val read = backgroundScope.async { session.connection.readPerformance() } + pump() + val request = session.requestId() + val invalidEnvelopes: List Unit> = listOf( + { sendingUid = Process.myUid() + 1 }, + { data.putInt(InferenceProtocol.VERSION_KEY, InferenceProtocol.VERSION - 1) }, + { data.putString(InferenceProtocol.INCARNATION, "wrong") }, + { data.putString(InferenceProtocol.JOB, "other-job") }, + { data.putString(InferenceProtocol.ENGINE_KEY, NativeGenerationEngine.ONNX.name) }, + { data.putLong(InferenceProtocol.SEQUENCE, 0) }, + { data.putLong(InferenceProtocol.RESOURCE_REQUEST_ID, request + 1) }, + ) + + // When + val acceptedInvalidReply = invalidEnvelopes.map { mutate -> + session.respond(request, mutate) + pump() + read.isCompleted + } + session.respond(request) + pump() + + // Then + assertTrue(acceptedInvalidReply.none { it }) + assertEquals(200L, read.await()?.cpuTimeNanos) + } + + @Test + fun `given inference telemetry, callers read concurrently, expected serialized correlated resource requests`() = + runTest { + // Given + val session = connect() + val first = backgroundScope.async { session.connection.readPerformance() } + val second = backgroundScope.async { session.connection.readPerformance() } + pump() + val initialRequests = + session.commands.count { it.what == InferenceProtocol.READ_PERFORMANCE } + val firstId = session.requestId() + + // When + session.respond(firstId) + pump() + val secondId = session.requestId() + session.respond(secondId) { data.putLong(InferenceProtocol.RESIDENT_BYTES, 800) } + pump() + + // Then + assertEquals(1, initialRequests) + assertEquals( + 2, + session.commands.count { it.what == InferenceProtocol.READ_PERFORMANCE }) + assertTrue(secondId > firstId) + assertEquals(400L, first.await()?.residentBytes) + assertEquals(800L, second.await()?.residentBytes) + } + + @Test + fun `given inference telemetry, collector cancels resource read, expected later reading works and inference stays active`() = + runTest { + // Given + val session = connect() + val first = backgroundScope.async { session.connection.readPerformance() } + pump() + + // When + first.cancelAndJoin() + val second = backgroundScope.async { session.connection.readPerformance() } + pump() + session.respond(session.requestId()) + pump() + + // Then + assertEquals(400L, second.await()?.residentBytes) + assertTrue(session.generation.isActive) + assertFalse(session.commands.any { it.what == InferenceProtocol.CANCEL }) + } + + @Test + fun `given inference telemetry, child disconnects during read, expected pending read fails promptly and generation fails`() = + runTest { + // Given + val session = connect() + val read = + backgroundScope.async { runCatching { session.connection.readPerformance() } } + pump() + + // When + session.disconnect() + pump() + + // Then + assertEquals("Inference process exited", read.await().exceptionOrNull()?.message) + assertTrue(session.generation.await().isFailure) + } + + @Test + fun `given inference telemetry, generation finishes, expected later reading absent without further resource request`() = + runTest { + // Given + val session = connect() + session.send(InferenceProtocol.SUCCESS) + pump() + + // When + val reading = session.connection.readPerformance() + + // Then + assertNull(reading) + assertTrue(session.generation.await().isSuccess) + assertFalse(session.commands.any { it.what == InferenceProtocol.READ_PERFORMANCE }) + } + + private fun TestScope.connect(): Session { + val session = Session().also(sessions::add) + session.generation = backgroundScope.async { + runCatching { + session.connection.run( + session.job, + NativeGenerationEngine.MNN, + {}, + {}, + { _, _ -> }) + } + } + runCurrent() + session.attachPeer() + session.send(InferenceProtocol.READY) + pump() + assertTrue( + "Expected submitted job, received ${session.commands.map { it.what }}", + session.commands.any { it.what == InferenceProtocol.SUBMIT }) + // The production heartbeat uses wall-clock uptime; this fixture advances only virtual + // coroutine time to test the independent resource deadline. + ReflectionHelpers.getField(session.connection, "heartbeat").cancel() + return session + } + + private fun TestScope.pump() { + runCurrent() + } + + private class Session { + val incarnation = "a7f4298e-4dfa-4b00-b49a-ec6d6e326fbb" + val job = "25c57c00-f42d-4f07-a401-8d1b88d7528d" + val component = ComponentName("test", "Inference") + val binding = slot() + val commands = mutableListOf() + private val context = mockk(relaxed = true) { + every { bindService(any(), capture(binding), any()) } returns true + } + val connection = AndroidInferenceConnection(context) + lateinit var generation: Deferred> + private var sequence = 0L + private val peer = mockk { + every { send(any()) } answers { commands.add(firstArg()); Unit } + } + + fun attachPeer() { + ReflectionHelpers.setField(connection, "remote", peer) + } + + fun requestId() = commands.last { it.what == InferenceProtocol.READ_PERFORMANCE } + .data.getLong(InferenceProtocol.RESOURCE_REQUEST_ID) + + fun respond(requestId: Long, mutate: Message.() -> Unit = {}) { + send(InferenceProtocol.PERFORMANCE) { + data.putLong(InferenceProtocol.RESOURCE_REQUEST_ID, requestId) + data.putLong(InferenceProtocol.CPU_NANOS, 200) + data.putLong(InferenceProtocol.RESIDENT_BYTES, 400) + mutate() + } + } + + fun send(what: Int, mutate: Message.() -> Unit = {}) { + val message = InferenceProtocol.message(what, incarnation, job, ++sequence).apply { + sendingUid = Process.myUid() + data.putInt(InferenceProtocol.PID, 99) + data.putString(InferenceProtocol.ENGINE_KEY, NativeGenerationEngine.MNN.name) + mutate() + } + ReflectionHelpers.callInstanceMethod( + connection, + "onMessage", + ClassParameter.from(Message::class.java, message) + ) + } + + fun disconnect() { + if (binding.isCaptured) binding.captured.onServiceDisconnected(component) + } + } +} diff --git a/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/MnnNativeGatewayTest.kt b/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/MnnNativeGatewayTest.kt index 0fdef8765..8546a789c 100644 --- a/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/MnnNativeGatewayTest.kt +++ b/app/android/src/test/java/com/shifthackz/aisdv1/app/inference/MnnNativeGatewayTest.kt @@ -4,6 +4,7 @@ import com.shifthackz.aisdv1.presentation.app.bootstrap.createNativeInferenceEng import android.app.Application import com.shifthackz.aisdv1.app.diagnostics.GenerationAttemptJournal +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.LocalDiffusionStatus import com.shifthackz.aisdv1.domain.entity.MnnBackend import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine @@ -17,6 +18,7 @@ import io.mockk.verify import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -37,7 +39,9 @@ class MnnNativeGatewayTest { fun `given MNN gateway, child completes isolated attempt, expected MNN callbacks and owned output publication`() = runTest { // Given - val connection = mockk(relaxed = true) + val connection = mockk(relaxed = true) { + every { processId } returns 4321 + } val connections = mockk { every { create() } returns connection } val files = mockk(relaxed = true) { @@ -62,6 +66,8 @@ class MnnNativeGatewayTest { ) ) } + val reading = ProcessPerformanceReading("4321:worker", 123, 456) + coEvery { connection.readPerformance() } returns reading coEvery { connection.close() } returns true coEvery { connection.run( @@ -72,6 +78,7 @@ class MnnNativeGatewayTest { any() ) } coAnswers { + assertEquals(reading, gateway.readProcessPerformance()) arg<(LocalDiffusionStatus) -> Unit>(2)(LocalDiffusionStatus(15, 100)) arg<(NativeGenerationStage) -> Unit>(3)(NativeGenerationStage.RUNNING) assertEquals( @@ -88,6 +95,7 @@ class MnnNativeGatewayTest { val output = gateway.generate(request) // Then + assertNull(gateway.readProcessPerformance()) assertEquals("AQID", output) assertEquals( LocalDiffusionStatus(0, 0), diff --git a/core/localization/src/androidMain/res/values-de/strings.xml b/core/localization/src/androidMain/res/values-de/strings.xml index fd6d9c234..5bbd3173c 100644 --- a/core/localization/src/androidMain/res/values-de/strings.xml +++ b/core/localization/src/androidMain/res/values-de/strings.xml @@ -778,4 +778,11 @@ Gemeinsame Zugangsdaten bleiben für nicht ausgewählte Anbieter erhalten: %1$s. Display dimmen *Das Display wird nur gedimmt, wenn die Hintergrundgenerierung ausgeschaltet ist. + + Leistungsanzeige + CPU + RAM + %1$s / %2$s MiB + Diese App + Gesamt diff --git a/core/localization/src/androidMain/res/values-ru/strings.xml b/core/localization/src/androidMain/res/values-ru/strings.xml index e761db33a..9b2d7cd5e 100644 --- a/core/localization/src/androidMain/res/values-ru/strings.xml +++ b/core/localization/src/androidMain/res/values-ru/strings.xml @@ -741,4 +741,11 @@ Общие учётные данные сохранены для невыбранных провайдеров: %1$s. Затемнять экран *Затемнение экрана работает только при отключённой фоновой генерации. + + Монитор производительности + ЦП + ОЗУ + %1$s / %2$s МиБ + Это приложение + Всего diff --git a/core/localization/src/androidMain/res/values-tr/strings.xml b/core/localization/src/androidMain/res/values-tr/strings.xml index 26ddaa22e..b213037a5 100644 --- a/core/localization/src/androidMain/res/values-tr/strings.xml +++ b/core/localization/src/androidMain/res/values-tr/strings.xml @@ -741,4 +741,11 @@ Seçilmeyen sağlayıcıları korumak için ortak kimlik bilgileri tutuldu: %1$s. Ekranı karart *Ekran karartma yalnızca arka planda üretim kapalıyken etkindir. + + Performans göstergesi + CPU + RAM + %1$s / %2$s MiB + Bu uygulama + Toplam diff --git a/core/localization/src/androidMain/res/values-uk/strings.xml b/core/localization/src/androidMain/res/values-uk/strings.xml index 4d6602d82..c8b961013 100644 --- a/core/localization/src/androidMain/res/values-uk/strings.xml +++ b/core/localization/src/androidMain/res/values-uk/strings.xml @@ -741,4 +741,11 @@ Спільні облікові дані збережено для невибраних провайдерів: %1$s. Затемнювати екран *Затемнення екрана працює лише за вимкненої фонової генерації. + + Монітор продуктивності + ЦП + ОЗП + %1$s / %2$s МіБ + Цей застосунок + Загалом diff --git a/core/localization/src/androidMain/res/values-zh/strings.xml b/core/localization/src/androidMain/res/values-zh/strings.xml index 54b5f1f3e..668dad48a 100644 --- a/core/localization/src/androidMain/res/values-zh/strings.xml +++ b/core/localization/src/androidMain/res/values-zh/strings.xml @@ -793,4 +793,11 @@ 为保留未选提供商的设置,共用凭据未更改:%1$s。 调暗屏幕 *仅在关闭后台生成时才会调暗屏幕。 + + 性能监视器 + CPU + 内存 + %1$s / %2$s MiB + 此应用 + 总计 diff --git a/core/localization/src/androidMain/res/values/strings.xml b/core/localization/src/androidMain/res/values/strings.xml index 75037bc5c..74a2e7615 100755 --- a/core/localization/src/androidMain/res/values/strings.xml +++ b/core/localization/src/androidMain/res/values/strings.xml @@ -778,4 +778,11 @@ Shared sign-in credentials were kept to preserve unselected providers: %1$s. Dim screen *Screen dimming is active only when background generation is off. + + Performance overlay + CPU + RAM + %1$s / %2$s MiB + This app + Total diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt index d6f890303..acb303beb 100644 --- a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt +++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt @@ -30,6 +30,8 @@ import org.koin.android.ext.koin.androidContext import org.koin.core.module.dsl.factoryOf import org.koin.core.module.dsl.singleOf import org.koin.dsl.bind +import com.shifthackz.aisdv1.data.performance.AndroidPerformanceGateway +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway import org.koin.dsl.module /** @@ -38,6 +40,7 @@ import org.koin.dsl.module * @author Dmitriy Moroz */ private val androidDataOverridesModule = module { + single { AndroidPerformanceGateway(androidContext(), get()) } singleOf(::DatabaseClearGatewayImpl) bind DatabaseClearGateway::class singleOf(::MediaStoreImageFormatResolverImpl) bind MediaStoreImageFormatResolver::class single { diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/performance/AndroidPerformanceGateway.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/performance/AndroidPerformanceGateway.kt new file mode 100644 index 000000000..378a958c1 --- /dev/null +++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/performance/AndroidPerformanceGateway.kt @@ -0,0 +1,62 @@ +package com.shifthackz.aisdv1.data.performance + +import android.app.ActivityManager +import android.content.Context +import android.os.Process +import android.os.Debug +import android.os.SystemClock +import com.shifthackz.aisdv1.domain.entity.CpuUsageCounters +import com.shifthackz.aisdv1.domain.entity.PerformanceReading +import com.shifthackz.aisdv1.domain.gateway.NativeGenerationGateway +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway +import java.io.File + +/** + * Combines host-owned counters with on-demand child IPC readings. Android blocks sibling /proc + * reads even for the app's inference process; those reads must never stand in for worker telemetry. + * Proportional resident memory apportions shared pages between their processes. Device usage + * includes reclaimable file caches, so file-backed model pages remain in both accounting scopes. + * @param context Application context used to read device physical memory capacity. + * @param nativeGateway Current inference connection, queried without starting a worker. + * @author Dmitriy Moroz + */ +internal class AndroidPerformanceGateway( + context: Context, + private val nativeGateway: NativeGenerationGateway, +) : PerformanceGateway { + private val activityManager = + context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + + override suspend fun read(): PerformanceReading { + val worker = nativeGateway.readProcessPerformance() + val processMemory = Debug.MemoryInfo() + Debug.getMemoryInfo(processMemory) + val residentKilobytes = + processMemory.dalvikPss.toLong() + processMemory.nativePss + processMemory.otherPss + check(residentKilobytes > 0) + val memory = ActivityManager.MemoryInfo() + activityManager.getMemoryInfo(memory) + return PerformanceReading( + elapsedNanos = SystemClock.elapsedRealtimeNanos(), + cpuTimeNanos = buildMap { + put("host", Process.getElapsedCpuTime() * 1_000_000L) + worker?.let { put(it.identity, it.cpuTimeNanos) } + }, + processorCount = Runtime.getRuntime().availableProcessors(), + residentBytes = residentKilobytes * 1024L + (worker?.residentBytes ?: 0L), + totalMemoryBytes = memory.totalMem, + deviceUsedMemoryBytes = memory.totalMem - parseFreeMemoryBytes( + File("/proc/meminfo").readText(), + memory.totalMem + ), + deviceCpu = runCatching { + val ticks = File("/proc/stat").useLines { lines -> + lines.first().trim().split(Regex("\\s+")).drop(1).take(8).map(String::toLong) + } + require(ticks.size >= 4) + val total = ticks.sum() + CpuUsageCounters(total - ticks[3] - ticks.getOrElse(4) { 0L }, total) + }, + ) + } +} diff --git a/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/performance/ProcMemoryInfo.kt b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/performance/ProcMemoryInfo.kt new file mode 100644 index 000000000..08eccb415 --- /dev/null +++ b/data/src/androidMain/kotlin/com/shifthackz/aisdv1/data/performance/ProcMemoryInfo.kt @@ -0,0 +1,18 @@ +package com.shifthackz.aisdv1.data.performance + +/** + * Reads actual unused RAM from Linux meminfo without treating reclaimable caches as free. + * Invalid or missing counters fail the sample rather than changing the accounting definition. + * + * @param content Complete /proc/meminfo text, whose memory quantities use binary kilobytes. + * @param totalBytes Device physical capacity used to reject inconsistent kernel counters. + * @author Dmitriy Moroz + */ +internal fun parseFreeMemoryBytes(content: String, totalBytes: Long): Long { + val fields = content.lineSequence().first { it.startsWith("MemFree:") } + .trim().split(Regex("\\s+")) + require(fields.size == 3 && fields[2] == "kB") + val kibibytes = fields[1].toLong() + require(totalBytes > 0 && kibibytes in 0..totalBytes / 1024) + return kibibytes * 1024 +} diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/performance/ProcMemoryInfoTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/performance/ProcMemoryInfoTest.kt new file mode 100644 index 000000000..aed829609 --- /dev/null +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/performance/ProcMemoryInfoTest.kt @@ -0,0 +1,73 @@ +package com.shifthackz.aisdv1.data.performance + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +/** + * Guards the difference between unused RAM and reclaimable file cache in Linux counters. + * @author Dmitriy Moroz + */ +class ProcMemoryInfoTest { + @Test + fun `given device memory accounting, model cache is reclaimable, expected free counter excludes no cached pages`() { + // Given + val content = + "MemTotal: 8000 kB\nMemAvailable: 6000 kB\nCached: 5000 kB\nMemFree: 1000 kB\n" + + // When + val used = 8000 * 1024L - parseFreeMemoryBytes(content, 8000 * 1024L) + + // Then + assertEquals(7000 * 1024L, used) + } + + @Test + fun `given device memory accounting, no free pages remain, expected full physical capacity in use`() { + // Given + val total = 8000 * 1024L + + // When + val free = parseFreeMemoryBytes("MemFree:\t0 kB\n", total) + + // Then + assertEquals(0L, free) + assertEquals(total, total - free) + } + + @Test + fun `given device memory accounting, free counter is missing, expected read failure instead of available memory substitution`() { + // Given + val content = "MemAvailable: 6000 kB\nCached: 5000 kB\n" + + // When + val failure = assertThrows(NoSuchElementException::class.java) { + parseFreeMemoryBytes( + content, + 8000 * 1024L + ) + } + + // Then + assertEquals(NoSuchElementException::class.java, failure.javaClass) + } + + @Test + fun `given device memory accounting, free counter has invalid units format or range, expected failed samples`() { + // Given + val counters = listOf("1 MB", "1", "-1 kB", "9000 kB", "9223372036854775807 kB", "oops kB") + + // When + val failures = counters.map { + runCatching { + parseFreeMemoryBytes( + "MemFree: $it", + 8000 * 1024L + ) + }.isFailure + } + + // Then + assertEquals(List(counters.size) { true }, failures) + } +} diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt index ab7dadf6e..9985c8551 100644 --- a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImplTest.kt @@ -7,6 +7,9 @@ import com.shifthackz.aisdv1.domain.entity.Grid import com.shifthackz.aisdv1.domain.entity.HuggingFaceModel import com.shifthackz.aisdv1.domain.entity.ServerSource import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Before @@ -248,6 +251,54 @@ class PreferenceManagerImplTest { Assert.assertEquals("uk", settings.languageCode) } + @Test + fun `given performance overlay preferences, no choice is saved, expected overlay enabled in getter and snapshot`() = + runTest { + // Given + val freshPreferences = PreferenceManagerImpl(keyValueStore) + + // When + val snapshot = freshPreferences.observe().first() + + // Then + Assert.assertTrue(freshPreferences.shouldShowPerformanceOverlay) + Assert.assertTrue(snapshot.shouldShowPerformanceOverlay) + } + + @Test + fun `given performance overlay preferences, disabled choice is saved then manager recreated, expected disabled choice preserved`() = + runTest { + // Given + preferenceManager.shouldShowPerformanceOverlay = false + + // When + val recreated = PreferenceManagerImpl(keyValueStore) + val snapshot = recreated.observe().first() + + // Then + Assert.assertFalse(recreated.shouldShowPerformanceOverlay) + Assert.assertFalse(snapshot.shouldShowPerformanceOverlay) + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `given performance overlay preferences, user disables then reenables, expected live observer and durable choice updated`() = + runTest { + // Given + val values = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + preferenceManager.observe().collect { values.add(it.shouldShowPerformanceOverlay) } + } + + // When + preferenceManager.shouldShowPerformanceOverlay = false + preferenceManager.shouldShowPerformanceOverlay = true + + // Then + Assert.assertEquals(listOf(true, false, true), values) + Assert.assertTrue(PreferenceManagerImpl(keyValueStore).shouldShowPerformanceOverlay) + } + private class InMemoryKeyValueStore : KeyValueStore { override fun retryPendingWrite(): Boolean = false override fun contains(key: String): Boolean = diff --git a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt index 19142cc6f..b57e3613d 100644 --- a/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt +++ b/data/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImplTest.kt @@ -423,4 +423,75 @@ class BackupPreferencesGatewayImplTest { // Then assertTrue(recovered.isEmpty()) } + + @Test + fun `given performance overlay backup, saved choice is exported then restored, expected both flag choices survive round trip`() { + // Given + val actualPreferences = PreferenceManagerImpl(store) + val actualGateway = BackupPreferencesGatewayImpl(store, actualPreferences) + every { store.putSettingsDurably(any(), any(), any()) } answers { + strings.putAll(firstArg()); flags.putAll(secondArg()); integers.putAll(thirdArg()) + } + val choices = listOf(false, true) + + // When + val restored = choices.map { isEnabled -> + flags["key_performance_overlay"] = isEnabled + val exported = actualGateway.read() + val supported = actualGateway.filterSupported(exported) + flags.remove("key_performance_overlay") + actualGateway.writeSettings(supported.settings) + PreferenceManagerImpl(store).shouldShowPerformanceOverlay + } + + // Then + assertEquals(choices, restored) + } + + @Test + fun `given older settings backup, overlay flag is absent, expected current explicit choice is preserved`() { + // Given + flags["key_performance_overlay"] = false + val actualPreferences = PreferenceManagerImpl(store) + + // When + gateway.writeSettings(mapOf("autoSave" to BackupValue.Flag(true))) + + // Then + assertFalse(actualPreferences.shouldShowPerformanceOverlay) + verify { + store.putSettingsDurably(emptyMap(), mapOf("key_ai_auto_save" to true), emptyMap()) + } + } + + @Test + fun `given performance overlay backup, nonboolean value is imported, expected validation failure`() { + // Given + val incoming = + BackupPreferences(emptyMap(), mapOf("performanceOverlay" to BackupValue.Text("false"))) + + // When + val failure = + assertThrows(IllegalArgumentException::class.java) { gateway.filterSupported(incoming) } + + // Then + assertEquals("Invalid portable preference type", failure.message) + } + + @Test + fun `given recovered overlay preference write, effective choice changes, expected settings invalidation`() { + // Given + every { preferences.shouldShowPerformanceOverlay } answers { + flags["key_performance_overlay"] ?: true + } + every { store.retryPendingWrite() } answers { + flags["key_performance_overlay"] = false; true + } + + // When + val recovered = gateway.recoverPendingWrite() + + // Then + assertEquals(setOf(BackupCategory.SETTINGS), recovered) + } } diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt index baa12a356..d6f7827fd 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/PreferenceManagerImpl.kt @@ -586,10 +586,18 @@ internal class PreferenceManagerImpl( set(value) = putString(KEY_DESIGN_DARK_TOKEN, value) /** - * Whether active foreground generation lowers display brightness. + * Whether generation progress displays app CPU and resident-memory history. * * @author Dmitriy Moroz */ + override var shouldShowPerformanceOverlay: Boolean + get() = keyValueStore.getBoolean(KEY_PERFORMANCE_OVERLAY, true) + set(value) = putBoolean(KEY_PERFORMANCE_OVERLAY, value) + + /** + * Whether active foreground generation lowers display brightness. + * @author Dmitriy Moroz + */ override var shouldDimScreen: Boolean get() = keyValueStore.getBoolean(KEY_DIM_SCREEN) set(value) = putBoolean(KEY_DIM_SCREEN, value) @@ -670,6 +678,7 @@ internal class PreferenceManagerImpl( monitorConnectivity = monitorConnectivity, backgroundGeneration = backgroundGeneration, shouldDimScreen = shouldDimScreen, + shouldShowPerformanceOverlay = shouldShowPerformanceOverlay, autoSaveAiResults = autoSaveAiResults, saveToMediaStore = saveToMediaStore, formAdvancedOptionsAlwaysShow = formAdvancedOptionsAlwaysShow, @@ -1115,10 +1124,16 @@ internal class PreferenceManagerImpl( const val KEY_DESIGN_DARK_TOKEN = "key_design_dark_color_token_theme" /** - * Stable storage key for the opt-in foreground display dimming preference. + * Stable storage key for the generation resource overlay preference. * * @author Dmitriy Moroz */ + const val KEY_PERFORMANCE_OVERLAY = "key_performance_overlay" + + /** + * Stable storage key for the opt-in foreground display dimming preference. + * @author Dmitriy Moroz + */ const val KEY_DIM_SCREEN = "key_dim_screen" /** Stable storage key for background generation scheduling. diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt index e2ad53364..c0469eb80 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/BackupPreferencesGatewayImpl.kt @@ -26,6 +26,7 @@ internal class BackupPreferencesGatewayImpl( private val store: KeyValueStore, private val preferences: PreferenceManager ) : BackupPreferencesGateway { + override fun recoverPendingWrite(): Set { val previous = read() val authorizationCommit = store.getString("key_authorization_commit_id") @@ -101,6 +102,7 @@ internal class BackupPreferencesGatewayImpl( "taggedInput" to BackupValue.Flag(preferences.formPromptTaggedInput), "connectionTimeout" to BackupValue.Integer(preferences.connectionTimeout.seconds), "generationTimeout" to BackupValue.Integer(preferences.generationRequestTimeout.seconds), + "performanceOverlay" to BackupValue.Flag(preferences.shouldShowPerformanceOverlay), "dimScreen" to BackupValue.Flag(preferences.shouldDimScreen), "backgroundGeneration" to BackupValue.Flag(preferences.backgroundGeneration), "monitorConnection" to BackupValue.Flag(preferences.monitorConnectivity), diff --git a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt index 548c3bfd5..e5a1a121b 100644 --- a/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt +++ b/data/src/commonMain/kotlin/com/shifthackz/aisdv1/data/preference/backup/PortablePreferenceSchema.kt @@ -146,6 +146,10 @@ internal object PortablePreferenceSchema { "key_generation_request_timeout_seconds", PortablePreferenceType.INTEGER ), + "performanceOverlay" to PortablePreferenceField( + "key_performance_overlay", + PortablePreferenceType.FLAG + ), "dimScreen" to PortablePreferenceField("key_dim_screen", PortablePreferenceType.FLAG), "backgroundGeneration" to PortablePreferenceField( "key_background_generation", diff --git a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt index 21b139886..7365aeb30 100644 --- a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt +++ b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/di/DataModule.kt @@ -18,6 +18,8 @@ import com.shifthackz.aisdv1.domain.repository.WakeLockRepository import org.koin.core.module.dsl.factoryOf import org.koin.core.module.dsl.singleOf import org.koin.dsl.bind +import com.shifthackz.aisdv1.data.performance.IosPerformanceGateway +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway import org.koin.dsl.module import platform.Foundation.NSBundle import platform.Foundation.NSHomeDirectory @@ -28,6 +30,7 @@ import platform.Foundation.NSHomeDirectory * @author Dmitriy Moroz */ private val iosDataOverridesModule = module { + single { IosPerformanceGateway() } singleOf(::MnnBundleValidatorImpl) bind MnnBundleValidator::class singleOf(::IosMnnModelFileStore) bind MnnModelStore::class singleOf(::MnnGenerationRepositoryImpl) bind MnnGenerationRepository::class diff --git a/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/performance/IosPerformanceGateway.kt b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/performance/IosPerformanceGateway.kt new file mode 100644 index 000000000..477a03fae --- /dev/null +++ b/data/src/iosMain/kotlin/com/shifthackz/aisdv1/data/performance/IosPerformanceGateway.kt @@ -0,0 +1,113 @@ +@file:OptIn(ExperimentalForeignApi::class) + +package com.shifthackz.aisdv1.data.performance + +import com.shifthackz.aisdv1.domain.entity.CpuUsageCounters +import com.shifthackz.aisdv1.domain.entity.PerformanceReading +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.get +import kotlinx.cinterop.IntVar +import kotlinx.cinterop.alloc +import kotlinx.cinterop.ptr +import kotlinx.cinterop.reinterpret +import kotlinx.cinterop.sizeOf +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.value +import platform.Foundation.NSProcessInfo +import platform.darwin.CPU_STATE_IDLE +import platform.darwin.CPU_STATE_MAX +import platform.darwin.HOST_CPU_LOAD_INFO +import platform.darwin.HOST_VM_INFO64 +import platform.darwin.host_cpu_load_info_data_t +import platform.darwin.vm_statistics64_data_t +import platform.darwin.host_statistics +import platform.darwin.host_statistics64 +import platform.darwin.mach_host_self +import platform.darwin.mach_port_deallocate +import platform.posix.getpagesize +import platform.darwin.KERN_SUCCESS +import platform.darwin.MACH_TASK_BASIC_INFO +import platform.darwin.mach_task_basic_info_data_t +import platform.darwin.mach_task_self_ +import platform.darwin.task_info +import platform.posix.CLOCK_MONOTONIC +import platform.posix.RUSAGE_SELF +import platform.posix.clock_gettime +import platform.posix.getrusage +import platform.posix.rusage +import platform.posix.timespec + +/** + * Reads iOS resident app memory and cumulative CPU time using public Mach/POSIX APIs. + * Counters cover the in-process native inference engines as well as the UI runtime. + * @author Dmitriy Moroz + */ +internal class IosPerformanceGateway : PerformanceGateway { + override suspend fun read(): PerformanceReading = memScoped { + val usage = alloc() + check(getrusage(RUSAGE_SELF, usage.ptr) == 0) + val memory = alloc() + val count = alloc { + value = (sizeOf() / sizeOf()).toInt() + } + check( + task_info( + mach_task_self_, + MACH_TASK_BASIC_INFO.toUInt(), + memory.ptr.reinterpret(), + count.ptr.reinterpret() + ) == KERN_SUCCESS + ) + val clock = alloc() + check(clock_gettime(CLOCK_MONOTONIC.toUInt(), clock.ptr) == 0) + val cpuNanos = (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * 1_000_000_000L + + (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) * 1_000L + val host = mach_host_self() + val deviceCpu = try { + runCatching { + val cpu = alloc() + count.value = (sizeOf() / sizeOf()).toInt() + check( + host_statistics( + host, + HOST_CPU_LOAD_INFO, + cpu.ptr.reinterpret(), + count.ptr.reinterpret() + ) == KERN_SUCCESS + ) + val total = (0 until CPU_STATE_MAX).sumOf { cpu.cpu_ticks[it].toLong() } + CpuUsageCounters(total - cpu.cpu_ticks[CPU_STATE_IDLE].toLong(), total) + } + } finally { + mach_port_deallocate(mach_task_self_, host) + } + val memoryHost = mach_host_self() + val deviceUsedMemory = try { + val vm = alloc() + count.value = (sizeOf() / sizeOf()).toInt() + check( + host_statistics64( + memoryHost, + HOST_VM_INFO64, + vm.ptr.reinterpret(), + count.ptr.reinterpret() + ) == KERN_SUCCESS + ) + (NSProcessInfo.processInfo.physicalMemory.toLong() - vm.free_count.toLong() * getpagesize()).coerceAtLeast( + 0L + ) + } finally { + mach_port_deallocate(mach_task_self_, memoryHost) + } + PerformanceReading( + elapsedNanos = clock.tv_sec * 1_000_000_000L + clock.tv_nsec, + cpuTimeNanos = mapOf("app" to cpuNanos), + processorCount = NSProcessInfo.processInfo.processorCount.toInt(), + residentBytes = memory.resident_size.toLong(), + totalMemoryBytes = NSProcessInfo.processInfo.physicalMemory.toLong(), + deviceCpu = deviceCpu, + deviceUsedMemoryBytes = deviceUsedMemory, + ) + } +} diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCaseImplTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCaseImplTest.kt new file mode 100644 index 000000000..37b820ced --- /dev/null +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCaseImplTest.kt @@ -0,0 +1,243 @@ +package com.shifthackz.aisdv1.domain.usecase.generation + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.CpuUsageCounters +import com.shifthackz.aisdv1.domain.entity.PerformanceReading +import com.shifthackz.aisdv1.domain.entity.PerformanceSample +import com.shifthackz.aisdv1.domain.entity.Settings +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ObserveGenerationPerformanceUseCaseImplTest { + private val preferences = mockk() + private val gateway = mockk() + private val settings = MutableStateFlow(Settings(shouldShowPerformanceOverlay = true)) + + @Test + fun `given performance observation, host and worker consume CPU, expected device-normalized sum and resident bytes`() = + runTest { + // Given + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + every { preferences.observe() } returns settings + coEvery { gateway.read() } returnsMany listOf( + PerformanceReading( + 1_000_000_000, + mapOf("host" to 100_000_000, "worker" to 100_000_000), + 4, + 100, + 1000, + Result.success(CpuUsageCounters(200, 1000)), + 600, + ), + PerformanceReading( + 2_000_000_000, + mapOf("host" to 600_000_000, "worker" to 1_600_000_000), + 4, + 700, + 1000, + Result.success(CpuUsageCounters(700, 2000)), + 800, + ), + ) + val values = mutableListOf>() + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + + // When + backgroundScope.launch { useCase().collect { values.add(it) } } + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertNull(values.first().last().cpuPercent) + assertEquals(50f, values.last().last().cpuPercent) + assertEquals(700L, values.last().last().residentBytes) + assertEquals(1000L, values.last().last().totalMemoryBytes) + assertEquals(50f, values.last().last().deviceCpuPercent) + assertEquals(800L, values.last().last().deviceUsedMemoryBytes) + } + + @Test + fun `given performance observation, preference is disabled then enabled, expected sampling stops and history restarts`() = + runTest { + // Given + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + every { preferences.observe() } returns settings + coEvery { gateway.read() } returns PerformanceReading( + 1, + mapOf("host" to 1), + 4, + 100, + 1000 + ) + val values = mutableListOf>() + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + backgroundScope.launch { useCase().collect { values.add(it) } } + runCurrent() + + // When + settings.value = Settings(shouldShowPerformanceOverlay = false) + runCurrent() + advanceTimeBy(5_000) + runCurrent() + + // Then + assertTrue(values.last().isEmpty()) + coVerify(exactly = 1) { gateway.read() } + settings.value = Settings(shouldShowPerformanceOverlay = true) + runCurrent() + assertEquals(1, values.last().size) + assertNull(values.last().last().cpuPercent) + coVerify(exactly = 2) { gateway.read() } + } + + @Test + fun `given performance observation, platform read fails then recovers, expected unavailable point and fresh CPU baseline`() = + runTest { + // Given + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + every { preferences.observe() } returns settings + var calls = 0 + coEvery { gateway.read() } answers { + calls++ + if (calls == 2) throw IllegalStateException("Process exited") + PerformanceReading( + calls * 1_000_000_000L, + mapOf("host" to calls * 100_000_000L), + 4, + 100, + 1000 + ) + } + val values = mutableListOf>() + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + + // When + backgroundScope.launch { useCase().collect { values.add(it) } } + runCurrent() + advanceTimeBy(2_000) + runCurrent() + + // Then + assertEquals(PerformanceSample(), values[1].last()) + assertEquals(100L, values.last().last().residentBytes) + assertNull(values.last().last().cpuPercent) + } + + @Test + fun `given performance observation, collection exceeds one minute then cancels, expected bounded history and no further reads`() = + runTest { + // Given + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + every { preferences.observe() } returns settings + var calls = 0 + coEvery { gateway.read() } answers { + calls++ + PerformanceReading( + calls * 1_000_000_000L, + mapOf("host" to calls * 100_000_000L), + 4, + 100, + 1000 + ) + } + var history = emptyList() + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + val job = backgroundScope.launch { useCase().collect { history = it } } + + // When + runCurrent() + advanceTimeBy(65_000) + runCurrent() + job.cancel() + runCurrent() + val countAtCancellation = calls + advanceTimeBy(5_000) + runCurrent() + + // Then + assertEquals(60, history.size) + assertEquals(countAtCancellation, calls) + } + + @Test + fun `given performance observation, platform operation is cancelled, expected no fallback sample or retry`() = + runTest { + // Given + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + every { preferences.observe() } returns settings + coEvery { gateway.read() } throws CancellationException("Stopped") + val values = mutableListOf>() + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + + // When + val job = backgroundScope.launch { useCase().collect { values.add(it) } } + runCurrent() + advanceTimeBy(5_000) + runCurrent() + + // Then + coVerify(exactly = 1) { gateway.read() } + job.cancel() + assertTrue(values.isEmpty()) + } + + @Test + fun `given performance observation, device CPU access is denied, expected app values retained and total CPU unavailable`() = + runTest { + // Given + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + every { preferences.observe() } returns settings + var calls = 0L + coEvery { gateway.read() } answers { + calls++ + PerformanceReading( + elapsedNanos = calls * 1_000_000_000L, + cpuTimeNanos = mapOf("host" to calls * 1_000_000_000L), + processorCount = 4, + residentBytes = 100, + totalMemoryBytes = 1000, + deviceCpu = Result.failure(SecurityException("Device CPU restricted")), + deviceUsedMemoryBytes = 800, + ) + } + var history = emptyList() + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + + // When + backgroundScope.launch { useCase().collect { history = it } } + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertEquals(25f, history.last().cpuPercent) + assertNull(history.last().deviceCpuPercent) + assertEquals(100L, history.last().residentBytes) + assertEquals(800L, history.last().deviceUsedMemoryBytes) + } + +} diff --git a/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/PerformanceObservationBoundaryTest.kt b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/PerformanceObservationBoundaryTest.kt new file mode 100644 index 000000000..2793adf83 --- /dev/null +++ b/domain/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/PerformanceObservationBoundaryTest.kt @@ -0,0 +1,240 @@ +package com.shifthackz.aisdv1.domain.usecase.generation + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.CpuUsageCounters +import com.shifthackz.aisdv1.domain.entity.PerformanceReading +import com.shifthackz.aisdv1.domain.entity.PerformanceSample +import com.shifthackz.aisdv1.domain.entity.Settings +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Checks counter discontinuities and preference changes at the sampler's public flow boundary. + * @author Dmitriy Moroz + */ +@OptIn(ExperimentalCoroutinesApi::class) +class PerformanceObservationBoundaryTest { + @Test + fun `given disabled performance observation, time passes, expected empty history and no platform reads`() = + runTest { + // Given + val observation = observeReadings(reading(1)) + observation.settings.value = Settings(shouldShowPerformanceOverlay = false) + + // When + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + // Then + assertEquals(listOf(emptyList()), observation.values) + coVerify(exactly = 0) { observation.gateway.read() } + } + + @Test + fun `given performance observation, unrelated setting changes, expected history and sampling cadence retained`() = + runTest { + // Given + val observation = observeReadings(reading(1), reading(2)) + runCurrent() + + // When + observation.settings.value = observation.settings.value.copy(languageCode = "de") + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertEquals(2, observation.values.last().size) + assertEquals(25f, observation.values.last().last().cpuPercent) + coVerify(exactly = 2) { observation.gateway.read() } + } + + @Test + fun `given performance observation, worker incarnation changes, expected new worker lifetime excluded from interval CPU`() = + runTest { + // Given + val observation = observeReadings( + reading(1).copy(cpuTimeNanos = mapOf("host" to 0L, "old-worker" to 900_000_000L)), + reading(2).copy( + cpuTimeNanos = mapOf( + "host" to 1_000_000_000L, + "new-worker" to 80_000_000_000L + ) + ), + ) + + // When + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertEquals(25f, observation.values.last().last().cpuPercent) + } + + @Test + fun `given performance observation, worker exits, expected host CPU continues without negative worker delta`() = + runTest { + // Given + val observation = observeReadings( + reading(1).copy(cpuTimeNanos = mapOf("host" to 0L, "worker" to 80_000_000_000L)), + reading(2).copy(cpuTimeNanos = mapOf("host" to 1_000_000_000L)), + ) + + // When + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertEquals(25f, observation.values.last().last().cpuPercent) + } + + @Test + fun `given performance observation, cumulative process CPU decreases, expected zero instead of negative usage`() = + runTest { + // Given + val observation = observeReadings(reading(2).copy(elapsedNanos = 0), reading(1)) + + // When + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertEquals(0f, observation.values.last().last().cpuPercent) + } + + @Test + fun `given performance observation, elapsed clock stalls or reverses then recovers, expected CPU gaps then fresh interval`() = + runTest { + // Given + val observation = observeReadings( + reading(1), reading(2).copy(elapsedNanos = 1_000_000_000L), + reading(3).copy(elapsedNanos = 0), reading(4).copy(elapsedNanos = 1_000_000_000L), + ) + + // When + runCurrent() + advanceTimeBy(3_000) + runCurrent() + + // Then + val samples = observation.values.last() + assertNull(samples[1].cpuPercent) + assertNull(samples[2].cpuPercent) + assertEquals(25f, samples[3].cpuPercent) + } + + @Test + fun `given performance observation, processor count is invalid and counters exceed capacity, expected CPU bounded to one hundred`() = + runTest { + // Given + val observation = observeReadings( + reading(1), + reading(2).copy( + processorCount = 0, + cpuTimeNanos = mapOf("host" to 90_000_000_000L) + ), + ) + + // When + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + // Then + assertEquals(100f, observation.values.last().last().cpuPercent) + } + + @Test + fun `given performance observation, device ticks stall reset or exceed capacity, expected missing invalid intervals and bounded valid usage`() = + runTest { + // Given + val observation = observeReadings( + reading(1).copy(deviceCpu = Result.success(CpuUsageCounters(10, 100))), + reading(2).copy(deviceCpu = Result.success(CpuUsageCounters(20, 100))), + reading(3).copy(deviceCpu = Result.success(CpuUsageCounters(0, 0))), + reading(4).copy(deviceCpu = Result.success(CpuUsageCounters(200, 100))), + ) + + // When + runCurrent() + advanceTimeBy(3_000) + runCurrent() + + // Then + val samples = observation.values.last() + assertNull(samples[1].deviceCpuPercent) + assertNull(samples[2].deviceCpuPercent) + assertEquals(100f, samples[3].deviceCpuPercent) + assertTrue(samples.drop(1).all { it.cpuPercent == 25f }) + } + + @Test + fun `given performance observation, device CPU becomes available, expected one baseline sample before total percentage`() = + runTest { + // Given + val observation = observeReadings( + reading(1), + reading(2).copy(deviceCpu = Result.success(CpuUsageCounters(10, 100))), + reading(3).copy(deviceCpu = Result.success(CpuUsageCounters(60, 200))), + ) + + // When + runCurrent() + advanceTimeBy(2_000) + runCurrent() + + // Then + val samples = observation.values.last() + assertNull(samples[0].deviceCpuPercent) + assertNull(samples[1].deviceCpuPercent) + assertEquals(50f, samples[2].deviceCpuPercent) + } + + private fun reading(second: Long) = PerformanceReading( + elapsedNanos = second * 1_000_000_000L, + cpuTimeNanos = mapOf("host" to second * 1_000_000_000L), + processorCount = 4, + residentBytes = second * 100, + totalMemoryBytes = 1000, + ) + + private fun TestScope.observeReadings(vararg readings: PerformanceReading): Observation { + val settings = MutableStateFlow(Settings()) + val preferences = mockk { every { observe() } returns settings } + val gateway = mockk() + coEvery { gateway.read() } returnsMany readings.toList() + val dispatcher = StandardTestDispatcher(testScheduler) + val dispatchers = mockk { every { io } returns dispatcher } + val observation = Observation(settings, gateway) + val useCase = ObserveGenerationPerformanceUseCaseImpl(preferences, gateway, dispatchers) + backgroundScope.launch { useCase().collect { observation.values.add(it) } } + return observation + } + + private class Observation( + val settings: MutableStateFlow, + val gateway: PerformanceGateway, + ) { + val values = mutableListOf>() + } +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt index db7341b65..e0baff622 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/di/DomainCoreModule.kt @@ -1,5 +1,7 @@ package com.shifthackz.aisdv1.domain.di +import com.shifthackz.aisdv1.domain.usecase.generation.ObserveGenerationPerformanceUseCase +import com.shifthackz.aisdv1.domain.usecase.generation.ObserveGenerationPerformanceUseCaseImpl import com.shifthackz.aisdv1.domain.usecase.generation.ObserveMnnProcessStatusUseCaseImpl import com.shifthackz.aisdv1.domain.usecase.generation.ObserveMnnProcessStatusUseCase @@ -281,6 +283,9 @@ import org.koin.dsl.module * @author Dmitriy Moroz */ val coreDomainModule = module { + factory { + ObserveGenerationPerformanceUseCaseImpl(get(), get(), get()) + } single { MnnBackendPolicyImpl(get()) } factory { ObserveMnnProcessStatusUseCaseImpl(get()) } single { NoOpNativeGenerationGateway } diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/CpuUsageCounters.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/CpuUsageCounters.kt new file mode 100644 index 000000000..4825b4648 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/CpuUsageCounters.kt @@ -0,0 +1,9 @@ +package com.shifthackz.aisdv1.domain.entity + +/** + * Cumulative device-wide CPU counters in the platform's native tick unit. + * @param activeTicks Time spent executing across all logical processors. + * @param totalTicks Execution and idle time across those same processors. + * @author Dmitriy Moroz + */ +data class CpuUsageCounters(val activeTicks: Long, val totalTicks: Long) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/PerformanceReading.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/PerformanceReading.kt new file mode 100644 index 000000000..2f43d5ded --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/PerformanceReading.kt @@ -0,0 +1,23 @@ +package com.shifthackz.aisdv1.domain.entity + +/** + * Raw application resource counters, sampled together off the UI thread. + * + * @param elapsedNanos Monotonic time used to measure the sampling interval. + * @param cpuTimeNanos Cumulative user and kernel CPU time by process lifetime identity. + * @param processorCount Logical processors used to normalize CPU utilization to device capacity. + * @param residentBytes App resident bytes, including Android inference PSS; iOS reports task RSS. + * @param deviceCpu Device-wide tick counters, or the actual platform access/read failure. + * @param deviceUsedMemoryBytes Device RAM in use, including the OS and other applications. + * @param totalMemoryBytes Physical memory available to the operating system. + * @author Dmitriy Moroz + */ +data class PerformanceReading( + val elapsedNanos: Long, + val cpuTimeNanos: Map, + val processorCount: Int, + val residentBytes: Long, + val totalMemoryBytes: Long, + val deviceCpu: Result = Result.failure(UnsupportedOperationException("Device CPU counters unavailable")), + val deviceUsedMemoryBytes: Long? = null, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/PerformanceSample.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/PerformanceSample.kt new file mode 100644 index 000000000..bc2cd071c --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/PerformanceSample.kt @@ -0,0 +1,20 @@ +package com.shifthackz.aisdv1.domain.entity + +/** + * One point in the visible generation resource history. Null values mark unavailable readings, + * leaving gaps in graphs rather than presenting failures as zero usage. + * + * @param cpuPercent App CPU utilization from 0 to 100, normalized across logical processors. + * @param residentBytes App resident bytes; Android apportions shared pages using PSS, iOS reports RSS. + * @param deviceCpuPercent Device-wide CPU usage from 0 to 100; null when restricted or unavailable. + * @param deviceUsedMemoryBytes RAM in use across the device, including the OS and other apps. + * @param totalMemoryBytes Device physical memory in bytes, not the app's allocation limit. + * @author Dmitriy Moroz + */ +data class PerformanceSample( + val cpuPercent: Float? = null, + val residentBytes: Long? = null, + val totalMemoryBytes: Long? = null, + val deviceCpuPercent: Float? = null, + val deviceUsedMemoryBytes: Long? = null, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ProcessPerformanceReading.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ProcessPerformanceReading.kt new file mode 100644 index 000000000..c2666fd74 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/ProcessPerformanceReading.kt @@ -0,0 +1,14 @@ +package com.shifthackz.aisdv1.domain.entity + +/** + * Resource counters read inside an inference process rather than through restricted cross-process files. + * @param identity Process incarnation used to avoid joining CPU counters across worker restarts. + * @param cpuTimeNanos Cumulative user and kernel CPU execution time. + * @param residentBytes Proportional resident process memory, including native allocations and model mappings. + * @author Dmitriy Moroz + */ +data class ProcessPerformanceReading( + val identity: String, + val cpuTimeNanos: Long, + val residentBytes: Long, +) diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt index 664dfe589..de56fdf70 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/entity/Settings.kt @@ -5,6 +5,7 @@ import com.shifthackz.aisdv1.core.common.schedulers.SchedulersToken /** * Observable application preferences including the selected generation source. * + * @param shouldShowPerformanceOverlay Whether generation dialogs display live app CPU and RAM history. * @param shouldDimScreen Whether active foreground generation lowers screen brightness. * @param providerSelectionRevision Durable source revision used to invalidate earlier queued work. * @@ -83,6 +84,7 @@ data class Settings( * @author Dmitriy Moroz */ val shouldDimScreen: Boolean = false, + val shouldShowPerformanceOverlay: Boolean = true, /** * Whether completed images are automatically persisted to the gallery. * diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NativeGenerationGateway.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NativeGenerationGateway.kt index bc378b97f..98f92228c 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NativeGenerationGateway.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NativeGenerationGateway.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.domain.gateway +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.LocalDiffusionStatus import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine import com.shifthackz.aisdv1.domain.entity.NativeGenerationStage @@ -13,6 +14,14 @@ import kotlinx.coroutines.flow.Flow * @author Dmitriy Moroz */ interface NativeGenerationGateway { + /** + * Requests resource counters from the currently owned child without starting a process. + * Returns null before submission or after teardown; transport/read failures propagate. + * Cancelling the read must not cancel inference or the connection's heartbeat. + * @author Dmitriy Moroz + */ + suspend fun readProcessPerformance(): ProcessPerformanceReading? + /** * Submits one immutable attempt; concurrent submissions fail without interrupting its owner. * diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NoOpNativeGenerationGateway.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NoOpNativeGenerationGateway.kt index 9d5f2a0d0..9c18b1ae0 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NoOpNativeGenerationGateway.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/NoOpNativeGenerationGateway.kt @@ -1,5 +1,6 @@ package com.shifthackz.aisdv1.domain.gateway +import com.shifthackz.aisdv1.domain.entity.ProcessPerformanceReading import com.shifthackz.aisdv1.domain.entity.LocalDiffusionStatus import com.shifthackz.aisdv1.domain.entity.NativeGenerationEngine import com.shifthackz.aisdv1.domain.entity.NativeGenerationStage @@ -13,6 +14,12 @@ import kotlinx.coroutines.flow.emptyFlow * @author Dmitriy Moroz */ internal object NoOpNativeGenerationGateway : NativeGenerationGateway { + /** + * No inference child exists on this platform. + * @author Dmitriy Moroz + */ + override suspend fun readProcessPerformance(): ProcessPerformanceReading? = null + /** * Fails explicitly because this platform has no Android inference process. * diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/PerformanceGateway.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/PerformanceGateway.kt new file mode 100644 index 000000000..9e9fccf40 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/gateway/PerformanceGateway.kt @@ -0,0 +1,16 @@ +package com.shifthackz.aisdv1.domain.gateway + +import com.shifthackz.aisdv1.domain.entity.PerformanceReading + +/** + * Reads platform app resource counters without retaining a sampler or starting background work. + * @author Dmitriy Moroz + */ +interface PerformanceGateway { + /** + * Returns current counters for the host and its inference processes. Platform read failures + * propagate to the observing use case; callers must invoke this operation off the UI thread. + * @author Dmitriy Moroz + */ + suspend fun read(): PerformanceReading +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt index d9b98c8b3..ed563998f 100644 --- a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/preference/PreferenceManager.kt @@ -435,6 +435,13 @@ interface PreferenceManager { */ var shouldDimScreen: Boolean + /** + * Enables live CPU and resident-memory graphs in foreground generation progress dialogs. + * Defaults to true; an explicitly disabled preference prevents resource sampling. + * @author Dmitriy Moroz + */ + var shouldShowPerformanceOverlay: Boolean + /** * Number of background processes tracked by the existing work UI. * diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCase.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCase.kt new file mode 100644 index 000000000..9786fcf43 --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCase.kt @@ -0,0 +1,18 @@ +package com.shifthackz.aisdv1.domain.usecase.generation + +import com.shifthackz.aisdv1.domain.entity.PerformanceSample +import kotlinx.coroutines.flow.Flow + +/** + * Supplies preference-controlled resource history for a visible generation progress dialog. + * @author Dmitriy Moroz + */ +interface ObserveGenerationPerformanceUseCase { + /** + * Starts an independent one-second sampler on collection, retaining at most 60 samples. + * Emits an empty history when disabled and stops sampling on cancellation. The first CPU + * point is unavailable until two readings establish an interval. + * @author Dmitriy Moroz + */ + operator fun invoke(): Flow> +} diff --git a/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCaseImpl.kt b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCaseImpl.kt new file mode 100644 index 000000000..7932cb98e --- /dev/null +++ b/domain/src/commonMain/kotlin/com/shifthackz/aisdv1/domain/usecase/generation/ObserveGenerationPerformanceUseCaseImpl.kt @@ -0,0 +1,84 @@ +package com.shifthackz.aisdv1.domain.usecase.generation + +import com.shifthackz.aisdv1.core.common.schedulers.DispatchersProvider +import com.shifthackz.aisdv1.domain.entity.PerformanceReading +import com.shifthackz.aisdv1.domain.entity.PerformanceSample +import com.shifthackz.aisdv1.domain.gateway.PerformanceGateway +import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.isActive + +/** + * Samples only during visible enabled collection, with bounded history and explicit unavailable + * points on transient platform failures. Cancellation stops sampling without a fallback point. + * + * @param preferences Persisted overlay flag and its invalidation stream. + * @param gateway Platform counters, including Android inference children. + * @param dispatchersProvider IO dispatcher for system and process-file reads. + * @author Dmitriy Moroz + */ +@OptIn(ExperimentalCoroutinesApi::class) +internal class ObserveGenerationPerformanceUseCaseImpl( + private val preferences: PreferenceManager, + private val gateway: PerformanceGateway, + private val dispatchersProvider: DispatchersProvider, +) : ObserveGenerationPerformanceUseCase { + override fun invoke() = preferences.observe() + .map { it.shouldShowPerformanceOverlay } + .distinctUntilChanged() + .flatMapLatest { isEnabled -> + if (!isEnabled) flowOf(emptyList()) else history() + } + .flowOn(dispatchersProvider.io) + + private fun history() = flow { + var previous: PerformanceReading? = null + var samples = emptyList() + while (currentCoroutineContext().isActive) { + val sample = try { + val reading = gateway.read() + val interval = previous?.let { reading.elapsedNanos - it.elapsedNanos } ?: 0L + val cpu = previous?.takeIf { interval > 0L }?.let { baseline -> + val delta = reading.cpuTimeNanos.entries.sumOf { (identity, time) -> + baseline.cpuTimeNanos[identity]?.let { (time - it).coerceAtLeast(0L) } ?: 0L + } + (100.0 * delta / interval / reading.processorCount.coerceAtLeast(1)) + .toFloat().coerceIn(0f, 100f) + } + val deviceCpu = reading.deviceCpu.getOrNull()?.let { current -> + previous?.deviceCpu?.getOrNull()?.let { baseline -> + val total = current.totalTicks - baseline.totalTicks + val active = current.activeTicks - baseline.activeTicks + if (total > 0 && active >= 0) (100.0 * active / total).toFloat() + .coerceIn(0f, 100f) else null + } + } + previous = reading + PerformanceSample( + cpu, + reading.residentBytes, + reading.totalMemoryBytes, + deviceCpu, + reading.deviceUsedMemoryBytes + ) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + previous = null + PerformanceSample() + } + samples = (samples + sample).takeLast(60) + emit(samples) + delay(1_000) + } + } +} diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt index d5bb9da79..977285cc2 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdApp.kt @@ -31,6 +31,7 @@ import com.shifthackz.aisdv1.presentation.components.extensions.generationBright import com.shifthackz.aisdv1.core.common.appbuild.BuildInfoProvider import com.shifthackz.aisdv1.core.extensions.clearFocusOnTap import com.shifthackz.aisdv1.domain.preference.PreferenceManager +import com.shifthackz.aisdv1.domain.usecase.generation.ObserveGenerationPerformanceUseCase import org.koin.mp.KoinPlatform.getKoin import com.shifthackz.aisdv1.presentation.components.platform.rememberExternalUrlLauncher import com.shifthackz.aisdv1.presentation.generation.img2img.ImageToImageIntent @@ -136,6 +137,7 @@ fun AiSdApp( buildInfoProvider = koin.get(), preferenceManager = preferenceManager, shouldShowHomeChrome = selectedHomeRoute != null, + observePerformance = remember(koin) { koin.get() }, textToImageViewModel = textToImageViewModel, imageToImageViewModel = imageToImageViewModel, ) diff --git a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt index b8f4c7f0d..96727e31f 100644 --- a/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt +++ b/presentation/app/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/app/AiSdAppRoutes.kt @@ -68,6 +68,8 @@ import com.shifthackz.aisdv1.presentation.app.onboarding.FormPageContent import com.shifthackz.aisdv1.presentation.app.onboarding.ProviderPageContent import com.shifthackz.aisdv1.presentation.app.onboarding.LocalDiffusionPageContent import com.shifthackz.aisdv1.presentation.app.onboarding.LookAndFeelPageContent +import com.shifthackz.aisdv1.domain.usecase.generation.ObserveGenerationPerformanceUseCase +import com.shifthackz.aisdv1.presentation.generation.performance.GenerationPerformanceOverlay import org.koin.core.Koin import org.koin.core.parameter.parametersOf @@ -85,6 +87,7 @@ import org.koin.core.parameter.parametersOf * @param buildInfoProvider Build metadata consumed by scaffold-level UI. * @param preferenceManager Preferences source consumed by scaffold-level UI. * @param shouldShowHomeChrome Whether bottom tabs and home-level chrome should be visible. + * @param observePerformance Cold opt-in sampler shared with visible generation dialogs. * @param textToImageViewModel Shared Text-to-Image ViewModel kept alive with its tab. * @param imageToImageViewModel Shared Image-to-Image ViewModel kept alive with its tab. * @@ -99,6 +102,7 @@ internal fun HomeRoutesScaffold( preferenceManager: PreferenceManager, modifier: Modifier = Modifier, shouldShowHomeChrome: Boolean = true, + observePerformance: ObserveGenerationPerformanceUseCase, textToImageViewModel: TextToImageViewModel, imageToImageViewModel: ImageToImageViewModel, ) { @@ -122,6 +126,10 @@ internal fun HomeRoutesScaffold( state = state, processIntent = processIntent, useDrawerNavigation = true, + performanceOverlay = { + val history = remember(observePerformance) { observePerformance() } + GenerationPerformanceOverlay(history) + }, ) } } @@ -136,6 +144,10 @@ internal fun HomeRoutesScaffold( state = state, processIntent = processIntent, useDrawerNavigation = true, + performanceOverlay = { + val history = remember(observePerformance) { observePerformance() } + GenerationPerformanceOverlay(history) + }, ) } } diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/DialogContent.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/DialogContent.kt index f5c12eb02..f1276079a 100644 --- a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/DialogContent.kt +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/DialogContent.kt @@ -18,7 +18,6 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -192,15 +191,14 @@ fun ProgressDialogContent( Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 16.dp)) { Text( text = title, - style = TextStyle(fontSize = 16.sp), - fontWeight = FontWeight.Bold, - color = AlertDialogDefaults.titleContentColor, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onBackground, ) Text( modifier = Modifier.padding(top = 14.dp), text = subTitle, - style = TextStyle(fontSize = 14.sp), - color = AlertDialogDefaults.textContentColor, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onBackground, ) ProgressDialogStatusContent( waitTimeText = waitTimeText, @@ -210,7 +208,7 @@ fun ProgressDialogContent( modifier = Modifier .fillMaxWidth() .padding(top = 8.dp), - color = AlertDialogDefaults.iconContentColor, + color = MaterialTheme.colorScheme.primary, ) content?.invoke() } @@ -235,13 +233,13 @@ fun ProgressDialogStatusContent( Column(modifier.padding(vertical = 4.dp)) { Text( text = waitTimeText.orEmpty(), - style = TextStyle(fontSize = 12.sp), - color = AlertDialogDefaults.textContentColor, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onBackground, ) Text( text = statusText.orEmpty(), - style = TextStyle(fontSize = 12.sp), - color = AlertDialogDefaults.textContentColor, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onBackground, ) } } diff --git a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt index 8f8fbeedd..e51fec09d 100644 --- a/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt +++ b/presentation/components/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/components/widget/dialog/ProgressDialog.kt @@ -1,5 +1,7 @@ package com.shifthackz.aisdv1.presentation.components.widget.dialog +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.window.Dialog @@ -53,7 +55,8 @@ fun ProgressDialog( ), ) { GeneratingProgressDialogContent( - modifier = Modifier.generationBrightnessInteraction(), + modifier = Modifier.generationBrightnessInteraction() + .verticalScroll(rememberScrollState()), title = title, subTitle = subTitle, waitTimeSeconds = waitTimeSeconds, diff --git a/presentation/generation/build.gradle.kts b/presentation/generation/build.gradle.kts index 6b7886d85..ef6c48166 100644 --- a/presentation/generation/build.gradle.kts +++ b/presentation/generation/build.gradle.kts @@ -19,6 +19,7 @@ android { kotlin { sourceSets { commonMain.dependencies { + implementation(libs.androidx.lifecycle.compose) implementation(project(":core:common")) implementation(project(":core:localization")) implementation(project(":core:ui")) diff --git a/presentation/generation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/generation/model/CoreMlProgressModalTest.kt b/presentation/generation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/generation/model/CoreMlProgressModalTest.kt new file mode 100644 index 000000000..912cecb4e --- /dev/null +++ b/presentation/generation/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/generation/model/CoreMlProgressModalTest.kt @@ -0,0 +1,42 @@ +package com.shifthackz.aisdv1.presentation.generation.model + +import com.shifthackz.aisdv1.core.common.platform.Platform +import com.shifthackz.aisdv1.domain.entity.ServerSource +import com.shifthackz.aisdv1.presentation.generation.txt2img.TextToImageState +import com.shifthackz.aisdv1.presentation.generation.txt2img.progressModal +import com.shifthackz.aisdv1.presentation.generation.img2img.ImageToImageState +import com.shifthackz.aisdv1.presentation.generation.img2img.progressModal +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Verifies Core ML cancellation remains available without the legacy local debug switch. + * @author Dmitriy Moroz */ +class CoreMlProgressModalTest { + @Test + fun `given iOS Core ML text generation, legacy cancellation flag is off, expected cancel remains available`() { + // Given + val state = + TextToImageState(platform = Platform.IOS, mode = ServerSource.LOCAL_APPLE_CORE_ML) + + // When + val modal = + state.progressModal(canCancelLocalGeneration = false) as GenerationModal.Generating + + // Then + assertTrue(modal.canCancel) + } + + @Test + fun `given iOS Core ML image generation, legacy cancellation flag is off, expected cancel remains available`() { + // Given + val state = + ImageToImageState(platform = Platform.IOS, mode = ServerSource.LOCAL_APPLE_CORE_ML) + + // When + val modal = + state.progressModal(canCancelLocalGeneration = false) as GenerationModal.Generating + + // Then + assertTrue(modal.canCancel) + } +} diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageContent.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageContent.kt index 47134f077..766fbf5f2 100644 --- a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageContent.kt +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageContent.kt @@ -92,6 +92,7 @@ data class ImageToImageStrings( * @param processIntent Publishes field, generation, export and navigation requests. * @param modifier Layout modifiers for the form scaffold. * @param strings Localized labels and provider capability explanations. + * @param performanceOverlay Optional live resource panel supplied by the application root. * @param useDrawerNavigation Whether the toolbar opens the home drawer instead of navigating back. * * @author Dmitriy Moroz @@ -103,6 +104,7 @@ fun ImageToImageContent( modifier: Modifier = Modifier, strings: ImageToImageStrings = ImageToImageStrings(), useDrawerNavigation: Boolean = false, + performanceOverlay: @Composable () -> Unit = {}, ) { val promptChipTextFieldState = remember { mutableStateOf(TextFieldValue()) } val negativePromptChipTextFieldState = remember { mutableStateOf(TextFieldValue()) } @@ -289,6 +291,7 @@ fun ImageToImageContent( ) } GenerationModalRenderer( + performanceOverlay = performanceOverlay, screenModal = state.screenModal, onDismissRequest = { processIntent(ImageToImageIntent.DismissModal) }, onCancelGeneration = { processIntent(ImageToImageIntent.CancelGeneration) }, diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageViewModelHelpers.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageViewModelHelpers.kt index af5efec00..806767dd7 100644 --- a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageViewModelHelpers.kt +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/img2img/ImageToImageViewModelHelpers.kt @@ -138,7 +138,7 @@ internal fun ImageToImageState.progressModal( } else { null }, - canCancel = canCancelLocalGeneration || (platform == Platform.ANDROID && mode in setOf( + canCancel = mode == ServerSource.LOCAL_APPLE_CORE_ML || canCancelLocalGeneration || (platform == Platform.ANDROID && mode in setOf( ServerSource.LOCAL_MICROSOFT_ONNX, ServerSource.LOCAL_GOOGLE_MEDIA_PIPE, ServerSource.LOCAL_STABLE_DIFFUSION_CPP, diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/modal/GenerationModalRenderer.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/modal/GenerationModalRenderer.kt index d8f2ae7c5..777a6d002 100644 --- a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/modal/GenerationModalRenderer.kt +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/modal/GenerationModalRenderer.kt @@ -33,6 +33,7 @@ import com.shifthackz.aisdv1.presentation.components.widget.dialog.ProgressDialo /** * Renders the active generation decision, progress or result dialog and forwards its actions. * + * @param performanceOverlay Optional resource panel, composed only during generation progress. * @param screenModal Captured dialog state, including provider progress units. * @param onDismissRequest Closes a dismissible dialog. * @param onCancelGeneration Requests cancellation of the active generation owner. @@ -58,6 +59,7 @@ fun GenerationModalRenderer( onSkipBenchmarkRequest: () -> Unit, onBenchmarkContinueRequest: () -> Unit, onBenchmarkDoNotAskRequest: () -> Unit, + performanceOverlay: @Composable () -> Unit = {}, ) { when (screenModal) { GenerationModal.None -> Unit @@ -66,10 +68,9 @@ fun GenerationModalRenderer( canDismiss = false, waitTimeSeconds = screenModal.hordeProcessStatus?.waitTimeSeconds, positionInQueue = screenModal.hordeProcessStatus?.queuePosition, - content = screenModal.canCancel.takeIf { it }?.let { - { - ProgressDialogCancelButton(onClick = onCancelGeneration) - } + content = { + performanceOverlay() + if (screenModal.canCancel) ProgressDialogCancelButton(onClick = onCancelGeneration) }, ) @@ -81,10 +82,9 @@ fun GenerationModalRenderer( overallPercentage = screenModal.overallPercentage, subTitle = (screenModal.nativeStage?.localizedText() ?: Localization.string("communicating_progress_sub_title")).asUiText(), - content = screenModal.canCancel.takeIf { it }?.let { - { - ProgressDialogCancelButton(onClick = onCancelGeneration) - } + content = { + performanceOverlay() + if (screenModal.canCancel) ProgressDialogCancelButton(onClick = onCancelGeneration) }, ) diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/GenerationPerformanceOverlay.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/GenerationPerformanceOverlay.kt new file mode 100644 index 000000000..1cf6744bb --- /dev/null +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/GenerationPerformanceOverlay.kt @@ -0,0 +1,92 @@ +package com.shifthackz.aisdv1.presentation.generation.performance + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +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.Modifier +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.repeatOnLifecycle +import com.shifthackz.aisdv1.core.localization.Localization +import com.shifthackz.aisdv1.core.mvi.LocalMviVisibility +import com.shifthackz.aisdv1.domain.entity.PerformanceSample +import kotlinx.coroutines.flow.Flow +import kotlin.math.roundToInt + +/** + * Collects resource history only while the generation dialog's tab is visible and resumed. + * Removing the dialog or backgrounding the app cancels collection and discards its history. + * + * @param history Cold preference-controlled sampler supplied by the application composition root. + * @param modifier Layout applied to the resource panel. + * @author Dmitriy Moroz + */ +@Composable +fun GenerationPerformanceOverlay( + history: Flow>, + modifier: Modifier = Modifier, +) { + val isVisible = LocalMviVisibility.current + val lifecycle = LocalLifecycleOwner.current.lifecycle + var samples by remember(history) { mutableStateOf(emptyList()) } + LaunchedEffect(history, isVisible, lifecycle) { + samples = emptyList() + if (isVisible) lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) { + try { + history.collect { samples = it } + } finally { + samples = emptyList() + } + } + } + val latest = samples.lastOrNull() ?: return + val capacity = latest.totalMemoryBytes + Column( + modifier = modifier.fillMaxWidth().padding(top = 16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + PerformanceResourceGraph( + label = Localization.string("performance_cpu"), + appValue = latest.cpuPercent?.let { "${it.roundToInt()}%" }, + totalValue = latest.deviceCpuPercent?.let { "${it.roundToInt()}%" }, + appValues = samples.map { it.cpuPercent?.div(100f) }, + totalValues = samples.map { it.deviceCpuPercent?.div(100f) }, + ) + PerformanceResourceGraph( + label = Localization.string("performance_ram"), + appValue = memoryValue(latest.residentBytes, capacity), + totalValue = memoryValue(latest.deviceUsedMemoryBytes, capacity), + appValues = samples.map { fraction(it.residentBytes, it.totalMemoryBytes) }, + totalValues = samples.map { fraction(it.deviceUsedMemoryBytes, it.totalMemoryBytes) }, + ) + PerformanceLegend() + } +} + +/** + * Formats a known used/capacity pair in binary megabytes, preserving unavailable samples. + * @param used Resident app bytes or device-wide used bytes. + * @param total Device physical capacity, not a per-process allocation limit. + * @author Dmitriy Moroz + */ +private fun memoryValue(used: Long?, total: Long?): String? = + if (used != null && total != null) Localization.string( + "performance_memory_value", (used / 1_048_576).toString(), (total / 1_048_576).toString(), + ) else null + +/** + * Maps byte counters to the graph's shared physical-capacity scale. + * @param used RAM in use for one series, or null for an unavailable reading. + * @param total Device capacity in bytes. + * @author Dmitriy Moroz + */ +private fun fraction(used: Long?, total: Long?): Float? = + if (used != null && total != null && total > 0) used.toFloat() / total else null diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/PerformanceLegend.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/PerformanceLegend.kt new file mode 100644 index 000000000..0a941ba9b --- /dev/null +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/PerformanceLegend.kt @@ -0,0 +1,67 @@ +package com.shifthackz.aisdv1.presentation.generation.performance + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.size +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization + +/** + * Shares one accessible legend across CPU and RAM, using the same colors and stroke styles. + * @param modifier Layout applied to the legend row. + * @author Dmitriy Moroz + */ +@Composable +internal fun PerformanceLegend(modifier: Modifier = Modifier) { + val appColor = MaterialTheme.colorScheme.primary + val totalColor = MaterialTheme.colorScheme.onBackground + Row( + modifier, + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Canvas(Modifier.size(18.dp, 8.dp)) { + drawLine( + appColor, + Offset(0f, size.height / 2), + Offset(size.width, size.height / 2), + 2.dp.toPx() + ) + } + Text( + Localization.string("performance_this_app"), + style = MaterialTheme.typography.bodySmall, + color = appColor + ) + } + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Canvas(Modifier.size(18.dp, 8.dp)) { + drawLine( + totalColor, + Offset(0f, size.height / 2), + Offset(size.width, size.height / 2), + 2.dp.toPx() + ) + } + Text( + Localization.string("performance_total"), + style = MaterialTheme.typography.bodySmall, + color = totalColor + ) + } + } +} diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/PerformanceResourceGraph.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/PerformanceResourceGraph.kt new file mode 100644 index 000000000..271f7cf19 --- /dev/null +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/performance/PerformanceResourceGraph.kt @@ -0,0 +1,141 @@ +package com.shifthackz.aisdv1.presentation.generation.performance + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import com.shifthackz.aisdv1.core.localization.Localization + +/** + * Displays two resource series on a fixed 60-sample, zero-to-capacity scale. The app uses the + * theme accent; device totals use foreground color. Both series use solid traces. + * @param label Localized resource name. + * @param appValue Current app reading with its unit; null hides an unavailable value. + * @param totalValue Current device-wide reading with its unit; null hides an unavailable value. + * @param appValues Oldest-to-newest normalized app points, at most 60; nulls leave gaps. + * @param totalValues Device-wide points in the same time window and scale. + * @param modifier Layout applied to the metric and plot. + * @author Dmitriy Moroz + */ +@Composable +internal fun PerformanceResourceGraph( + label: String, + appValue: String?, + totalValue: String?, + appValues: List, + totalValues: List, + modifier: Modifier = Modifier, +) { + val appColor = MaterialTheme.colorScheme.primary + val totalColor = MaterialTheme.colorScheme.onBackground + val gridColor = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.12f) + val appLabel = Localization.string("performance_this_app") + val totalLabel = Localization.string("performance_total") + Column(modifier = modifier.semantics { + contentDescription = listOfNotNull( + label, + appValue?.let { "$appLabel: $it" }, + totalValue?.let { "$totalLabel: $it" }, + ).joinToString(", ") + }, verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + label, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onBackground + ) + Column(horizontalAlignment = Alignment.End) { + appValue?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = appColor + ) + } + totalValue?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = totalColor + ) + } + } + } + Canvas(Modifier.fillMaxWidth().height(48.dp)) { + for (line in 0..4) { + val y = size.height * line / 4 + drawLine(gridColor, Offset(0f, y), Offset(size.width, y), 1.dp.toPx()) + } + for (line in 0..6) { + val x = size.width * line / 6 + drawLine(gridColor, Offset(x, 0f), Offset(x, size.height), 1.dp.toPx()) + } + drawSeries(totalValues, totalColor) + drawSeries(appValues, appColor) + } + } +} + +/** + * Draws a translucent area beneath known points and a crisp trace above it. + * Each contiguous segment closes to the baseline separately, preserving gaps for missing readings. + * @param values Normalized series within the fixed 60-point viewport. + * @param color Theme role shared with the numeric value and legend. + * @author Dmitriy Moroz + */ +private fun DrawScope.drawSeries( + values: List, + color: Color, +) { + val path = Path() + val area = Path() + var lastX = 0f + var hasPreviousPoint = false + values.forEachIndexed { index, value -> + if (value == null) { + if (hasPreviousPoint) { + area.lineTo(lastX, size.height) + area.close() + } + hasPreviousPoint = false + } else { + val x = size.width * (60 - values.size + index) / 59f + val y = size.height * (1 - value.coerceIn(0f, 1f)) + if (hasPreviousPoint) { + path.lineTo(x, y) + area.lineTo(x, y) + } else { + path.moveTo(x, y) + area.moveTo(x, size.height) + area.lineTo(x, y) + } + lastX = x + hasPreviousPoint = true + } + } + if (hasPreviousPoint) { + area.lineTo(lastX, size.height) + area.close() + } + drawPath(area, color.copy(alpha = 0.16f)) + drawPath(path, color, style = Stroke(width = 2.dp.toPx())) +} diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageContent.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageContent.kt index 303a993fe..5fc84358d 100644 --- a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageContent.kt +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageContent.kt @@ -71,6 +71,7 @@ data class TextToImageStrings( * @param processIntent Dispatches user actions to the owning text-to-image flow. * @param modifier Layout bounds and insets supplied by the screen host. * @param strings Localized screen labels that previews and tests can override. + * @param performanceOverlay Optional live resource panel supplied by the application root. * @param useDrawerNavigation Whether the top app bar opens the app drawer instead of navigating back. * * @author Dmitriy Moroz @@ -82,6 +83,7 @@ fun TextToImageContent( modifier: Modifier = Modifier, strings: TextToImageStrings = TextToImageStrings(), useDrawerNavigation: Boolean = false, + performanceOverlay: @Composable () -> Unit = {}, ) { val promptChipTextFieldState = remember { mutableStateOf(TextFieldValue()) } val negativePromptChipTextFieldState = remember { mutableStateOf(TextFieldValue()) } @@ -252,6 +254,7 @@ fun TextToImageContent( ) } GenerationModalRenderer( + performanceOverlay = performanceOverlay, screenModal = state.screenModal, onDismissRequest = { processIntent(TextToImageIntent.DismissModal) }, onCancelGeneration = { processIntent(TextToImageIntent.CancelGeneration) }, diff --git a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageViewModelHelpers.kt b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageViewModelHelpers.kt index 693be62e9..5834dd963 100644 --- a/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageViewModelHelpers.kt +++ b/presentation/generation/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/generation/txt2img/TextToImageViewModelHelpers.kt @@ -138,7 +138,7 @@ internal fun TextToImageState.progressModal( mode == ServerSource.LOCAL_APPLE_CORE_ML -> GenerationModal.Generating( title = Localization.string("communicating_core_ml_title").asUiText(), - canCancel = canCancelLocalGeneration, + canCancel = true, ) mode == ServerSource.LOCAL_APPLE_BONSAI -> GenerationModal.Generating( diff --git a/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt b/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt index 5fbc5e8ee..3ecce9764 100644 --- a/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt +++ b/presentation/settings/src/androidUnitTest/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModelTest.kt @@ -362,6 +362,39 @@ class SettingsViewModelTest { } + @Test + fun `given performance overlay settings, preference snapshots change, expected switch follows saved choice`() = + runTest { + // Given + val viewModel = createViewModel() + advanceUntilIdle() + assertTrue(viewModel.state.value.shouldShowPerformanceOverlay) + + // When + settings.value = settings.value.copy(shouldShowPerformanceOverlay = false) + advanceUntilIdle() + + // Then + assertEquals(false, viewModel.state.value.shouldShowPerformanceOverlay) + } + + @Test + fun `given performance overlay settings, switch is disabled then enabled, expected exact choices persisted`() = + runTest { + // Given + val viewModel = createViewModel() + advanceUntilIdle() + + // When + viewModel.processIntent(SettingsIntent.UpdateFlag.PerformanceOverlay(false)) + viewModel.processIntent(SettingsIntent.UpdateFlag.PerformanceOverlay(true)) + advanceUntilIdle() + + // Then + verify(exactly = 1) { preferenceManager.shouldShowPerformanceOverlay = false } + verify(exactly = 1) { preferenceManager.shouldShowPerformanceOverlay = true } + } + private fun TestScope.createViewModel( buildInfoProvider: BuildInfoProvider = TestBuildInfoProvider, ): SettingsViewModel { diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt index 2de51f2f7..06accd214 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsContentTypes.kt @@ -17,6 +17,7 @@ internal fun SettingsListItem.contentType(): SettingsContentType = when (this) { SettingsListItem.COMMUNITY_HEADER, SettingsListItem.INFO_HEADER -> SettingsContentType.HEADER + SettingsListItem.PERFORMANCE_OVERLAY, SettingsListItem.DIM_SCREEN, SettingsListItem.NNAPI, SettingsListItem.BACKGROUND_GENERATION, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt index 8b9ae4d5d..9cfb22771 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsIntent.kt @@ -166,6 +166,13 @@ sealed interface SettingsIntent : MviIntent { */ data class DimScreen(override val flag: Boolean) : UpdateFlag + /** + * Persists visibility of resource graphs in generation dialogs. + * @param flag Whether the overlay is enabled. + * @author Dmitriy Moroz + */ + data class PerformanceOverlay(override val flag: Boolean) : UpdateFlag + data class MonitorConnection(override val flag: Boolean) : UpdateFlag data class AutoSaveResult(override val flag: Boolean) : UpdateFlag diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt index dabbba5ad..d7aacc62b 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItem.kt @@ -21,6 +21,7 @@ internal enum class SettingsListItem { BACKGROUND_WARNING, DEBUG_MENU, APP_HEADER, + PERFORMANCE_OVERLAY, DIM_SCREEN, DIM_SCREEN_WARNING, MONITOR_CONNECTION, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt index 1425ef953..7f8a70be6 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsListItems.kt @@ -41,6 +41,7 @@ internal fun settingsListItems( } if (!state.loading && state.developerMode) add(SettingsListItem.DEBUG_MENU) add(SettingsListItem.APP_HEADER) + add(SettingsListItem.PERFORMANCE_OVERLAY) add(SettingsListItem.DIM_SCREEN) if (!state.loading && state.backgroundGeneration) add(SettingsListItem.DIM_SCREEN_WARNING) if (state.showMonitorConnectionOption) add(SettingsListItem.MONITOR_CONNECTION) diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt index 86cb23061..98583963a 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsState.kt @@ -27,6 +27,7 @@ import com.shifthackz.aisdv1.domain.entity.ServerSourceType * @param stabilityAiCredits Current Stability AI balance shown in Settings. * @param localUseNNAPI Whether ONNX local diffusion should use NNAPI acceleration. * @param backgroundGenerationAvailable Whether background generation is supported by this target. + * @param shouldShowPerformanceOverlay Whether generation dialogs display live app CPU and RAM history. * @param shouldDimScreen Whether active foreground generation dims the screen. * @param backgroundGeneration Whether background generation is currently enabled. * @param monitorConnectivity Whether server connectivity monitoring is enabled. @@ -62,6 +63,7 @@ data class SettingsState( val backgroundGenerationAvailable: Boolean = false, val backgroundGeneration: Boolean = false, val shouldDimScreen: Boolean = false, + val shouldShowPerformanceOverlay: Boolean = true, val monitorConnectivity: Boolean = false, val autoSaveAiResults: Boolean = false, val saveToMediaStore: Boolean = false, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt index 7bbc52eab..4c387bcc3 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/SettingsViewModel.kt @@ -173,6 +173,7 @@ class SettingsViewModel( stabilityAiCredits = credits, localUseNNAPI = settings.localUseNNAPI, shouldDimScreen = settings.shouldDimScreen, + shouldShowPerformanceOverlay = settings.shouldShowPerformanceOverlay, backgroundGenerationAvailable = platformActions.supportsBackgroundGeneration, backgroundGeneration = settings.backgroundGeneration && platformActions.supportsBackgroundGeneration, @@ -271,6 +272,10 @@ class SettingsViewModel( preferenceManager.autoSaveAiResults = intent.flag } + is SettingsIntent.UpdateFlag.PerformanceOverlay -> { + preferenceManager.shouldShowPerformanceOverlay = intent.flag + } + is SettingsIntent.UpdateFlag.DimScreen -> { preferenceManager.shouldDimScreen = intent.flag } diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt index eaf8c6bfe..c005faf71 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/content/SettingsContent.kt @@ -78,6 +78,7 @@ internal fun ContentSettingsState( SettingsListItem.BACKGROUND_WARNING, SettingsListItem.DEBUG_MENU, SettingsListItem.APP_HEADER, + SettingsListItem.PERFORMANCE_OVERLAY, SettingsListItem.DIM_SCREEN, SettingsListItem.DIM_SCREEN_WARNING, SettingsListItem.MONITOR_CONNECTION, diff --git a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt index bc4604763..d31e1e888 100644 --- a/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt +++ b/presentation/settings/src/commonMain/kotlin/com/shifthackz/aisdv1/presentation/settings/section/SettingsServerSection.kt @@ -212,6 +212,17 @@ internal fun SettingsServerSection( ) } + SettingsListItem.PERFORMANCE_OVERLAY -> { + SettingsToggleItem( + modifier = itemModifier, + isLoading = state.loading, + startIcon = Icons.Default.Speed, + text = text("settings_item_performance_overlay"), + isChecked = state.shouldShowPerformanceOverlay, + onCheckedChange = { processIntent(SettingsIntent.UpdateFlag.PerformanceOverlay(it)) }, + ) + } + SettingsListItem.DIM_SCREEN -> { SettingsToggleItem( modifier = itemModifier,