Private notes summarizer with on-device Gemini Nano

Build a private notes app in Kotlin with Jetpack Compose and Room that summarises and proofreads text on-device using ML Kit GenAI and Gemini Nano. About 34 hours.

What you will build

The finished app lets a user write, store, and manage private notes entirely on their phone. Each note can be summarised into bullet points or proofread without leaving the device, using the ML Kit GenAI Summarization and Proofreading APIs, which run Gemini Nano through Android AICore on supported devices only. The app checks feature status before any AI call, downloads the feature when needed with progress, and shows a clear fallback when the device is unsupported. All note text stays in Room; nothing is sent to a server unless the user explicitly opts into a cloud path behind a consent screen.

For an employer, this project shows you can integrate on-device generative AI with proper feature detection, handle async model downloads, respect platform limits (foreground only, per-app quotas), design a clean fallback, test with a fake interface, and measure real latency. It proves comfort with Jetpack Compose state, Room persistence, Kotlin coroutines, and the trade-offs between on-device and cloud AI.

Skills you practise

  • On-device feature detection and model download with ML Kit GenAI
  • Jetpack Compose state management with StateFlow and MVI
  • Room persistence for offline-first note storage
  • Bridging callback and future-based APIs into coroutines and Flow
  • Fallback design and explicit user consent for cloud paths
  • Testing with a fake interface instead of the real model
  • Latency measurement and privacy-safe logging on mobile

Architecture

The app follows unidirectional data flow. Compose screens (note list, note editor, summary sheet) read a StateFlow<UiState> from a ViewModel. The ViewModel talks to a NoteAi interface; the production implementation wraps ML Kit's Summarization.getClient(...) and Proofreading.getClient(...), while tests inject a FakeNoteAi. All note text lives in Room behind a NoteRepository; the ViewModel never calls Room directly.

Before showing the AI buttons, the ViewModel asks NoteAi for the feature status, which comes from checkFeatureStatus() and is one of FeatureStatus.UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, or AVAILABLE. When it is DOWNLOADABLE, the UI offers a download button that calls downloadFeature with a DownloadCallback, bridged into a Flow of progress events. When it is UNAVAILABLE, the UI shows a fallback message and, only if the user has consented, routes to an optional cloud path through your own backend. Inference runs only while the app is the top foreground app; AICore blocks background use and enforces per-app quotas, which surface as GenAiException error codes. Latency is measured at the NoteAi boundary and logged without note text.

Module or layerResponsibility
UI (Compose screens)Note list, editor, and summary screens. Render UiState, emit user intents. No business logic.
ViewModel + MVIHolds UiState as a StateFlow. Calls NoteAi and NoteRepository. Maps results and error codes to UI states. Starts AI work only from user actions on a visible screen.
NoteAi interface + implementationsAbstraction over ML Kit GenAI summarisation and proofreading: status, download, summarize, proofread. MlKitNoteAi for production, FakeNoteAi for tests.
NoteRepository + RoomSingle source of truth for note text. CRUD operations. No AI logic. No network calls.
Feature detection + fallbackMaps FeatureStatus to an app status, drives the download, and decides on-device vs consented cloud vs unavailable.
Consent + settingsStores consent for the optional cloud path in DataStore. No API keys in the app; the cloud path goes through your backend.

Milestones

1. Notes CRUD with Compose and Room

Create, read, update, and delete notes stored in Room, shown in a Compose list and editor.

  1. Add Room and define a Note entity with id, title, body, and updated timestamp.
  2. Write a NoteDao with insert, update, delete, and a Flow<List<Note>> query for the list screen.
  3. Build a NoteListScreen with LazyColumn and a NoteEditorScreen with a TextField, wired with Navigation Compose.
  4. Create a NoteRepository that wraps the DAO; the ViewModel never calls Room directly.
  5. Add a NoteViewModel that exposes StateFlow<UiState> and handles create, edit, and delete intents.

Done when: You can add a note, see it in the list, edit it, delete it, and the list is still there after the process is killed and restarted.

Lessons: room entities daos queries, mvi in practice, navigation in compose

2. Feature status and model download

