library-ui: add startup timing and post-first-frame deferral seam
- Commit
d204bff61fbb2efa56df4c585d2806ca36e58ad0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 18:21 UTC (16 hours ago)
- Parents
6954921
With the launcher preview window gone, cold start lands directly on the first composed frame, so that frame's cost is now user-visible in every app. The shared MaActivity shell previously gave apps no way to keep non-essential work off that frame and no record of how long the frame took. StartupTiming records activityCreate -> beforeContent -> contentSet -> firstFrame marks (first write wins, injected-clock StartupMarks core) and logs the elapsed total once per launch through the repo Log facade; MaActivity/MaFragmentActivity feed the marks, call reportFullyDrawn at the first draw, and expose deferAfterFirstFrame for work that must not gate the frame (companion sync starts, warm-ups). FirstFrameGate queues blocks until the first OnDraw, then posts them so the frame is never delayed by the deferred work itself. No behaviour change for any app: composition, themes and intent handling are untouched; the only new side effect is one log line per launch. Verified: :library:ui:testDebugUnitTest (StartupMarksTest) and :library:ui:lint pass.
Diff
library/ui/AGENTS.md
diff --git a/library/ui/AGENTS.md b/library/ui/AGENTS.mdindex f65a8e556f..579a52e425 100644--- a/library/ui/AGENTS.md+++ b/library/ui/AGENTS.md@@ -27,7 +27,8 @@ ## Key files ### Shell + scaffolds — start here-- com/vayunmathur/library/ui/MaActivity.kt — shared activity shell (incl. `MaFragmentActivity`)+- com/vayunmathur/library/ui/MaActivity.kt — shared activity shell (incl. `MaFragmentActivity`); `deferAfterFirstFrame` queues non-essential startup work past the first drawn frame+- com/vayunmathur/library/ui/StartupTiming.kt — permanent cold-start marks (activityCreate→firstFrame, logged via `Log`) + `FirstFrameGate`/`StartupMarks` - com/vayunmathur/library/ui/AppScaffold.kt - com/vayunmathur/library/ui/DetailScaffold.kt - com/vayunmathur/library/ui/LazyListScaffold.kt
library/ui/src/main/java/com/vayunmathur/library/ui/MaActivity.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MaActivity.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MaActivity.ktindex d8156cb0fd..5ec896325e 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MaActivity.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MaActivity.kt@@ -29,13 +29,27 @@ abstract class MaActivity : ComponentActivity() { /** False for the one TV activity that never drew edge-to-edge. */ protected open val edgeToEdge: Boolean = true + private val firstFrameGate = FirstFrameGate()+ override fun onCreate(savedInstanceState: Bundle?) {+ StartupTiming.mark(StartupMarks.ACTIVITY_CREATE) super.onCreate(savedInstanceState) if (edgeToEdge) applyEdgeToEdge() onCreateBeforeContent()+ StartupTiming.mark(StartupMarks.BEFORE_CONTENT) showContent() } + /**+ * Queues [block] to run right after the first frame is drawn, so+ * non-essential startup work (companion sync, warm-ups) never delays+ * the frame the user first sees. Use instead of doing that work+ * synchronously in [onCreateBeforeContent].+ */+ protected fun deferAfterFirstFrame(block: () -> Unit) {+ firstFrameGate.defer(window.decorView, block)+ }+ /** * Applies edge-to-edge. Override for a custom style — the camera forces a * black navigation bar because its UI is always dark.@@ -66,6 +80,8 @@ abstract class MaActivity : ComponentActivity() { Content() } }+ StartupTiming.mark(StartupMarks.CONTENT_SET)+ firstFrameGate.attach(this, window.decorView) } } @@ -83,13 +99,22 @@ abstract class MaFragmentActivity : FragmentActivity() { /** False when the app calls [showContent] itself once it is ready. */ protected open val autoSetContent: Boolean = true + private val firstFrameGate = FirstFrameGate()+ override fun onCreate(savedInstanceState: Bundle?) {+ StartupTiming.mark(StartupMarks.ACTIVITY_CREATE) super.onCreate(savedInstanceState) if (edgeToEdge) applyEdgeToEdge() onCreateBeforeContent()+ StartupTiming.mark(StartupMarks.BEFORE_CONTENT) if (autoSetContent) showContent() } + /** See [MaActivity.deferAfterFirstFrame]. */+ protected fun deferAfterFirstFrame(block: () -> Unit) {+ firstFrameGate.defer(window.decorView, block)+ }+ /** Applies edge-to-edge; override for a custom style. See [MaActivity.applyEdgeToEdge]. */ protected open fun applyEdgeToEdge() { enableEdgeToEdge()@@ -112,5 +137,7 @@ abstract class MaFragmentActivity : FragmentActivity() { Content() } }+ StartupTiming.mark(StartupMarks.CONTENT_SET)+ firstFrameGate.attach(this, window.decorView) } }
library/ui/src/main/java/com/vayunmathur/library/ui/StartupTiming.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/StartupTiming.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/StartupTiming.ktnew file mode 100644index 0000000000..6dba44ddfd--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/StartupTiming.kt@@ -0,0 +1,101 @@+package com.vayunmathur.library.ui++import android.app.Activity+import android.os.SystemClock+import android.view.View+import android.view.ViewTreeObserver+import com.vayunmathur.library.log.Log++/**+ * Permanent, lightweight cold-start timing for every app on the [MaActivity]+ * shell: marks from activity create through the first drawn frame, logged+ * once per launch through the repo log facade (no analytics backend).+ *+ * The pure mark/duration core is [StartupMarks] with an injected clock so+ * ordering and elapsed math are unit-testable on the host; [StartupTiming]+ * is the process-wide instance fed by `MaActivity`/`MaFragmentActivity`.+ */+class StartupMarks(private val clock: () -> Long) {+ private val marks = LinkedHashMap<String, Long>()++ /** Records [name] at the current clock value; first write wins. */+ fun mark(name: String) {+ if (name !in marks) marks[name] = clock()+ }++ /** Elapsed ms between two marks, or null when either is absent. */+ fun elapsed(from: String, to: String): Long? {+ val start = marks[from] ?: return null+ val end = marks[to] ?: return null+ return end - start+ }++ /** Ordered snapshot of mark name to elapsed-ms since the first mark. */+ fun snapshot(): Map<String, Long> {+ val origin = marks.values.firstOrNull() ?: return emptyMap()+ return marks.mapValues { it.value - origin }+ }++ companion object {+ const val ACTIVITY_CREATE = "activityCreate"+ const val BEFORE_CONTENT = "beforeContent"+ const val CONTENT_SET = "contentSet"+ const val FIRST_FRAME = "firstFrame"+ }+}++/** Process-wide startup marks, fed by the shared activity shells. */+object StartupTiming {+ private const val TAG = "StartupTiming"++ private val marks = StartupMarks { SystemClock.uptimeMillis() }++ fun mark(name: String) = marks.mark(name)++ /** Mark-to-first-frame elapsed ms for tests and callers; null pre-frame. */+ fun firstFrameElapsed(from: String = StartupMarks.ACTIVITY_CREATE): Long? =+ marks.elapsed(from, StartupMarks.FIRST_FRAME)++ internal fun onFirstFrame(activity: Activity) {+ marks.mark(StartupMarks.FIRST_FRAME)+ val total = marks.elapsed(StartupMarks.ACTIVITY_CREATE, StartupMarks.FIRST_FRAME)+ Log.status(TAG, "${activity.javaClass.simpleName} first frame in ${total}ms marks=${marks.snapshot()}")+ }+}++/**+ * One-shot first-frame gate: queues blocks until the host view draws its+ * first frame, then runs them (posted, so the frame itself is never+ * delayed). Work that is not needed for the first frame — companion sync+ * starts, catalog warm-ups — belongs behind this gate, not in+ * `onCreateBeforeContent` on the main thread.+ */+class FirstFrameGate {+ private val pending = mutableListOf<() -> Unit>()+ private var fired = false++ /** Runs [block] after the first frame, or posts it now if already fired. */+ fun defer(view: View, block: () -> Unit) {+ if (fired) {+ view.post(block)+ } else {+ pending += block+ }+ }++ /** Attaches the one-shot draw listener that releases queued blocks. */+ fun attach(activity: Activity, view: View) {+ view.viewTreeObserver.addOnDrawListener(object : ViewTreeObserver.OnDrawListener {+ override fun onDraw() {+ view.viewTreeObserver.removeOnDrawListener(this)+ if (fired) return+ fired = true+ StartupTiming.onFirstFrame(activity)+ runCatching { activity.reportFullyDrawn() }+ val blocks = pending.toList()+ pending.clear()+ view.post { blocks.forEach { it() } }+ }+ })+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/StartupMarksTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/StartupMarksTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/StartupMarksTest.ktnew file mode 100644index 0000000000..24e6c94803--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/StartupMarksTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.library.ui++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Pure mark/elapsed math behind [StartupTiming], with a fake clock. */+class StartupMarksTest {++ @Test fun elapsedBetweenMarksUsesInjectedClock() {+ var now = 1_000L+ val marks = StartupMarks { now }+ marks.mark(StartupMarks.ACTIVITY_CREATE)+ now = 1_040L+ marks.mark(StartupMarks.BEFORE_CONTENT)+ now = 1_260L+ marks.mark(StartupMarks.FIRST_FRAME)+ assertEquals(260L, marks.elapsed(StartupMarks.ACTIVITY_CREATE, StartupMarks.FIRST_FRAME))+ assertEquals(220L, marks.elapsed(StartupMarks.BEFORE_CONTENT, StartupMarks.FIRST_FRAME))+ }++ @Test fun firstWriteWinsAndMissingMarksYieldNull() {+ var now = 100L+ val marks = StartupMarks { now }+ marks.mark(StartupMarks.ACTIVITY_CREATE)+ now = 999L+ marks.mark(StartupMarks.ACTIVITY_CREATE)+ assertEquals(mapOf(StartupMarks.ACTIVITY_CREATE to 0L), marks.snapshot())+ assertNull(marks.elapsed(StartupMarks.ACTIVITY_CREATE, StartupMarks.FIRST_FRAME))+ }++ @Test fun snapshotIsElapsedSinceFirstMarkInOrder() {+ var now = 500L+ val marks = StartupMarks { now }+ marks.mark(StartupMarks.ACTIVITY_CREATE)+ now = 530L+ marks.mark(StartupMarks.CONTENT_SET)+ now = 575L+ marks.mark(StartupMarks.FIRST_FRAME)+ assertEquals(+ listOf(StartupMarks.ACTIVITY_CREATE, StartupMarks.CONTENT_SET, StartupMarks.FIRST_FRAME),+ marks.snapshot().keys.toList(),+ )+ assertEquals(75L, marks.snapshot()[StartupMarks.FIRST_FRAME])+ }+}