ScreenSync MCP guide

Testing Android Paging 3 with Claude Code and MCP

Test Jetpack Paging 3 LazyPagingItems, RemoteMediator Room transactions, offline LoadState.Error retries, and process-death scroll restoration on real Android devices with Claude Code and ScreenSync MCP.

Minimalist 3D architectural render of an Android smartphone displaying tiered frosted-glass paginated list cards linked by glowing purple fiber-optic lines to a developer laptop in deep navy lighting

Jetpack Paging 3 (androidx.paging) simplifies incremental data loading across network APIs and Room databases, yet infinite-scroll bugs routinely slip past JVM unit tests and asSnapshot() checks into production releases. Missing itemKey lambdas cause LazyColumn scroll jumps, RemoteMediator race conditions drop pages during withTransaction writes, and LoadState.Error retry banners stall when real cellular or Wi-Fi connections drop mid-fling. Connecting Claude Code to physical Android hardware through ScreenSync MCP—an Android and browser Model Context Protocol (MCP) server created by EpsolDev—allows an autonomous coding agent to drive real scroll flings, inspect live Compose UI trees, read Logcat pagination telemetry, and verify PagingData recovery directly on your test device.

Key Takeaways

  • Real-Device Pagination Verification: Testing Paging 3 on physical Android hardware exposes LazyPagingItems flicker, duplicate RemoteKeys, prefetch storms, and process-death scroll resets that synthetic PagingData.from() tests hide.
  • Decoupled Capture and Control: ScreenSync MCP captures live Android screens using Android's native MediaProjection API with no root and no ADB (~94 ms median LAN mirror latency in EpsolDev's tests), while control_tap, control_swipe, and control_type execute deterministically through ADB (USB or wireless debugging).
  • 226-Tool Verification Surface: The Node.js 18+ desktop hub exposes 29 phone and desktop tools (12 control_*, 3 os_*, and 14 capture/hub tools including get_latest_screenshot, get_ui_hierarchy, get_logcat, and record_screen) alongside *197 `web_` browser tools** for cross-surface API and admin-dashboard checks.
  • Deterministic State Observability: Pairing Compose testTagsAsResourceId semantics with structured Logcat breadcrumbs lets Claude Code verify LoadState.Refresh, LoadState.Append, and RemoteMediator commits without guessing screen coordinates.

Why Paging 3 Regressions Escape JVM Unit Tests

Jetpack Paging 3 bugs escape JVM unit tests because PagingSource and asSnapshot() tests execute against deterministic in-memory dispatchers without real LazyColumn viewport recycling, touch-fling physics, network latency jitter, or Room transaction contention. Real-device testing on physical Android hardware reveals LoadState race conditions, scroll-position loss, and prefetch thrashing immediately.

Most Android teams validate androidx.paging:paging-testing inside JVM unit suites by calling flow.asSnapshot { scrollTo(index = 40) } against a fake repository. While asSnapshot confirms cursor arithmetic and prevKey/nextKey math, it strips out four runtime realities that govern how users experience infinite lists:

  1. Initial itemCount == 0 flicker in LazyPagingItems: Before the first PagingData emission settles in collectAsLazyPagingItems(), pagingItems.itemCount is 0 while loadState.refresh transitions from NotLoading to Loading. Screens that gate empty-state placeholders on itemCount == 0 alone flash "No items found" frames for 100–300 ms on physical displays before content snaps into place.
  2. Missing stable itemKey and itemContentType lambdas: Passing items(count = pagingItems.itemCount) without key = pagingItems.itemKey { it.id } forces Compose to key rows by positional index. When a RemoteMediator prepends new records or invalidates a stale page during pull-to-refresh, existing rows jump abruptly, reset local state, or trigger duplicate animations.
  3. RemoteMediator and Room invalidation loops: Under real network latency, wrapping remoteKeysDao.clearAll() and itemsDao.insertAll() outside an atomic database.withTransaction { ... } block causes Room's InvalidationTracker to emit intermediate empty snapshots mid-sync. That transient empty emission wipes the user's LazyListState scroll offset back to item 0.
  4. Prefetch exhaustion under fast flings: A user flicking rapidly down a 60 Hz or 120 Hz physical display burns through PagingConfig(prefetchDistance = 5) faster than slow 3G/4G endpoints respond. If loadState.append transitions to LoadState.Error while the footer is off-screen or poorly tagged, pagingItems.retry() becomes unreachable or unresponsive.