Detect whether summarisation is unavailable, downloadable, downloading, or available, and download it from the UI.

  1. Add the com.google.mlkit:genai-summarization and com.google.mlkit:genai-proofreading dependencies, plus kotlinx-coroutines-guava so you can await() the returned futures.
  2. Build SummarizerOptions.builder(context) with an input type, output type (one, two, or three bullets), and language, then create the client with Summarization.getClient(options).
  3. Call summarizer.checkFeatureStatus().await() and map the four FeatureStatus values to a sealed AiStatus type.
  4. When the status is DOWNLOADABLE, show a "Download model" button that calls downloadFeature with a DownloadCallback; wrap it in callbackFlow and emit started, progress, completed, and failed events.
  5. Check the status again when the screen resumes, since a download may have finished or failed while the app was away. Close the clients in onCleared().

Done when: On a supported device the status moves from DOWNLOADABLE to AVAILABLE after you tap download, with visible progress; on an unsupported device it stays UNAVAILABLE and the UI shows a clear message.

Lessons: ml kit ready made on device ml, on device llms gemini nano and litert lm, error handling and result types

3. Summarisation and proofreading in the foreground

Run summarisation and proofreading on the current note while the screen is visible, show a loading state, and display the result.

  1. Define a NoteAi interface with suspend fun status(): AiStatus, fun download(): Flow<DownloadEvent>, suspend fun summarize(text: String): String, and suspend fun proofread(text: String): String.
  2. Implement summarisation with SummarizationRequest.builder(text).build() and summarizer.runInference(request).await().summary, or use the streaming runInference(request) { newText -> ... } overload to show text as it arrives.
  3. Implement proofreading with ProofreaderOptions (input type KEYBOARD or VOICE, plus a language), Proofreading.getClient, and ProofreadingRequest; show the top suggestion from results. Proofreading accepts only short input, so send one paragraph at a time.
  4. Only start AI work from a button tap on the visible editor, and launch it in viewModelScope so leaving the screen cancels waiting for the result.
  5. Measure latency with SystemClock.elapsedRealtime() before and after each call and show it in a small label.

Done when: Tapping "Summarise" on a long note shows a progress indicator, then bullet points with a latency label. Tapping "Proofread" on a paragraph shows a corrected version the user can accept or dismiss.

Lessons: latency cost and fallbacks, stateflow and sharedflow, collecting flows safely in the ui

When on-device AI is unavailable, show a clear message and offer an optional cloud path only after the user consents.

  1. Add a ConsentStore backed by DataStore that holds one boolean: cloudAiConsented.
  2. When AiStatus is UNAVAILABLE, show "On-device AI is not available on this device." with an optional "Use cloud" button. Notes, editing, and search keep working without AI.
  3. The cloud button opens a consent screen explaining that note text will leave the device. No cloud call happens before consent is stored.
  4. Route the cloud path through your own backend (or Firebase AI Logic with App Check); never put a provider API key in the app.
  5. Add a settings toggle where the user can revoke consent at any time.

Done when: On a device where checkFeatureStatus() returns UNAVAILABLE, the user sees the fallback message. The cloud path is never reached without an explicit consent tap. Revoking consent disables the cloud path immediately.

Lessons: on device vs cloud ai how to choose, privacy safety and content filtering, calling claude and other llm apis through your backend

5. Tests with a fake NoteAi

Write unit tests that exercise every AI state without a real model, using a FakeNoteAi.

  1. Create FakeNoteAi with a configurable status, a scripted download flow, and a configurable result or exception for summarize and proofread.
  2. Write a NoteViewModelTest that injects the fake and asserts the UiState transitions: idle, loading, success, and error.
  3. Add a test for the busy or quota path: the fake throws your own AiBusyException, and the UI shows a "try again later" message instead of a crash.
  4. Add tests for UNAVAILABLE (fallback state) and for a download that fails (retry button, no endless spinner).
  5. Run the suite with ./gradlew test and confirm it passes on a machine without any device.

Done when: NoteViewModelTest covers success, busy or quota error, unavailable, failed download, and empty note, and no test touches a real ML Kit client.

Lessons: fakes vs mocks, testing coroutines and flows, test pyramid for android

6. Quota errors, logging, and hardening

Handle platform errors gracefully, record latency without leaking note text, and verify the privacy guarantee.

  1. Catch GenAiException in MlKitNoteAi and map errorCode: ErrorCode.BUSY (too many requests in a short time) to retry with exponential backoff, ErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDED (longer-duration quota) to a "try again later" state, and ErrorCode.BACKGROUND_USE_BLOCKED to a "reopen the app" state.
  2. Add a LatencyLogger that records timestamp, operation, latency, and status, plus the note id but never the body.
  3. Handle long notes: enable setLongInputAutoTruncationEnabled(true) on the summarizer options or split the note and summarise the parts.
  4. Audit the code: confirm no note body is passed to any network call unless cloudAiConsented is true, and none reaches logs or crash reports.
  5. On a supported device, download the feature, run several summaries, and read the log to see the latency spread.

Done when: Busy and quota errors show a specific message instead of a crash or a generic error. The log contains latency entries with no note text. A search of the codebase shows no note body reaching a network call when consent is off.

Lessons: evaluating ai features, performance monitoring in production, crash handling and reporting

Key code

import android.content.Context
import com.google.mlkit.genai.common.DownloadCallback
import com.google.mlkit.genai.common.FeatureStatus
import com.google.mlkit.genai.common.GenAiException
import com.google.mlkit.genai.summarization.Summarization
import com.google.mlkit.genai.summarization.SummarizationRequest
import com.google.mlkit.genai.summarization.SummarizerOptions
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.guava.await
 
enum class AiStatus { UNAVAILABLE, DOWNLOADABLE, DOWNLOADING, AVAILABLE }
 
sealed interface DownloadEvent {
    data class Started(val bytesToDownload: Long) : DownloadEvent
    data class Progress(val bytesDownloaded: Long) : DownloadEvent
    data object Completed : DownloadEvent
}
 
interface NoteSummarizer : AutoCloseable {
    suspend fun status(): AiStatus
    fun download(): Flow<DownloadEvent>
    suspend fun summarize(text: String): String
}
 
class MlKitNoteSummarizer(context: Context) : NoteSummarizer {
    private val summarizer = Summarization.getClient(
        SummarizerOptions.builder(context)
            .setInputType(SummarizerOptions.InputType.ARTICLE)
            .setOutputType(SummarizerOptions.OutputType.THREE_BULLETS)
            .setLanguage(SummarizerOptions.Language.ENGLISH)
            .setLongInputAutoTruncationEnabled(true)
            .build()
    )
 
    override suspend fun status(): AiStatus =
        when (summarizer.checkFeatureStatus().await()) {
            FeatureStatus.AVAILABLE -> AiStatus.AVAILABLE
            FeatureStatus.DOWNLOADING -> AiStatus.DOWNLOADING
            FeatureStatus.DOWNLOADABLE -> AiStatus.DOWNLOADABLE
            else -> AiStatus.UNAVAILABLE
        }
 
    override fun download(): Flow<DownloadEvent> = callbackFlow {
        summarizer.downloadFeature(object : DownloadCallback {
            override fun onDownloadStarted(bytesToDownload: Long) {
                trySend(DownloadEvent.Started(bytesToDownload))
            }
            override fun onDownloadProgress(totalBytesDownloaded: Long) {
                trySend(DownloadEvent.Progress(totalBytesDownloaded))
            }
            override fun onDownloadCompleted() {
                trySend(DownloadEvent.Completed)
                close()
            }
            override fun onDownloadFailed(e: GenAiException) {
                close(e) // the collector sees the failure, so the UI can show retry
            }
        })
        awaitClose { }
    }
 
    // Call only from a user action while the app is in the foreground.
    override suspend fun summarize(text: String): String {
        val request = SummarizationRequest.builder(text).build()
        return summarizer.runInference(request).await().summary
    }
 
    override fun close() = summarizer.close()
}
 
class FakeNoteSummarizer(
    var currentStatus: AiStatus = AiStatus.AVAILABLE,
    var result: Result<String> = Result.success("- Fake summary"),
) : NoteSummarizer {
    override suspend fun status() = currentStatus
    override fun download(): Flow<DownloadEvent> = callbackFlow {
        trySend(DownloadEvent.Completed)
        close()
        awaitClose { }
    }
    override suspend fun summarize(text: String) = result.getOrThrow()
    override fun close() {}
}
  • NoteSummarizer is the summarisation half of NoteAi; proofreading follows the same pattern with Proofreading.getClient. checkFeatureStatus(), runInference(), and downloadFeature() return ListenableFutures; kotlinx-coroutines-guava supplies await() so they read as suspend calls. The ViewModel catches GenAiException and maps its errorCode to UI state.
  • callbackFlow turns DownloadCallback into a Flow. onDownloadFailed closes the flow with the exception, so a failed download ends in an error state instead of an endless spinner.
  • setLongInputAutoTruncationEnabled(true) lets the summarizer cut input that is over its limit instead of failing. Very short notes may be rejected for the article input type, so hide the button for them.
  • The fake implements the same interface, so ViewModel tests can script every status, download outcome, and error without a device, AICore, or Gemini Nano.