If your team already runs Jetpack Compose UI testing on physical devices, extending that loop to Paging 3 closes the gap between synthetic flow assertions and real hardware rendering.

Verification Dimension asSnapshot() / PagingSource JVM Tests ComposeTestRule with PagingData.from() Cloud Device Farms ScreenSync MCP + Claude Code (Physical Hardware)
Real LazyColumn Viewport & Recycling None (headless Flow snapshot only) Partial (simulated clock & static list) Full Android SurfaceFlinger Full physical display via MediaProjection (~94 ms LAN)
Touch Fling & Velocity Physics Programmatic scrollTo(index) Synthetic performScrollToIndex Remote WebRTC touch relay Real hardware touch events via control_swipe over ADB
RemoteMediator + Room Contention Requires Robolectric or in-memory Room Bypassed when mocking PagingData.from() Supported, slower log extraction Live Room SQLite + get_logcat + get_ui_hierarchy
Offline / Network Drop Recovery Mocked IOException return values Hardcoded error LoadState injection Radio disable severs cloud session Real ADB radio toggles with USB adb reverse mirror
Process Death Scroll Restoration Not exercised Limited to StateRestorationTester Slow multi-minute session restarts Instant adb shell am kill + relaunch & visual check

Setting Up ScreenSync MCP for Paging 3 Hardware Testing

Setting up ScreenSync MCP connects your local Android test phone to Claude Code over a private LAN or USB bridge in four steps. Screen capture runs through Android's native MediaProjection API without root or ADB, while touch gestures, scrolls, and keyboard inputs dispatch over ADB via the Node.js 18+ desktop hub.

Before automating pagination flows, verify your workstation and physical Android device meet ScreenSync MCP's runtime requirements. All components—the Android app, the desktop hub, and the browser extension—are free downloads provided by EpsolDev, and the complete installation walkthrough lives in the ScreenSync MCP setup guide.

1. Install the Android App and Start the Desktop Hub

  • Install ScreenSync MCP (com.screensync.mcp, version 2.5.7) free from Google Play on a physical phone or tablet running Android 7.0 or later. ScreenSync MCP is built exclusively for Android devices paired with a desktop hub and Chrome/Edge browser extension.
  • Download and unpack the ScreenSync MCP desktop hub (version 1.14.4) on Windows, macOS, or Linux with Node.js 18+ and adb on your PATH. Start the hub with start-hub.bat (Windows) or start-hub.sh (macOS/Linux). The hub opens an HTTP listener on port 3000 and speaks Model Context Protocol over stdio.
  • Pair your phone by scanning the hub's terminal QR code or via mDNS auto-discovery on the same subnet. When starting capture, tap Start Now on Android's MediaProjection consent dialog. Keep the transport boundary explicit: screen capture uses Android's MediaProjection API with no root and no ADB, whereas device control tools (control_tap, control_swipe, control_type) execute through ADB over USB or wireless debugging.

2. Register the Stdio Server in Claude Code or Claude Desktop

Register ScreenSync MCP in Claude Code from your Android project root:

claude mcp add screensync node "/path/to/hub/screensync-hub.js"

If you also drive workflows from Claude Desktop, add the local stdio server entry to claude_desktop_config.json (Settings > Developer) with your hub bearer token:

{
  "mcpServers": {
    "screensync": {
      "command": "node",
      "args": [
        "/path/to/hub/screensync-hub.js"
      ],
      "env": {
        "SCREEN_SYNC_TOKEN": "your-local-pairing-token"
      }
    }
  }
}

Cursor and VS Code agent mode also work with ScreenSync MCP—check your editor's MCP documentation to configure the same screensync-hub.js stdio entrypoint. Browser-only ChatGPT web sessions require remote HTTPS MCP endpoints and cannot run local stdio servers. Once connected, your agent receives 226 MCP tools (29 phone and desktop tools—12 control_*, 3 os_*, and 14 capture/hub tools—plus *197 `web_` browser tools), 17 prompts, and 3 resources**. For deeper architectural details on how frames reach your workstation, read how ScreenSync MCP captures Android screens.

Instrumenting Paging 3 and Compose LazyColumn for AI Observability

Instrumenting a Jetpack Paging 3 feed for Claude Code verification requires stable itemKey bindings, semantic testTag modifiers exposed via testTagsAsResourceId = true, and structured Logcat state logs inside RemoteMediator and LoadState collectors. These lightweight debug hooks let Claude Code distinguish empty-state bugs, append errors, and page duplicates deterministically.