Pitfalls

  • Calling the GenAI APIs from WorkManager, a service, or when the app is in the background. Inference is allowed only when your app is the top foreground app; anything else, including a foreground service, fails with ErrorCode.BACKGROUND_USE_BLOCKED. Fix: start AI work only from user actions on a visible screen, and treat that error as "reopen the app".
  • Skipping the status check. On an unsupported device the feature is UNAVAILABLE and inference fails; on a supported device the feature may still need downloading. Fix: call checkFeatureStatus() first and branch on all four values, and check again when the screen resumes.
  • Putting a cloud API key in local.properties or BuildConfig. Anything in the APK can be extracted. Fix: the optional cloud path goes through your own backend or through Firebase AI Logic with App Check, and the app never holds a provider key.
  • Treating quota errors as generic failures. AICore enforces per-app quotas: ErrorCode.BUSY after too many requests in a short time and ErrorCode.PER_APP_BATTERY_USE_QUOTA_EXCEEDED for longer-duration limits. Fix: back off exponentially on BUSY, show a clear "try again later" message for the longer quota, and never retry in a tight loop.
  • Blocking the main thread on the futures. Calling .get() on the returned ListenableFuture from the main thread freezes the UI until inference finishes. Fix: await() it from a coroutine, or use the streaming runInference callback.
  • Logging the full note body. The whole point is that notes stay on the device; logging the body to a file, Logcat, or a crash reporter defeats it. Fix: log only the note id, operation, latency, and status.

Code review finding

Model download failure leaves the UI stuck on a perpetual spinner
  • The user taps "Download model" and the UI switches to a progress indicator.
  • The DownloadCallback implementation handles onDownloadCompleted but leaves onDownloadFailed empty.
  • When the network drops, onDownloadFailed fires, nothing changes in UiState, and the spinner never ends.
  • When the user comes back later, the screen never calls checkFeatureStatus() again, so it does not notice the status changed.
The fix
  • Close the callbackFlow with the exception in onDownloadFailed, catch it in the ViewModel, and show a "Retry download" button.
  • Call checkFeatureStatus() again when the screen resumes and update the UI from the fresh value.
  • Add a unit test where FakeNoteSummarizer.download() fails and assert the UI ends in the retry state, not loading.

Stretch goals

  • Show proofreading suggestions inline in the editor with an AnnotatedString that highlights changed words.
  • Stream the summary into the UI with the callback overload of runInference instead of waiting for the full result.
  • Add the ML Kit GenAI Rewriting API to offer tone changes (for example, more formal or shorter) for a note.
  • Write a one-page design doc comparing on-device and cloud for this use case, covering privacy and device coverage, and link it from the README.
  • Add screenshot tests for the fallback screen and the consent screen so the fallback path is checked in CI.

Done checklist

  • Every AI call is preceded by a checkFeatureStatus() check, and all four FeatureStatus values are handled.
  • downloadFeature uses a DownloadCallback whose failure path leads to a retry state.
  • AI work starts only from user actions on a visible screen; nothing runs from WorkManager or a service.
  • Busy, quota, and background-blocked GenAiException codes each show a specific message.
  • Summarisation and proofreading sit behind an interface, and the ViewModel tests use the fake without a device.
  • Unsupported devices get a clear fallback; the cloud path is unreachable without stored consent and holds no API key in the app.
  • No note body appears in any network call (without consent), log line, or crash report.
  • The ML Kit clients are closed when the ViewModel is cleared.

Talking about it in an interview

  • Explain why the AI sits behind an interface: it decouples the ViewModel from ML Kit, lets you test every state with a fake, and makes it easy to add a cloud implementation later without touching the UI.
  • Walk through the feature-detection flow: check status, branch on four values, download only on a user tap with progress, and re-check on resume. Emphasise that on-device generative AI exists only on some devices, so the app must be complete without it.
  • Describe the platform limits: inference only when the app is in the foreground, and per-app quotas that return BUSY or a longer-duration quota error. Explain how each maps to UI and why you back off rather than retry in a loop.
  • Describe the privacy decision: notes stay in Room, the cloud path is opt-in and goes through a backend, and logs hold ids and latencies, not text. Frame it as a product decision as well as a technical one.
  • Mention the testing strategy: a fake rather than a mock, because you want scripted, readable behaviour for status, download, and errors. Contrast this with a mock and say when you would choose one.