Screenshots alone cannot tell an AI agent whether a LazyColumn rendered items from local Room cache or hit the network, nor whether RemoteMediator triggered two overlapping APPEND requests during a fast scroll. By pairing Jetpack Compose semantics with concise PagingQA Logcat markers, you give Claude Code two authoritative inspection channels: get_ui_hierarchy and get_logcat.

Below is a production-structured Paging 3 implementation combining a Room-backed RemoteMediator (@OptIn(ExperimentalPagingApi::class)), atomic withTransaction key persistence, and a Jetpack Compose screen instrumented for ScreenSync MCP:

package com.example.pagingqa.data

import android.util.Log
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.RoomDatabase
import androidx.room.withTransaction
import androidx.paging.PagingSource
import java.io.IOException

@Entity(tableName = "feed_items")
data class FeedItemEntity(
    @PrimaryKey val id: String,
    val title: String,
    val pageIndex: Int,
    val updatedAt: Long
)

@Entity(tableName = "remote_keys")
data class RemoteKeyEntity(
    @PrimaryKey val itemId: String,
    val prevKey: Int?,
    val nextKey: Int?
)

@Dao
interface FeedDao {
    @Query("SELECT * FROM feed_items ORDER BY pageIndex ASC, id ASC")
    fun pagingSource(): PagingSource<Int, FeedItemEntity>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(items: List<FeedItemEntity>)

    @Query("DELETE FROM feed_items")
    suspend fun clearAll()
}

@Dao
interface RemoteKeyDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(keys: List<RemoteKeyEntity>)

    @Query("SELECT * FROM remote_keys WHERE itemId = :itemId")
    suspend fun remoteKeyByItemId(itemId: String): RemoteKeyEntity?

    @Query("DELETE FROM remote_keys")
    suspend fun clearRemoteKeys()
}

@Database(entities = [FeedItemEntity::class, RemoteKeyEntity::class], version = 1)
abstract class FeedDatabase : RoomDatabase() {
    abstract fun feedDao(): FeedDao
    abstract fun remoteKeyDao(): RemoteKeyDao
}

interface FeedApi {
    suspend fun fetchPage(page: Int, limit: Int): List<FeedItemEntity>
}

@OptIn(ExperimentalPagingApi::class)
class FeedRemoteMediator(
    private val db: FeedDatabase,
    private val api: FeedApi
) : RemoteMediator<Int, FeedItemEntity>() {

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, FeedItemEntity>
    ): MediatorResult {
        return try {
            val page = when (loadType) {
                LoadType.REFRESH -> {
                    val closest = state.anchorPosition?.let { pos ->
                        state.closestItemToPosition(pos)?.id?.let { id ->
                            db.remoteKeyDao().remoteKeyByItemId(id)
                        }
                    }
                    closest?.nextKey?.minus(1) ?: 1
                }
                LoadType.PREPEND -> {
                    val firstItem = state.firstItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)
                    val key = db.remoteKeyDao().remoteKeyByItemId(firstItem.id)
                    key?.prevKey ?: return MediatorResult.Success(endOfPaginationReached = true)
                }
                LoadType.APPEND -> {
                    val lastItem = state.lastItemOrNull()
                        ?: return MediatorResult.Success(endOfPaginationReached = true)
                    val key = db.remoteKeyDao().remoteKeyByItemId(lastItem.id)
                    key?.nextKey ?: return MediatorResult.Success(endOfPaginationReached = true)
                }
            }

            Log.d("PagingQA", "MEDIATOR_START loadType=$loadType page=$page")
            val remoteItems = api.fetchPage(page = page, limit = state.config.pageSize)
            val endOfPagination = remoteItems.isEmpty()

            db.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    db.remoteKeyDao().clearRemoteKeys()
                    db.feedDao().clearAll()
                }
                val prevKey = if (page == 1) null else page - 1
                val nextKey = if (endOfPagination) null else page + 1
                val keys = remoteItems.map { item ->
                    RemoteKeyEntity(itemId = item.id, prevKey = prevKey, nextKey = nextKey)
                }
                db.remoteKeyDao().insertAll(keys)
                db.feedDao().insertAll(remoteItems)
            }

            Log.d(
                "PagingQA",
                "MEDIATOR_COMMIT loadType=$loadType page=$page count=${remoteItems.size} end=$endOfPagination"
            )
            MediatorResult.Success(endOfPaginationReached = endOfPagination)
        } catch (e: IOException) {
            Log.w("PagingQA", "MEDIATOR_ERROR loadType=$loadType type=IO msg=${e.message}")
            MediatorResult.Error(e)
        } catch (e: Exception) {
            Log.e("PagingQA", "MEDIATOR_ERROR loadType=$loadType type=FATAL msg=${e.message}")
            MediatorResult.Error(e)
        }
    }
}

Next, pair the RemoteMediator with a Jetpack Compose LazyColumn that correctly guards against the initial itemCount == 0 loading trap, exposes stable keys, and surfaces retry controls in the accessibility tree:

package com.example.pagingqa.ui

import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.itemContentType
import androidx.paging.compose.itemKey
import com.example.pagingqa.data.FeedItemEntity

@Composable
fun PaginatedFeedScreen(
    pagingItems: LazyPagingItems<FeedItemEntity>,
    modifier: Modifier = Modifier
) {
    val listState = rememberLazyListState()

    LaunchedEffect(pagingItems.loadState) {
        Log.d(
            "PagingQA",
            "LOAD_STATE refresh=${pagingItems.loadState.refresh::class.simpleName} " +
                "append=${pagingItems.loadState.append::class.simpleName} " +
                "count=${pagingItems.itemCount}"
        )
    }

    Box(
        modifier = modifier
            .fillMaxSize()
            .semantics { testTagsAsResourceId = true }
    ) {
        when (val refreshState = pagingItems.loadState.refresh) {
            is LoadState.Loading if pagingItems.itemCount == 0 -> {
                CircularProgressIndicator(
                    modifier = Modifier
                        .align(Alignment.Center)
                        .testTag("paging_initial_loader")
                )
            }
            is LoadState.Error if pagingItems.itemCount == 0 -> {
                Column(
                    modifier = Modifier
                        .align(Alignment.Center)
                        .padding(24.dp)
                        .testTag("paging_initial_error"),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(refreshState.error.localizedMessage ?: "Failed to load feed")
                    Spacer(Modifier.height(12.dp))
                    Button(
                        onClick = { pagingItems.retry() },
                        modifier = Modifier.testTag("btn_paging_initial_retry")
                    ) {
                        Text("Retry Feed")
                    }
                }
            }
            else -> {
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxSize()
                        .testTag("paging_feed_list"),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    items(
                        count = pagingItems.itemCount,
                        key = pagingItems.itemKey { it.id },
                        contentType = pagingItems.itemContentType { "feed_item" }
                    ) { index ->
                        val item = pagingItems[index]
                        if (item != null) {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .testTag("feed_card_${item.id}")
                            ) {
                                Column(Modifier.padding(16.dp)) {
                                    Text(item.title, style = MaterialTheme.typography.titleMedium)
                                    Text("Page ${item.pageIndex}", style = MaterialTheme.typography.bodySmall)
                                }
                            }
                        }
                    }

                    when (val appendState = pagingItems.loadState.append) {
                        is LoadState.Loading -> {
                            item(key = "append_loading") {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(16.dp)
                                        .testTag("paging_append_loader"),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }
                        is LoadState.Error -> {
                            item(key = "append_error") {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(16.dp)
                                        .testTag("paging_append_error"),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Text(appendState.error.localizedMessage ?: "Page load failed")
                                    Button(
                                        onClick = { pagingItems.retry() },
                                        modifier = Modifier.testTag("btn_paging_append_retry")
                                    ) {
                                        Text("Retry")
                                    }
                                }
                            }
                        }
                        is LoadState.NotLoading -> {
                            if (appendState.endOfPaginationReached && pagingItems.itemCount > 0) {
                                item(key = "end_of_list") {
                                    Text(
                                        text = "End of feed",
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp)
                                            .testTag("paging_end_marker")
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Three instrumentation choices directly accelerate Claude Code's verification loop:

  • Distinct testTag states for refresh vs. append: Separating paging_initial_loader / btn_paging_initial_retry from paging_append_loader / btn_paging_append_retry ensures get_ui_hierarchy reports unambiguous resource-id nodes for every LoadState phase.
  • Per-item stable feed_card_${item.id} tags: Claude Code can capture get_ui_hierarchy before and after a control_swipe fling, compute exact card ID deltas, and verify zero duplicate keys or missing gaps across page boundaries.
  • MEDIATOR_START and MEDIATOR_COMMIT Logcat lines: Inspecting get_logcat reveals immediately if LoadType.APPEND fired twice for the same page, or if RemoteKeyEntity returned null prematurely and stopped pagination early.

Core ScreenSync MCP Loop for Infinite Lists and Scroll Prefetching

Testing Paging 3 scroll prefetching with Claude Code pairs control_swipe touch flings over ADB with get_ui_hierarchy node-count diffing, get_latest_screenshot visual inspection, and get_logcat mediator tracking. Because ScreenSync MCP streams frames at roughly 94 ms median LAN latency in EpsolDev's tests, the agent detects jank, placeholder flashes, and skipped pages in real time.

When Claude Code evaluates an infinite list on a physical Android phone, it avoids arbitrary blind scrolling. Instead, it drives a closed-loop verification cycle across ScreenSync MCP's mobile toolset:

Verification Phase ScreenSync MCP Tool(s) Transport / Privilege Concrete Paging 3 Assertion
1. Initial Refresh & Empty Guard get_ui_hierarchy, get_latest_screenshot, get_logcat MediaProjection capture (no root, no ADB) + Logcat Verify paging_initial_loader yields directly to feed_card_* items with zero empty-state flash
2. Prefetch Boundary Scroll control_swipe, get_ui_hierarchy, get_logcat ADB swipe injection + hierarchy/log inspection Swipe upward across viewport; verify MEDIATOR_START loadType=APPEND page=2 fires before reaching list bottom
3. Fast Fling & Visual Stability control_swipe, record_screen ADB high-velocity fling + MediaProjection recording Check video frames for blank placeholder flickering, clipped cards, or Choreographer skipped-frame warnings
4. End-of-Pagination Seal control_swipe, get_ui_hierarchy ADB scroll + hierarchy node check Scroll until paging_end_marker appears; confirm endOfPaginationReached=true stops redundant API calls
5. Cross-Surface Backend Sync web_* browser tools + control_swipe Chrome/Edge MV3 extension + Mobile ADB Mutate or publish a new item in the web admin console, trigger refresh on phone, verify page 1 updates

You can instruct Claude Code directly inside your repository using a structured prompt like this:

Using the connected ScreenSync MCP server on the paired Android phone:
1. Call get_ui_hierarchy and get_latest_screenshot to verify initial Page 1 items (feed_card_1 through feed_card_20) are visible inside paging_feed_list.
2. Call get_logcat filtering for "PagingQA" and confirm only a single MEDIATOR_COMMIT loadType=REFRESH page=1 occurred.
3. Perform 3 upward scrolls using control_swipe to cross prefetchDistance, then inspect get_ui_hierarchy to confirm feed_card_21+ rendered without duplicate IDs.
4. Capture a short 5-second clip with record_screen during a fast fling to confirm smooth rendering and no blank placeholder jumps.

For deeper touch-physics patterns when testing fast flings, decelerating scrolls, and pull-to-refresh thresholds on real screens, review our guide on dynamic gesture simulation in mobile AI testing.

Simulating Network Drops to Test LoadState.Error and retry()

Testing Paging 3 LoadState.Error and pagingItems.retry() requires severing real device connectivity mid-scroll without killing your test runner's screen mirror. Forwarding port 3000 over USB (adb reverse tcp:3000 tcp:3000) keeps ScreenSync MCP's MediaProjection stream alive while Claude Code toggles Wi-Fi or cellular data via ADB to trigger authentic IOException failures.

In unit tests, throwing a synthetic IOException from a FakeFeedApi verifies that MediatorResult.Error returns—but it never proves whether a real user can reach btn_paging_append_retry on a 6-inch screen, whether OkHttp timeouts hang the footer spinner for 30 seconds, or whether RemoteMediator corrupts Room's RemoteKeyEntity table when a socket drops mid-response.

Because ScreenSync MCP runs locally on your workstation rather than inside a remote cloud device farm that dies when the phone goes offline, Claude Code can sever public internet access safely:

# Keep ScreenSync MCP's MediaProjection video stream flowing over USB while radios are off
adb reverse tcp:3000 tcp:3000

# Verify reverse port mapping is active
adb reverse --list

# Drop Wi-Fi and cellular radios before scrolling past Page 2
adb shell svc wifi disable
adb shell svc data disable

Once the radios are disabled, Claude Code executes a deterministic offline-error and recovery sequence:

  1. Trigger LoadState.Append failure: Claude Code runs control_swipe to scroll down to the end of cached Page 2 items. Because FeedRemoteMediator attempts api.fetchPage(page = 3) and hits an OS-level UnknownHostException or ConnectException, get_logcat records MEDIATOR_ERROR loadType=APPEND type=IO.
  2. Verify footer error UI: Claude Code calls get_ui_hierarchy and get_latest_screenshot to confirm paging_append_error and btn_paging_append_retry are rendered cleanly at the bottom of paging_feed_list—not hidden behind system navigation insets and not replacing already-loaded Page 1–2 items with a full-screen error!
  3. Restore network and test retry(): Claude Code re-enables Wi-Fi (adb shell svc wifi enable), waits briefly for ConnectivityManager to settle, and invokes control_tap on the coordinates of btn_paging_append_retry.
  4. Verify seamless continuation: Claude Code checks get_logcat for MEDIATOR_COMMIT loadType=APPEND page=3 and confirms via get_ui_hierarchy that feed_card_41 appends directly below feed_card_40 with zero duplicated rows or scroll resets.

To expand this pattern into full offline-first cache reconciliation and retry backoff audits, explore testing Android offline mode and sync with Claude Code and MCP and testing Android network resilience with Claude Code and MCP.

Auditing RemoteMediator Room Transactions and Process Death

Auditing RemoteMediator durability requires testing Room schema behavior and Android OS process termination after scrolling multiple pages deep. Combining adb shell am kill with ScreenSync MCP's get_ui_hierarchy, get_latest_screenshot, and adb shell run-as SQLite checks exposes anchorPosition mismatches and scroll-offset resets that keep-alive test suites miss.

One of the trickiest production bugs in Paging 3 occurs when a user scrolls down to item #65 (Page 4), backgrounds the app to answer a message, and Android reclaims the background process under memory pressure. When the user taps the app icon again:

  • Android restores the LazyListState scroll index (firstVisibleItemIndex) via rememberSaveable.
  • Simultaneously, Pager initializes a fresh PagingSource from Room and may trigger RemoteMediator.load(LoadType.REFRESH, state) depending on initialize() (LAUNCH_INITIAL_REFRESH vs SKIP_INITIAL_REFRESH).
  • If LoadType.REFRESH calls clearAll() and reloads from page = 1 instead of reading state.anchorPosition and closestItemToPosition(pos), Room clears items 41–80, LazyListState clamps back to 0, and the user loses their place completely.

Claude Code verifies this exact failure mode on real hardware in four commands:

# 1. After scrolling to item #65, send the app to the background so Android saves instance state
adb shell input keyevent KEYCODE_HOME

# 2. Allow onSaveInstanceState to flush, then simulate OS low-memory process termination
sleep 2
adb shell am kill com.example.pagingqa

# 3. Inspect persisted RemoteKey rows in Room SQLite before relaunching
adb shell run-as com.example.pagingqa sqlite3 databases/feed_db   "SELECT COUNT(*), MIN(prevKey), MAX(nextKey) FROM remote_keys;"

# 4. Relaunch the Activity from Launcher/Recents to trigger SavedState restoration
adb shell am start -n com.example.pagingqa/.MainActivity

Immediately after relaunch, Claude Code runs:

  1. get_ui_hierarchy: Checks which feed_card_* IDs sit inside the visible viewport. If feed_card_1 appears instead of feed_card_63–feed_card_68, Claude Code flags a scroll-restoration or SKIP_INITIAL_REFRESH regression.
  2. get_logcat: Confirms whether MEDIATOR_START loadType=REFRESH fired needlessly and wiped cached Room pages, or resumed cleanly around anchorPosition.
  3. get_latest_screenshot: Verifies that restored rows render immediately from Room without displaying paging_initial_loader over cached content.

For deeper coverage on SavedStateHandle persistence and Room schema upgrades behind RemoteMediator, read testing Android process death with Claude Code and MCP and testing Android Room database migrations with Claude Code and MCP.

Paging 3 Bug Pattern Why Unit / asSnapshot Tests Miss It Real-Device Signal Caught by ScreenSync MCP Root Kotlin / Paging 3 Fix
Initial Empty-State Flash asSnapshot waits for first Page before returning record_screen / get_latest_screenshot shows 150 ms empty screen Gate empty placeholder on LoadState.NotLoading AND itemCount == 0
Scroll Jump on Prepend / Refresh Positional keys look fine without active user scroll get_ui_hierarchy shows visible item IDs jumping after refresh Supply key = pagingItems.itemKey { it.id } in LazyColumn items()
Wiped Cache on Process Death Process stays alive across asSnapshot calls get_ui_hierarchy resets to feed_card_1 after am kill Return SKIP_INITIAL_REFRESH when cache is fresh; resolve anchorPosition
Unreachable retry() Footer LoadParams tested directly without insets or touch get_ui_hierarchy shows btn_paging_append_retry clipped or missing Render LoadState.Error inside a LazyColumn item(key = "append_error")
Half-Committed Room Keys In-memory single-thread Room hides race windows get_logcat shows APPEND loop firing page=2 repeatedly Wrap clearRemoteKeys, clearAll, and insertAll inside db.withTransaction

Cross-Surface Pagination Testing: Mobile App + Web Admin Console

Cross-surface pagination testing verifies that mutations triggered in a desktop web dashboard propagate cleanly into an Android app's Paging 3 feed. Because ScreenSync MCP exposes 197 web_* Chrome and Edge extension tools alongside 29 phone and desktop tools in one stdio server, Claude Code can test end-to-end backend pagination consistency in a single session.

Paginated mobile feeds rarely exist in isolation—content moderation tools, e-commerce catalogs, CRM ticket queues, and SaaS dashboards all manage items from a web browser while mobile clients paginate through them via REST or GraphQL cursors. A classic pagination bug surfaces when an admin creates, deletes, or reorders an item in the web portal while the mobile app holds Page 1 and Page 2 in Room: offset-based APIs (?page=2&limit=20) shift rows across page boundaries, causing duplicate or skipped cards on the next APPEND load.

Using ScreenSync MCP's Chrome and Edge browser extension alongside your physical Android device, Claude Code executes an end-to-end cursor consistency test:

  1. Load Page 1 on mobile: Claude Code verifies feed_card_1 through feed_card_20 on the Android phone via get_ui_hierarchy.
  2. Insert a record in the live web tab: Switching to ScreenSync MCP's web_* tools inside your real Chrome or Edge tab (where sensitive browser actions trigger a human approval prompt), Claude Code publishes a new top-sorted item in your staging admin panel.
  3. Trigger APPEND on Android: Claude Code calls control_swipe on the phone to fetch Page 2 (LoadType.APPEND).
  4. Detect offset drift automatically: If the API uses offset pagination instead of opaque keyset cursors, feed_card_20 shifts into Page 2 and appears twice in get_ui_hierarchy. Claude Code immediately flags the duplicate feed_card_20 node, inspects your backend query or PagingSource cursor logic in the repo, and proposes keyset pagination (after_id / created_at cursor) to eliminate boundary drift.

Comparing ScreenSync MCP with Other Android MCP Tools

Selecting an Android Model Context Protocol server for Paging 3 QA depends on whether you need zero-root MediaProjection streaming, live UI tree extraction, and unified browser automation in one local workflow. ScreenSync MCP delivers all three over a private local network without cloud device rentals or instrumentation APK rebuilds.

Teams evaluating Android MCP servers for Claude Code, Cursor, or VS Code agent mode generally choose between three architectures:

  • ScreenSync MCP (by EpsolDev): Pairs a free Android 7.0+ app (com.screensync.mcp) with a local Node.js 18+ hub (port 3000 HTTP + stdio MCP). Capture uses Android's MediaProjection API with no root and no ADB (~94 ms median LAN mirror in EpsolDev's tests), control uses ADB over USB or wireless debugging, and the same server includes 197 web_* browser tools alongside 29 mobile/desktop tools.
  • ADB-only MCP wrappers (scrcpy-mcp, Android-MCP): Wrap adb shell screencap or uiautomator commands over ADB without a dedicated Android MediaProjection capture app or integrated Chrome/Edge extension.
  • Cross-platform driver wrappers (mobile-mcp): Route actions through generic mobile automation drivers across emulators and devices, rather than offering a native Android MediaProjection + Compose/ADB + Chrome MV3 bridge.

Security and privacy boundaries are explicit in ScreenSync MCP: live screen frames travel strictly from your phone to your local desktop hub over your LAN (or adb reverse USB socket) and never pass through EpsolDev servers (Google Drive fallback is optional). Only the specific screenshots requested by Claude Code via get_latest_screenshot are transmitted to your chosen AI model provider for visual analysis—so always test against staging data rather than live production PII.

Production Checklist for Paging 3 QA with Claude Code

Running a standardized Paging 3 verification checklist before every release catches LazyColumn keying bugs, RemoteMediator transaction leaks, offline retry dead-ends, and process-death scroll resets on real Android hardware. Execute these six checks with Claude Code and ScreenSync MCP prior to merging pagination or feed refactors:

  • [ ] No Initial Empty-State Flash: get_latest_screenshot and record_screen confirm LoadState.Loading with itemCount == 0 never flashes an empty-state screen before Page 1 commits.
  • [ ] Stable Keys Under Refresh & Prepend: Every LazyColumn items() block defines key = pagingItems.itemKey { ... } and contentType, verified by get_ui_hierarchy delta checks before and after pull-to-refresh.
  • [ ] Atomic RemoteMediator Transactions: clearRemoteKeys(), clearAll(), and insertAll() execute inside db.withTransaction, with get_logcat showing single sequential MEDIATOR_COMMIT events per scroll boundary.
  • [ ] Offline Append Error & retry() Recovery: Disabling Wi-Fi/data via ADB with adb reverse tcp:3000 tcp:3000 active surfaces btn_paging_append_retry cleanly in get_ui_hierarchy without wiping cached pages, and tapping it resumes pagination upon reconnect.
  • [ ] Process-Death Scroll Preservation: Running adb shell am kill at Page 4 followed by relaunch restores the visible feed_card_* viewport without resetting LazyListState to item 0.
  • [ ] Cursor Stability Against Concurrent Writes: Inserting a record via web_* browser tools while Page 1 is loaded never produces duplicate cards in get_ui_hierarchy when Page 2 appends.

Ready to automate Paging 3 infinite-scroll, offline retry, and process-death testing on your own Android device with Claude Code? Download the free Android app on Google Play and connect the desktop hub using the links below.

Next steps

FAQ

Questions, answered

Why should teams test Jetpack Paging 3 on real Android hardware instead of asSnapshot() unit tests alone?

JVM asSnapshot() tests execute against deterministic in-memory dispatchers and skip real LazyColumn viewport recycling, touch fling physics, Room transaction contention, and system process death. Testing on physical Android devices with Claude Code and ScreenSync MCP exposes initial empty-state flashes, prefetch stalls, and scroll-position resets.

Does ScreenSync MCP require root access or ADB to capture Paging 3 screens?

Screen capture in ScreenSync MCP uses Android's native MediaProjection API after per-session user consent and requires no root and no ADB. Interactive device controls such as control_tap, control_swipe, and control_type execute over ADB via USB or wireless debugging from the desktop hub.

How does ScreenSync MCP keep streaming video when testing Paging 3 offline LoadState.Error states?

Because ScreenSync MCP runs locally on your workstation rather than in a remote cloud device farm, configuring adb reverse tcp:3000 tcp:3000 routes MediaProjection frames over the physical USB cable. Claude Code can disable Wi-Fi and cellular radios via ADB while continuing to inspect the offline retry UI.

How does Claude Code detect duplicate or skipped items across Paging 3 page boundaries?

By setting testTagsAsResourceId = true and tagging each row with feed_card_${item.id} alongside key = pagingItems.itemKey { it.id }, Claude Code queries get_ui_hierarchy before and after control_swipe scrolls. Comparing visible node IDs and PagingQA Logcat lines reveals duplicate offset rows or missing items immediately.

Can Claude Code test Paging 3 RemoteMediator behavior across Android process death?

Yes. Claude Code backgrounds the app, executes adb shell am kill to simulate OS memory reclamation, inspects persisted Room RemoteKeyEntity rows via ADB sqlite3, and relaunches the activity. It then uses get_ui_hierarchy and get_latest_screenshot to confirm scroll position restoration without an unwanted full refresh.

How many tools does ScreenSync MCP provide for mobile and browser pagination tests?

ScreenSync MCP provides 226 MCP tools in total: 29 phone and desktop tools (12 control_* tools, 3 os_* tools, and 14 capture and hub tools such as get_latest_screenshot, get_ui_hierarchy, get_logcat, and record_screen) plus 197 web_* browser tools through its Chrome and Edge extension.

What happens to screenshots captured during automated Paging 3 QA runs?

Live screen frames stream from the Android phone directly to the local Node.js hub on your network and never pass through EpsolDev servers, with optional Google Drive fallback. Whenever Claude Code or another AI agent calls get_latest_screenshot, that requested screenshot is sent to that agent's model provider.

Which Android versions and AI coding clients work with ScreenSync MCP?

The ScreenSync MCP Android app requires Android 7.0 or later and is free on Google Play. The Node.js 18+ desktop hub runs on Windows, macOS, and Linux over stdio for local Model Context Protocol clients including Claude Code, Claude Desktop, Cursor, and VS Code agent mode.

Written by

ScreenSync MCP team

The ScreenSync MCP team at EpsolDev builds the Android app, the desktop MCP hub and the browser extension that let AI agents see and control a real phone. These guides come out of that work.