perf(native): optimize iOS transcript refresh and add frame profiling

Preserve hosted rows while propagating current SwiftUI environments and render captures. Add differential refresh regressions, opt-in real-clock iOS/Android profiling, and reproducible performance results.

Validation: typecheck; CLI/hub/web/shared/relay suites (Web rerun with NODE_OPTIONS=--no-experimental-webstorage for Node 26/jsdom compatibility); existing iOS Debug/Release and Android regression runs.
This commit is contained in:
weishu
2026-09-10 16:22:36 +08:00
parent c2e3d16b7e
commit 0dcc70e7c7
13 changed files with 3242 additions and 13 deletions
+12
View File
@@ -81,8 +81,19 @@ android {
// null when no upload key is configured → unsigned release.
signingConfig = signingConfigs.findByName("release")
}
create("profile") {
initWith(getByName("release"))
// Optimized/non-debuggable, but unminified so diagnostic stacks
// and instrumentation access remain readable. Never distributed.
isMinifyEnabled = false
isShrinkResources = false
signingConfig = signingConfigs.getByName("debug")
matchingFallbacks += "release"
}
}
testBuildType = providers.gradleProperty("hapiTestBuildType").orElse("debug").get()
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
@@ -161,6 +172,7 @@ dependencies {
implementation(libs.androidx.compose.ui.tooling.preview)
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.ui.test.manifest)
add("profileImplementation", libs.androidx.compose.ui.test.manifest)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
androidTestImplementation(libs.androidx.test.runner)
@@ -0,0 +1,247 @@
package app.hapi.companion.feature.chat
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.view.Choreographer
import android.view.FrameMetrics
import android.view.MotionEvent
import android.view.Window
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.lifecycleScope
import androidx.test.core.app.ActivityScenario
import androidx.test.platform.app.InstrumentationRegistry
import app.hapi.companion.ui.markdown.LocalMarkdownRenderCache
import app.hapi.companion.ui.markdown.MarkdownRenderCache
import app.hapi.companion.ui.theme.HapiTheme
import app.hapi.data.store.ChatHistoryPagingState
import app.hapi.protocol.chat.AgentTextBlock
import app.hapi.protocol.chat.VisibleChatBlock
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
/** Opt-in diagnostics. Deliberately NO Compose test rule/virtual frame clock. */
class ChatFrameProfileTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private fun source(index: Int, rich: Boolean): String {
val paragraph = "Message $index. " + "Native transcript scrolling keeps the reading position stable. ".repeat(1 + index % 4)
if (!rich) return paragraph
return when (index % 4) {
0 -> "## Review $index\n\n$paragraph\n\n- **Stable identity** and `cached layout`\n- A [reference](https://example.com) with *details*\n- [x] Verified"
1 -> "### Code $index\n\n```swift\nfunc render() {\n" + (0..<14).joinToString("\n") { " let item$it = messages[$it] // row $index" } + "\n}\n```"
2 -> "| File | Added | Removed |\n| --- | ---: | ---: |\n" + (0..<10).joinToString("\n") { "| source-$index-$it.swift | ${it + 2} | 1 |" }
else -> "$paragraph\n\n> A longer explanation with **emphasis**.\n\n$paragraph"
}
}
private fun row(index: Int, text: String) = AgentTextBlock(
id = "profile-$index", localId = null, createdAt = index.toLong(), invokedAt = null,
text = text, meta = null,
)
private fun state(rows: List<VisibleChatBlock>) = ChatUiState(
sessionId = "frame-profile", header = ChatHeaderUi("Frame profile", subtitle = null, active = false, thinking = false),
flavor = null, basePath = "/workspace/hapi", blocks = rows, permissionOverrides = emptyMap(),
hasMore = true, isLoadingOlder = false, isSyncingTail = false, isInitialLoading = false,
loadFailed = false, warning = null, tailRevision = 0,
)
@Test fun profileRealFrames() {
assumeTrue("Opt in with -e hapiScrollProfile true", InstrumentationRegistry.getArguments().getString("hapiScrollProfile") == "true")
val output = File(instrumentation.targetContext.getExternalFilesDir(null), "scroll-profile").apply { mkdirs() }
val records = File(output, "frames.jsonl").apply { writeText("") }
for (scenarioName in listOf("plain", "rich", "rich-updates")) {
val sources = (0..<800).map { source(it, scenarioName != "plain") }
val updates = (0..<100).map { sources[799] + "\n\nStreaming revision $it" }
val cache = MarkdownRenderCache().apply { prepare(sources.toSet()) }
val state = mutableStateOf(state(sources.mapIndexed(::row)))
lateinit var list: LazyListState
ActivityScenario.launch(ComponentActivity::class.java).use { activity ->
activity.onActivity { host ->
host.setContent {
list = rememberLazyListState()
HapiTheme(darkTheme = false, dynamicColor = false) {
CompositionLocalProvider(LocalMarkdownRenderCache provides cache) {
ChatTranscript(
state.value, ChatHistoryPagingState(), 0, false,
onViewport = { _, _ -> }, onLayout = { _, _ -> },
onRetryHistory = {}, onJumpToLatest = {}, listState = list,
)
}
}
}
}
SystemClock.sleep(2_000)
for (repetition in 1..3) {
// Real touch first gives history intent, then place each
// repetition at the same row. Setup excluded from samples.
swipe(activity, duration = 300)
activity.onActivity { it.lifecycleScope.launch { list.scrollToItem(350, 0) } }
SystemClock.sleep(1_000)
val probe = FrameProbe()
var startIndex = 0
var width = 0
var height = 0
var refreshRate = 60f
shell("dumpsys gfxinfo ${instrumentation.targetContext.packageName} reset")
activity.onActivity { host ->
startIndex = list.firstVisibleItemIndex
width = host.window.decorView.width
height = host.window.decorView.height
@Suppress("DEPRECATION")
refreshRate = host.windowManager.defaultDisplay.refreshRate
probe.start(host.window)
if (scenarioName == "rich-updates") host.lifecycleScope.launch {
var revision = 0
while (isActive && probe.active.get()) {
state.value = state.value.copy(
blocks = state.value.blocks.dropLast(1) + row(799, updates[revision % updates.size]),
messagesVersion = state.value.messagesVersion + 1,
)
revision++
delay(100)
}
}
}
android.os.Trace.beginSection("HapiScroll:$scenarioName:$repetition")
repeat(8) {
swipe(activity, duration = 450)
SystemClock.sleep(250) // includes natural fling/deceleration
}
SystemClock.sleep(800)
android.os.Trace.endSection()
var endIndex = 0
activity.onActivity { host -> endIndex = list.firstVisibleItemIndex; probe.stop(host.window) }
probe.finish()
File(output, "$scenarioName-$repetition-gfxinfo.txt").writeText(shell("dumpsys gfxinfo ${instrumentation.targetContext.packageName} framestats"))
val record = probe.result(refreshRate.toDouble()).apply {
put("scenario", scenarioName); put("repetition", repetition); put("rows", 800)
put("viewportWidthPx", width); put("viewportHeightPx", height)
put("startIndex", startIndex); put("endIndex", endIndex)
put("api", android.os.Build.VERSION.SDK_INT)
put("metric", "window-frame-metrics-and-choreographer-not-presented-fps")
}
records.appendText(record.toString() + "\n")
val summary = JSONObject(record.toString()).apply { remove("framesMs"); remove("intervalsMs") }
android.util.Log.i("HapiFrameProfile", summary.toString())
assertTrue("Probe must scroll across rows", startIndex - endIndex > 5)
assertTrue("Must capture real rendered frames", record.getInt("renderedFrames") > 60)
}
}
}
}
private fun shell(command: String): String = instrumentation.uiAutomation.executeShellCommand(command).use {
android.os.ParcelFileDescriptor.AutoCloseInputStream(it).bufferedReader().readText()
}
private fun swipe(activity: ActivityScenario<ComponentActivity>, duration: Long) {
var width = 0
var height = 0
activity.onActivity { width = it.window.decorView.width; height = it.window.decorView.height }
val down = SystemClock.uptimeMillis()
fun send(action: Int, fraction: Float) {
val event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action, width * 0.5f, height * (0.22f + fraction * 0.56f), 0)
event.source = android.view.InputDevice.SOURCE_TOUCHSCREEN
try { instrumentation.sendPointerSync(event) } finally { event.recycle() }
}
android.os.Trace.beginSection("HapiGesture")
try {
send(MotionEvent.ACTION_DOWN, 0f)
for (step in 1..30) {
val wait = down + duration * step / 30 - SystemClock.uptimeMillis()
if (wait > 0) SystemClock.sleep(wait)
send(MotionEvent.ACTION_MOVE, step / 30f)
}
send(MotionEvent.ACTION_UP, 1f)
} finally {
android.os.Trace.endSection()
}
}
private class FrameProbe : Choreographer.FrameCallback {
val active = AtomicBoolean(false)
private val thread = HandlerThread("HapiFrameMetrics").apply { start() }
private val frames = mutableListOf<DoubleArray>()
private val intervals = mutableListOf<Double>()
private var droppedReports = 0
private var previous = 0L
private var began = 0L
private var ended = 0L
private val listener = Window.OnFrameMetricsAvailableListener { _, metrics, dropped ->
if (active.get() && metrics.getMetric(FrameMetrics.FIRST_DRAW_FRAME) == 0L) {
droppedReports += dropped
frames += doubleArrayOf(
metrics.getMetric(FrameMetrics.TOTAL_DURATION) / 1e6,
metrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION) / 1e6,
metrics.getMetric(FrameMetrics.DRAW_DURATION) / 1e6,
metrics.getMetric(FrameMetrics.SYNC_DURATION) / 1e6,
metrics.getMetric(FrameMetrics.COMMAND_ISSUE_DURATION) / 1e6,
)
}
}
fun start(window: Window) {
window.addOnFrameMetricsAvailableListener(listener, Handler(thread.looper))
began = System.nanoTime()
active.set(true)
Choreographer.getInstance().postFrameCallback(this)
}
override fun doFrame(frameTimeNanos: Long) {
if (!active.get()) return
val now = System.nanoTime()
if (previous != 0L) intervals += (now - previous) / 1e6
previous = now
Choreographer.getInstance().postFrameCallback(this)
}
fun stop(window: Window) {
ended = System.nanoTime()
active.set(false)
Choreographer.getInstance().removeFrameCallback(this)
window.removeOnFrameMetricsAvailableListener(listener)
thread.quitSafely()
}
fun finish() { thread.join() }
fun result(refreshRate: Double): JSONObject {
fun percentile(values: List<Double>, quantile: Double): Double =
values.sorted().let { if (it.isEmpty()) 0.0 else it[((it.size - 1) * quantile).toInt()] }
val total = frames.map { it[0] }
val seconds = (ended - began) / 1e9
return JSONObject().apply {
put("refreshRateHz", refreshRate); put("seconds", seconds)
put("renderedFrames", frames.size); put("droppedMetricReports", droppedReports)
put("callbackFPS", intervals.size / seconds)
put("intervalP95Ms", percentile(intervals, 0.95))
put("intervalP99Ms", percentile(intervals, 0.99))
put("frameP50Ms", percentile(total, 0.5)); put("frameP95Ms", percentile(total, 0.95))
put("frameP99Ms", percentile(total, 0.99)); put("maxFrameMs", total.maxOrNull())
put("framesOverBudget", total.count { it > 1000 / refreshRate })
put("framesOver50Ms", total.count { it > 50 })
put("layoutP95Ms", percentile(frames.map { it[1] }, 0.95))
put("drawP95Ms", percentile(frames.map { it[2] }, 0.95))
put("syncP95Ms", percentile(frames.map { it[3] }, 0.95))
put("commandP95Ms", percentile(frames.map { it[4] }, 0.95))
put("framesMs", JSONArray(frames.map { JSONArray(it.toList()) }))
put("intervalsMs", JSONArray(intervals))
}
}
}
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<profileable android:shell="true" />
</application>
</manifest>
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bash
# Dedicated disposable emulator. Never install into a connected personal device.
set -euo pipefail
cd "$(dirname "$0")/.."
sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}
if [ -z "$sdk" ] && [ -f local.properties ]; then sdk=$(sed -n 's/^sdk.dir=//p' local.properties); fi
: "${sdk:?Set ANDROID_HOME to an installed Android SDK}"
export ANDROID_HOME="$sdk"
output=${HAPI_PROFILE_OUTPUT:-$(mktemp -d /tmp/hapi-android-frames.XXXXXX)}
mkdir -p "$output"
output=$(cd "$output" && pwd)
export ANDROID_AVD_HOME
ANDROID_AVD_HOME=$(mktemp -d /tmp/hapi-profile-avd.XXXXXX)
serial=emulator-5584
pid=
cleanup() {
if [ -n "$pid" ]; then kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true; fi
rm -rf "$ANDROID_AVD_HOME"
}
trap cleanup EXIT
adb="$sdk/platform-tools/adb"
if "$adb" devices | grep -q "$serial"; then echo 'Test port occupied; refusing existing device'; exit 1; fi
./gradlew -PhapiTestBuildType=profile :app:assembleProfile :app:assembleProfileAndroidTest > "$output/build.log" 2>&1
system_image=${HAPI_PROFILE_SYSTEM_IMAGE:-system-images;android-35;google_apis_playstore;arm64-v8a}
printf 'no\n' | "$sdk/cmdline-tools/latest/bin/avdmanager" create avd -n HapiFrameProfile -k "$system_image" -p "$ANDROID_AVD_HOME/device"
cat >> "$ANDROID_AVD_HOME/device/config.ini" <<'EOF'
hw.lcd.width=1080
hw.lcd.height=1920
hw.lcd.density=420
hw.gpu.enabled=yes
EOF
gpu=${HAPI_PROFILE_GPU:-host}
printf 'system_image=%s\ngpu=%s\nbuild=profile (non-debuggable, unminified)\n' "$system_image" "$gpu" > "$output/environment.txt"
"$sdk/emulator/emulator" -avd HapiFrameProfile -no-window -no-audio -no-snapshot -no-boot-anim \
-gpu "$gpu" -port 5584 -memory 4096 -cores 4 > "$output/emulator.log" 2>&1 &
pid=$!
booted=false
for attempt in $(seq 1 120); do
if [ "$("$adb" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = 1 ]; then booted=true; break; fi
if ! kill -0 "$pid" 2>/dev/null; then cat "$output/emulator.log"; exit 1; fi
sleep 2
done
if [ "$booted" != true ]; then echo 'Emulator boot timed out'; exit 1; fi
"$adb" -s "$serial" shell input keyevent 82
"$adb" -s "$serial" shell settings put system screen_off_timeout 600000
# Synthetic UI needs no network. Avoid freshly booted Play Store downloads /
# dexopt competing with the app; this is ONLY our disposable emulator.
"$adb" -s "$serial" shell cmd connectivity airplane-mode enable
"$adb" -s "$serial" shell pm disable-user --user 0 com.android.vending >> "$output/environment.txt" 2>&1 || true
"$adb" -s "$serial" shell dumpsys SurfaceFlinger > "$output/surfaceflinger.txt"
"$adb" -s "$serial" install -r -t app/build/outputs/apk/profile/app-profile.apk
"$adb" -s "$serial" install -r -t app/build/outputs/apk/androidTest/profile/app-profile-androidTest.apk
sleep 30 # keep install/boot work out of the measured intervals
"$adb" -s "$serial" logcat -c
if [ "${HAPI_PROFILE_TRACE:-0}" = 1 ]; then
cat > "$output/perfetto.config" <<'EOF'
buffers { size_kb: 262144 fill_policy: RING_BUFFER }
duration_ms: 180000
data_sources { config { name: "android.surfaceflinger.frametimeline" } }
data_sources {
config {
name: "linux.ftrace"
ftrace_config {
atrace_apps: "run.hapi.companion"
atrace_categories: "gfx"
atrace_categories: "view"
ftrace_events: "sched/sched_switch"
ftrace_events: "sched/sched_waking"
}
}
}
data_sources { config { name: "linux.process_stats" } }
EOF
# Perfetto's SELinux domain cannot read /data/local/tmp on user images.
"$adb" -s "$serial" shell perfetto --background-wait --txt -c - \
-o /data/misc/perfetto-traces/hapi-scroll.pftrace < "$output/perfetto.config" > "$output/perfetto-start.txt"
fi
"$adb" -s "$serial" shell am instrument -w -r -e hapiScrollProfile true \
-e class app.hapi.companion.feature.chat.ChatFrameProfileTest \
run.hapi.companion.test/androidx.test.runner.AndroidJUnitRunner | tee "$output/instrumentation.log"
"$adb" -s "$serial" pull /sdcard/Android/data/run.hapi.companion/files/scroll-profile "$output/"
if [ "${HAPI_PROFILE_TRACE:-0}" = 1 ]; then
trace_pid=$(tr -d '\r' < "$output/perfetto-start.txt" | awk '/^[0-9]+$/ {print $1}')
if [ -n "$trace_pid" ]; then "$adb" -s "$serial" shell kill -INT "$trace_pid"; fi
sleep 3
"$adb" -s "$serial" pull /data/misc/perfetto-traces/hapi-scroll.pftrace "$output/"
fi
"$adb" -s "$serial" logcat -d > "$output/logcat.txt"
grep HapiFrameProfile "$output/logcat.txt" || true
grep -q '^OK (' "$output/instrumentation.log"
echo "Profile artifacts: $output"
+37
View File
@@ -0,0 +1,37 @@
-- Perfetto trace_processor: -q android/scripts/scroll-frame-summary.sql TRACE
-- Present cadence only during real drags; never divide frame count by idle time.
-- FrameTimeline Prediction Error / SurfaceFlinger Scheduling classifications in
-- an emulator are not a reliable app-jank score. Report app deadlines separately.
WITH phases AS (
SELECT id, name, ts, dur FROM slice WHERE name GLOB 'HapiScroll:*'
), gestures AS (
SELECT p.name AS phase, g.id, g.ts, g.dur
FROM phases p JOIN slice g
ON g.name = 'HapiGesture' AND g.ts >= p.ts AND g.ts + g.dur <= p.ts + p.dur
), frames AS (
SELECT g.phase, g.id AS gesture, a.ts + a.dur AS presented,
a.jank_type, a.on_time_finish
FROM gestures g JOIN actual_frame_timeline_slice a
ON a.ts + a.dur BETWEEN g.ts AND g.ts + g.dur
WHERE a.layer_name GLOB '*run.hapi.companion*'
AND a.dur > 0 AND a.present_type != 'Dropped Frame'
), intervals AS (
SELECT *, (presented - LAG(presented) OVER (PARTITION BY gesture ORDER BY presented)) / 1e6 AS gap_ms
FROM frames
)
SELECT phase,
COUNT(DISTINCT gesture) AS gestures,
COUNT(*) AS presented_frames,
ROUND(1000 * COUNT(gap_ms) / SUM(gap_ms), 2) AS present_cadence_fps,
ROUND(PERCENTILE(gap_ms, 50), 2) AS present_p50_ms,
ROUND(PERCENTILE(gap_ms, 95), 2) AS present_p95_ms,
ROUND(PERCENTILE(gap_ms, 99), 2) AS present_p99_ms,
SUM(CASE WHEN on_time_finish = 0 THEN 1 ELSE 0 END) AS app_late_finish,
SUM(CASE WHEN jank_type LIKE '%App Deadline Missed%' THEN 1 ELSE 0 END) AS app_deadline_missed
FROM intervals GROUP BY phase ORDER BY phase;
-- Must have all requested phases: a too-small ring buffer silently loses setup
-- and early scrolls even though the trace is otherwise parseable.
SELECT name FROM slice WHERE name GLOB 'HapiScroll:*' ORDER BY ts;
SELECT name, value, description FROM stats WHERE severity != 'info' AND value != 0;
+200
View File
@@ -0,0 +1,200 @@
# Native 聊天滚动:模拟器实测
日期:2026-09-10。业务代码基线:`5194271f`。
## 结论
1. **优先优化 iOS 的差量刷新与复杂内容测量,不继续盲目优化列表索引。**
普通文本接近 60 Hz;复杂 Markdown 稳定出现约 33 ms 的帧回调间隔。
叠加消息更新后进一步恶化。单变量实验已验证“刷新未变可见行”的额外成本。
2. **Android 必须区分应用工作与模拟器噪声。** 多数轮次接近 60 Hz,
但完整复测也出现过 47–52 FPS 和超过 600 ms 的长帧;不能只展示好看的轮次。
长帧调用链包含主线程等待 RenderThread 的 `postAndWait`,不应直接归因于
Compose 列表重组。保留原始异常数据,增加离线、调度记录的控制实验。
3. 定位轮的**诊断用简化优化已回滚**。后续落地了保留 hosting roots、桥接实时
renderer/environment 的差量刷新;见下文“iOS 优化落地”。没有冻结行高或
为跑分停止传递主题、字体、内容、交互环境。
## 测量边界
- 主机:Apple M4 Pro,14 核,48 GiB;macOS 26.6.2,Xcode 26.6。
- iOS:专用 iPhone 15 / iOS 26.5 Simulator,Release `-O` / whole-module
optimization,`ENABLE_TESTABILITY=YES`,显示回调请求 60 Hz。
- Android:专用 API 35 ARM64 模拟器,1080 × 1920 / 420 dpi,4 vCPU / 4 GiB;
`-gpu host`,日志确认 Apple M4 Pro / Metal,而不是旧脚本的 SwiftShader。
`profile` 构建:非 debuggable,未混淆,调试签名;不是商店分发 APK。
- 两个平台顺序运行,不同时压测。800 条合成消息,使用实际聊天行渲染器、
Markdown 缓存及原生列表,不是几何占位方块;每种场景重复 3 次。
- 普通文本;复杂 Markdown(标题、列表、14 行代码、10 行 × 3 列表格、引用);
复杂 Markdown + 每秒 10 次离屏尾消息更新。AST 在开始前预热。
- iOS:真实 CADisplayLink 驱动 1,800 pt/s、每轮 6 秒的连续滚动。
Android:真实 MotionEvent 拖动和自然减速,每轮 8 次;**不用 Compose 测试虚拟时钟**。
- 不包含 Hub/网络/消息归约耗时;没有覆盖分页到达、图片解码、键盘、120 Hz、
极长代码、真实用户会话或低端真机。不能跨平台直接比较数字,也不代表发行版验收。
### “FPS”分别指什么
- iOS 的 Instruments `Animation Hitches` 明确返回 **“Hitches is not supported
on this platform”**。因此下面是 **CADisplayLink 实际回调频率**,不是合成器
最终呈现 FPS。P95/P99 来自墙钟回调间隔;`>25 ms` 是诊断阈值,不是 Apple hitch 指标。
- Time Profiler attach 在本环境无响应,已终止;CPU 证据来自另一次独立的
macOS `sample` 1 ms 调用栈采样。带采样开销的运行不用于帧率基线。
- Android 同时记录 Choreographer 回调、Window.FrameMetrics、gfxinfo 和
Perfetto FrameTimeline。呈现频率仅计算 **HapiGesture 拖动区间内** 连续呈现的
间隔;不能拿整个测试时长(含停顿)除帧数。
- FrameTimeline 在此模拟器有大量 `Prediction Error` / `Early Present`,
不能把所有 `jank_type != None` 统计成应用掉帧。应用 deadline miss 单独报告。
各字段来自不同时间边界,FrameMetrics 超预算数不应等同 FrameTimeline missed 数。
## iOS 基线与单变量实验
| 场景 | 回调频率,三轮范围 | 回调间隔 P95 | >25 ms 间隔 / 全部间隔 |
| --- | ---: | ---: | ---: |
| 普通文本 | 59.83–59.84 /s | 16.72–16.73 ms | 3 / 1,079(0.28%) |
| 复杂 Markdown | 55.83–56.66 /s | 27.58–32.56 ms | 68 / 1,013(6.71%) |
| 复杂 Markdown + 10 Hz 更新 | 53.86–54.83 /s | 33.26–33.27 ms | 103 / 979(10.52%) |
独立 CPU 栈采样:32,440 个主线程样本,其中排除明确等待叶节点后 6,014 个。
路径占比可重叠,不是可相加的 CPU 分账,也不是精确耗时:
- `_UIHosting…` 路径:40.2%;`sizeThatFits`:32.8%;
`preferredLayoutAttributesFitting`:27.6%;富文本布局 `StyledText`:16.9%。
- `TranscriptCollectionController.drain()` 路径:19.9%。
- `TranscriptLayout`:2.3%。主线程未采到 `MarkdownBlockTree` 或 Highlightr 路径。
源码对应:`AnchoredTranscriptList.swift` 的 `drain()` 在任何配置更新时,把
**所有可见 ID** 加入 `reconfigureItems`,即使变化只有离屏尾消息。原意是刷新
SwiftUI 环境快照;代价是重复配置 hosting roots、自适应测量和富文本布局。
诊断实验只删除 `|| visibleIDs.contains($0.id)`,其他代码与输入不变,重新启动进程
重复三轮,然后恢复原文件:
| 场景 | 原均值 → 实验均值 | >25 ms 间隔数 |
| --- | ---: | ---: |
| 普通文本 | 59.84 → 59.84 /s | 3 → 3 |
| 复杂 Markdown | 56.22 → 56.11 /s | 68 → 70 |
| 复杂 Markdown + 更新 | **54.29 → 55.62 /s** | **103 → 79** |
证据支持“小而明确的更新路径收益”,不是消除所有卡顿。实验没有改复杂内容本身,
静态复杂列表也没有改善。**不能直接发布这一删行方案**:主题、Dynamic Type、
locale、basePath、链接/交互环境变化仍必须传递到已有 hosting cells。
## iOS 优化落地:保留 hosting roots
改动限于列表与聊天入口,无 Markdown/协议重写:
- `reconfigureItems` 只处理内容或宽度变化,不再无条件加入所有可见 ID。
- 每个 hosting root 保留轻量 SwiftUI wrapper,读取共享的 observable renderer。
最新 builder、basePath 等普通值捕获和 action captures 继续传入;SwiftUI 自己
比较返回的视图,而非让 UIKit 每次重新安装 hosting 配置。
- 在 `updateUIViewController` 读取 `context.environment`,统一桥接到已有与新建行。
不枚举可比较的环境键;主题、Dynamic Type、locale、方向、自定义服务都保留。
试验中发现:仅在逃逸 builder 中读取父视图的 `@Environment(\.self)`,可能漏掉
环境更新依赖。因此去掉聊天入口的手工快照,由列表负责传播。
- 快照串行化、锚点补偿、异步 self-sizing、隐藏页布局确认、重复 ID 防御不变。
**仍会更新轻量 wrapper;不是宣称 SwiftUI 零工作或跳过所有测量。**
新增回归覆盖:离屏更新的零可见 cell 重配置预算、可见行增高与锚点、回收后最新
内容、相同 Item 下的主题/basePath/链接 action 更新、语言/方向/字号变化及重新测量。
UIKit 自身可能在方向 trait 改变时重新请求 cell;这不属于无条件消息刷新。
复测使用相同 Release 场景,按“新实现 → 旧实现复跑 → 新实现复跑”顺序,均独立
进程、专用模拟器。本轮新增计时前的渲染截图和可见复杂行高度断言,已本地查看截图;
旧/新实现初始行高一致。截图在计时区间外,但可能影响暖机,**收益只与本轮同一
测试器的旧实现复跑比较,不用上一轮 54.29 /s 直接计算提升。**
| 场景 | 旧实现复跑,均值 | 新实现第 1 / 第 2 批,均值 | >25 ms:旧 / 新第 1 批 / 新第 2 批 |
| --- | ---: | ---: | ---: |
| 普通文本 | 59.83 /s | 59.84 / 59.84 /s | 3/1,078 / 3/1,079 / 3/1,080 |
| 复杂 Markdown | 59.73 /s | 59.34 / 59.45 /s | 5/1,078 / 12/1,070 / 10/1,073 |
| 复杂 Markdown + 更新 | 57.89 /s | 59.12 / 59.06 /s | 38/1,044 / 16/1,066 / 17/1,064 |
每批每场景三轮。合并新实现两批:更新场景均值 59.09 /s,较本轮旧实现约 +2.1%,
长间隔比例 3.64% → 1.55%。静态复杂场景没有改善,且略有回落;旧实现更新场景
也有 58.84、58.84、56.00 /s 的轮次差异。
因此主要确定性收益是**消除无关 cell 重配置**,不能据此承诺真机满帧。
本轮不增加复杂行高缓存、不改代码块/表格排版;继续保留动态测量正确性,后续用
真机长帧调用栈决定是否值得进一步优化复杂行。
最终校验:Debug **14 项通过**(含工作量断言);Release 两批各 **13 项通过**
(含 opt-in 帧测试)。Debug 有一项因主机休眠耗时约 650 秒:`pmset` 确认
13:16–13:27 的系统休眠,非应用长帧数据;Release 对应回归约 0.33 秒。
全部计时场景每轮约 6 秒,不把普通测试耗时作为帧性能证据。
原始记录:`/tmp/hapi-scroll-live-environment*`、`/tmp/hapi-scroll-baseline-control*`;
渲染预览和逐轮 JSON 留在各自 xcresult attachments,仅本地校验,未上传。
## Android:完整结果而非挑选最好轮次
初次运行,多数暖机轮的 FrameMetrics P95 为 4–7 ms,Choreographer 约 59.9 /s;
普通文本第一轮 P95 21.20 ms。此轮 64 MiB trace 环形缓冲只保留后五个场景;
应用 JSON/gfxinfo 九轮完整,但不把这份 trace 当成九轮完整证据。
扩大为 256 MiB,并加入真实拖动标记后的复测:
| 场景 / 轮次 | 拖动区间呈现频率 | 呈现间隔 P95 | 应用 deadline miss |
| --- | ---: | ---: | ---: |
| 普通文本 1 / 2 / 3 | 59.39 / 59.95 / 60.12 FPS | 24.90 / 19.21 / 18.10 ms | 3 / 0 / 0 |
| 复杂内容 1 / 2 / 3 | 51.66 / 49.55 / 60.13 FPS | 19.02 / 40.23 / 19.45 ms | 1 / 37 / 1 |
| 复杂内容 + 更新 1 / 2 / 3 | 59.78 / 59.60 / 47.58 FPS | 19.41 / 18.38 / 21.21 ms | 0 / 0 / 4 |
短采样窗口边界/时间戳抖动可让估计值略高于 60,不意味着设备超过刷新率。
最后一轮更新场景的 FrameMetrics 最大值 688.15 ms,不能用一个平均 FPS 隐藏它。
Trace 中有约 609 / 625 ms 的 `draw-VRI → postAndWait`,主线程等渲染线程;
也有长重组段。仅有 view/gfx 的 trace 无法判断这些段究竟在运行还是被抢占。
同期新模拟器的 GMS/Play Store 后台工作仍活跃;这只是环境竞争线索,不是定论。
控制实验:专用模拟器启用飞行模式、禁用 Play Store 自更新、等待 30 秒;
增加 `sched_switch` / `sched_waking` 和 process metadata。采到 495,548 条调度片段,
九个测试段均完整;**不修改应用业务代码**的结果:
| 场景 | 拖动区间呈现频率,三轮范围 | Window.FrameMetrics P95 | 应用 deadline miss |
| --- | ---: | ---: | ---: |
| 普通文本 | 60.04–60.13 FPS | 首轮 18.34 ms,后两轮 4.23–5.02 ms | 首轮 1,后两轮 0 |
| 复杂 Markdown | 60.00–60.05 FPS | 4.68–5.02 ms | 0 |
| 复杂 Markdown + 更新 | 59.32–59.75 FPS | 4.53–5.34 ms | 0 |
控制轮没有重现数百毫秒长帧;呈现间隔 P95 为 17.87–18.97 ms。所有运行的
FrameMetrics dropped reports 均为 0。结果支持**环境控制对 Android 模拟器测量
影响显著**,但多个环境变量一起改变,不能认定某个 GMS 任务就是唯一根因,
更不能声称应用优化消除了先前长帧。原始异常轮次仍保留。
## 下一轮优化顺序
1. **iOS 差量刷新已实现。** 数据/宽度变化走 diffable;环境和普通值捕获通过
live SwiftUI wrapper 传播,不再靠消息更新时重配所有可见行。继续保留新增回归。
2. **iOS:减少复杂行的重复测量。** 优先复用 renderer-ready 内容与 hosting 配置;
评估基于内容版本、宽度、字体的测量缓存。异步图片、展开态、代码高亮改变高度时
必须失效。更长 Markdown 可评估按块虚拟化;不要先重写已是二分查询的列表索引。
3. **Android:先归因首轮/偶发长帧。** 结合调度、RenderThread/GPU、冷/暖缓存,
再决定 Baseline Profile、文本布局缓存或复杂行预取。现有结果不足以支持
“把 LazyColumn 重写一遍”或“已稳定满帧”的结论。
4. 后续验收补真实手势 iOS / 快速 fling / 分页提交 / 图片 / 键盘,最后在真机
release/profile 构建上比较 P95/P99、deadline misses、内存;不把模拟器 FPS 设为 CI gate。
## 复测
```sh
# iOS:opt-in;默认 CI 跳过帧率诊断。脚本创建并删除自己的模拟器。
TEST_RUNNER_HAPI_SCROLL_PROFILE=1 ios/scripts/test-transcript.sh \
-configuration Release ENABLE_TESTABILITY=YES SWIFT_EMIT_LOC_STRINGS=NO \
-only-testing:HapiTests/TranscriptFrameProfileTests
# 可选:TEST_RUNNER_HAPI_SCROLL_SCENARIOS=rich,rich-updates
# Android:要求已安装对应 system image;所有 adb 操作绑定专用 emulator-5584。
ANDROID_HOME=/path/to/sdk HAPI_PROFILE_TRACE=1 \
HAPI_PROFILE_OUTPUT=/tmp/hapi-frame-run android/scripts/profile-transcript.sh
# Intel/Linux 主机替换为本机已安装的 x86_64 system image:
# HAPI_PROFILE_SYSTEM_IMAGE='system-images;android-35;google_apis;x86_64'
# 使用 Perfetto 官方 trace_processor 离线分析,不上传 trace:
trace_processor /tmp/hapi-frame-run/hapi-scroll.pftrace \
-q android/scripts/scroll-frame-summary.sql
```
Android trace 必须包含全部 9 个 `HapiScroll` 段与每段 8 个 `HapiGesture`。
本机 `ftrace_setup_errors=36` 为部分系统类别/事件不可用;已采到的应用段、
FrameTimeline 仍可使用,不能把缺失事件推断成零工作。
配套摘要:`performance/native-scroll-2026-09-10.json`。原始 JSON 数组 / gfxinfo /
Perfetto / xcresult / sample 位于本机 `/tmp/hapi-scroll-frame-*`,未提交大型 trace。
+17
View File
@@ -57,6 +57,15 @@ affected suffix's geometry, without allocating attributes for offscreen rows.
Attributes are cached lazily and never mutated after being handed to UIKit;
unchanged IDs/width do not rebuild geometry on a content-only refresh.
Only changed row values or widths request diffable reconfiguration. Existing
hosting roots read a shared observable renderer and the latest representable
environment; SwiftUI diffs their content without reinstalling every visible
hosting configuration. This preserves theme, Dynamic Type, locale, direction,
services, and action/value captures without an incomplete environment whitelist.
The row builder executes inside a SwiftUI body so row-owned observable reads
belong to the row. Dynamic heights still use UIKit self-sizing; no frozen-height
or measurement-result cache is introduced.
`ChatPresentationState` keeps expansion/form state outside recycled cells,
pruned to retained message/request IDs. Expanded tool groups become individual
display rows, without changing protocol groups. The per-chat Markdown cache
@@ -130,6 +139,11 @@ coordinator/store cancellation, retry, cursor, and retention behavior.
Stateful group-ID tests cover splits, inherited-ID collisions, prepends, and
stable recomputes. UIKit tests also verify that regrouping preserves both
groups and the existing reading anchor, plus duplicate-delivery handling.
`TranscriptRefreshTests` verifies that offscreen streaming does not reconfigure
unchanged visible cells, while visible edits resize, recycled rows see the
latest data, and equal items receive updated environments and action captures.
Debug counters also check the zero-configuration budget for ordinary context
updates; UIKit may request cells itself when layout-direction traits change.
Replay-gap tests cover same-epoch retention, epoch/reset replacement, and
trailing validation. App coordinators cover a slow invalidated page returning
after tail sync; Compose tests cover saved-screen and saved-instance-state
@@ -140,6 +154,9 @@ and restores expanded child-row anchors across navigation and saved state.
These are deterministic layout regressions, not proof of release-device FPS.
Real-clock simulator measurements, CPU sampling, differential-refresh results,
and limitations: [Simulator scroll profiling](native-chat-scroll-profile.md).
### Scroll work budgets
Measured before/after this optimization with dedicated simulators/emulators
File diff suppressed because it is too large Load Diff
@@ -21,7 +21,6 @@ private enum TranscriptRow: Identifiable, Equatable {
struct ChatTranscriptView: View {
let model: ChatModel
@Environment(\.self) private var environment
private var rows: [TranscriptRow] {
var rows: [TranscriptRow] = [.history(model.historyPaging.phase, model.hasMore)]
@@ -50,8 +49,8 @@ struct ChatTranscriptView: View {
},
onLayout: { version, progress in model.historyLaidOut(version: version, madeProgress: progress) }
) { row in
// HostingConfiguration creates a new root: inherit app services.
AnyView(rowView(row).environment(\.self, environment))
// The list bridges the current environment into its hosting roots.
AnyView(rowView(row))
}
.overlay(alignment: .bottomTrailing) {
if !model.followsTail || model.hasTrimmedTail || model.isJumpingToLatest {
@@ -0,0 +1,209 @@
import HapiUI
import Observation
import OSLog
import SwiftUI
import UIKit
import XCTest
@testable import Hapi
@testable import HapiProtocol
/// Opt-in, real-vsync diagnostic. No FPS assertion: host load affects Simulator.
/// CADisplayLink cadence is NOT compositor-presented FPS; correlate with Instruments.
@MainActor
final class TranscriptFrameProfileTests: XCTestCase {
struct Row: Identifiable, Equatable {
let id: String
let block: VisibleChatBlock
}
@Observable @MainActor
final class Driver {
var rows: [Row]
let cache = MarkdownRenderCache()
let presentation = ChatPresentationState()
init(rows: [Row]) { self.rows = rows }
}
private struct Harness: View {
let driver: Driver
var body: some View {
AnchoredTranscriptList(
items: driver.rows, historyVersion: 0, jumpToken: 0,
historyControlID: "history", onViewport: { _ in }, onLayout: { _, _ in }
) { row in
AnyView(ChatBlockCard(block: row.block, basePath: "/workspace/hapi")
.environment(\.hapiMarkdownCache, driver.cache)
.environment(\.chatPresentationState, driver.presentation)
.hapiTheme(.light))
}
}
}
private static func source(_ index: Int, rich: Bool) -> String {
let paragraph = "Message \(index). " + String(repeating: "Native transcript scrolling keeps the reading position stable. ", count: 1 + index % 4)
guard rich else { return paragraph }
switch index % 4 {
case 0: return "## Review \(index)\n\n\(paragraph)\n\n- **Stable identity** and `cached layout`\n- A [reference](https://example.com) with *details*\n- [x] Verified"
case 1:
let code = (0..<14).map { " let item\($0) = messages[\($0)] // row \(index)" }.joined(separator: "\n")
return "### Code \(index)\n\n```swift\nfunc render() {\n\(code)\n}\n```"
case 2:
return "| File | Added | Removed |\n| --- | ---: | ---: |\n" + (0..<10).map { "| source-\(index)-\($0).swift | \($0 + 2) | 1 |" }.joined(separator: "\n")
default: return "\(paragraph)\n\n> A longer explanation with **emphasis**.\n\n" + paragraph
}
}
private static func row(_ index: Int, text: String) -> Row {
let id = "profile-\(index)"
return Row(id: id, block: .block(.agentText(AgentTextBlock(
id: id, localId: nil, createdAt: index, invokedAt: nil,
durationMs: nil, usage: nil, model: nil, text: text, meta: nil
))))
}
func testProfileRealDisplayFrames() async throws {
try XCTSkipUnless(ProcessInfo.processInfo.environment["HAPI_SCROLL_PROFILE"] == "1",
"Run explicitly with TEST_RUNNER_HAPI_SCROLL_PROFILE=1; never a CI timing gate.")
let log = OSLog(subsystem: "run.hapi.profile", category: .pointsOfInterest)
let delay = Double(ProcessInfo.processInfo.environment["HAPI_SCROLL_PROFILE_DELAY"] ?? "0") ?? 0
print("HAPI_PROFILE_READY pid=\(ProcessInfo.processInfo.processIdentifier)")
try await Task.sleep(for: .seconds(delay))
let scenarios = (ProcessInfo.processInfo.environment["HAPI_SCROLL_SCENARIOS"] ?? "plain,rich,rich-updates").split(separator: ",").map(String.init)
for scenario in scenarios {
XCTAssertTrue(["plain", "rich", "rich-updates"].contains(scenario))
let sources = (0..<800).map { Self.source($0, rich: scenario != "plain") }
let driver = Driver(rows: sources.enumerated().map { Self.row($0.offset, text: $0.element) })
let updates = (0..<100).map { sources[799] + "\n\nStreaming revision \($0)" }
await driver.cache.prepare(sources)
let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
let window = UIWindow(windowScene: scene)
let host = UIHostingController(rootView: Harness(driver: driver))
window.rootViewController = host
window.makeKeyAndVisible()
defer { window.isHidden = true }
try await Task.sleep(for: .seconds(1))
func find(_ view: UIView) -> UICollectionView? {
if let collection = view as? UICollectionView { return collection }
return view.subviews.lazy.compactMap(find).first
}
let collection = try XCTUnwrap(find(host.view))
collection.delegate?.scrollViewWillBeginDragging?(collection)
collection.scrollToItem(at: IndexPath(item: 350, section: 0), at: .top, animated: false)
try await Task.sleep(for: .seconds(1))
let start = collection.contentOffset.y
let initialHeights = collection.visibleCells.map { $0.frame.height }.sorted()
if scenario != "plain" {
XCTAssertGreaterThan(initialHeights.max() ?? 0, 200,
"Rich rows must actually render and self-size, not remain empty estimates")
}
let preview = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
}
let previewAttachment = XCTAttachment(image: preview)
previewAttachment.name = "\(scenario)-rendered-transcript"
previewAttachment.lifetime = .keepAlways
add(previewAttachment)
print("HAPI_PROFILE_SCENARIO \(scenario)")
for repetition in 1...3 {
collection.contentOffset.y = start
try await Task.sleep(for: .milliseconds(500))
let label = "\(scenario)-\(repetition)"
let signpost = OSSignpostID(log: log)
os_signpost(.begin, log: log, name: "Transcript Scroll", signpostID: signpost, "%{public}s", label)
var previousRevision = -1
let probe = DisplayProbe(collection: collection, seconds: 6, speed: 1_800) { elapsed in
if scenario == "rich-updates" {
let revision = min(updates.count - 1, Int(elapsed * 10))
if revision != previousRevision {
previousRevision = revision
driver.rows[799] = Self.row(799, text: updates[revision])
}
}
}
let result = await probe.run()
os_signpost(.end, log: log, name: "Transcript Scroll", signpostID: signpost)
var record = result
record["scenario"] = scenario
record["repetition"] = repetition
record["rows"] = 800
record["viewportWidth"] = collection.bounds.width
record["viewportHeight"] = collection.bounds.height
record["initialVisibleHeights"] = initialHeights
record["maximumFramesPerSecond"] = window.screen.maximumFramesPerSecond
record["os"] = UIDevice.current.systemVersion
record["metric"] = "display-link-callback-cadence-not-presented-fps"
let data = try JSONSerialization.data(withJSONObject: record, options: [.sortedKeys])
print("HAPI_FRAME_PROFILE \(String(decoding: data, as: UTF8.self))")
let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json")
attachment.name = label
attachment.lifetime = .keepAlways
add(attachment)
XCTAssertGreaterThan(result["distancePoints"] as? Double ?? 0, 5_000, "Probe must actually scroll")
}
}
}
@MainActor
private final class DisplayProbe: NSObject {
let collection: UICollectionView
let seconds: Double
let speed: Double
let update: (Double) -> Void
var link: CADisplayLink?
var continuation: CheckedContinuation<[String: Any], Never>?
var began: Double?
var previous: Double?
var intervals: [Double] = []
var updateTimes: [Double] = []
var initialOffset = 0.0
init(collection: UICollectionView, seconds: Double, speed: Double, update: @escaping (Double) -> Void) {
self.collection = collection
self.seconds = seconds
self.speed = speed
self.update = update
}
func run() async -> [String: Any] {
await withCheckedContinuation { continuation in
self.continuation = continuation
initialOffset = collection.contentOffset.y
let link = CADisplayLink(target: self, selector: #selector(tick(_:)))
link.preferredFrameRateRange = CAFrameRateRange(minimum: 60, maximum: 60, preferred: 60)
self.link = link
link.add(to: .main, forMode: .common)
}
}
@objc func tick(_ link: CADisplayLink) {
let now = CACurrentMediaTime()
if began == nil { began = now }
let elapsed = now - began!
if let previous { intervals.append((now - previous) * 1_000) }
self.previous = now
if elapsed >= seconds {
link.invalidate()
self.link = nil
let sorted = intervals.sorted()
func percentile(_ p: Double) -> Double { sorted[min(sorted.count - 1, Int(Double(sorted.count - 1) * p))] }
let result: [String: Any] = [
"seconds": elapsed, "callbacks": intervals.count,
"callbackFPS": Double(intervals.count) / elapsed,
"intervalP50Ms": percentile(0.5), "intervalP95Ms": percentile(0.95),
"intervalP99Ms": percentile(0.99), "maxIntervalMs": sorted.last ?? 0,
"intervalsOver25Ms": intervals.filter { $0 > 25 }.count,
"intervalsOver50Ms": intervals.filter { $0 > 50 }.count,
"distancePoints": collection.contentOffset.y - initialOffset,
"offsetUpdateMaxMs": updateTimes.max() ?? 0,
"intervalsMs": intervals,
]
continuation?.resume(returning: result)
continuation = nil
return
}
collection.contentOffset.y = initialOffset + elapsed * speed
update(elapsed)
updateTimes.append((CACurrentMediaTime() - now) * 1_000)
}
}
}
+3 -2
View File
@@ -21,14 +21,15 @@ final class TranscriptGeometryTests: XCTestCase {
}
layout.prepare()
func verify(width: CGFloat) {
@MainActor func verify(width: CGFloat) {
var y: CGFloat = 10
let expected = ids.map { id -> CGRect in
let frame = CGRect(x: 12, y: y, width: width - 24, height: heights[id] ?? 100)
y = frame.maxY + 10
return frame
}
XCTAssertEqual(layout.collectionViewContentSize.height, y, accuracy: 0.01)
let actualHeight = layout.collectionViewContentSize.height
XCTAssertEqual(actualHeight, y, accuracy: 0.01)
let rects = stride(from: -500, to: Int(y) + 500, by: 377).map {
CGRect(x: 0, y: $0, width: Int(width), height: 844)
} + [.zero, .null, .infinite, CGRect(x: 1000, y: 0, width: 100, height: 100000)]
+188
View File
@@ -0,0 +1,188 @@
import Observation
import SwiftUI
import UIKit
import XCTest
@testable import HapiUI
@MainActor
final class TranscriptRefreshTests: XCTestCase {
struct Row: Identifiable, Equatable {
let id: String
var height: CGFloat = 120
}
struct Sample: Equatable {
let basePath: String
let dark: Bool
let size: DynamicTypeSize
let locale: String
let direction: LayoutDirection
}
@Observable @MainActor
final class Driver {
var rows = (0..<80).map { Row(id: String($0)) }
var version = 0
var basePath = "/before"
var dark = false
var size = DynamicTypeSize.large
var locale = Locale(identifier: "en")
var direction = LayoutDirection.leftToRight
var actionToken = 0
@ObservationIgnored var lastAction = -1
@ObservationIgnored var layouts: [Int] = []
@ObservationIgnored var samples: [String: Sample] = [:]
@ObservationIgnored var actions: [String: HapiOpenURLAction] = [:]
}
private struct Harness: View {
let driver: Driver
var body: some View {
let token = driver.actionToken
ListView(driver: driver)
.hapiTheme(driver.dark ? .dark : .light)
.environment(\.dynamicTypeSize, driver.size)
.environment(\.locale, driver.locale)
.environment(\.layoutDirection, driver.direction)
.environment(\.hapiOpenURL, HapiOpenURLAction { _ in
Task { @MainActor in driver.lastAction = token }
})
}
}
private struct ListView: View {
let driver: Driver
var body: some View {
// An ordinary value capture, not a live observable read in a row.
let basePath = driver.basePath
AnchoredTranscriptList(
items: driver.rows, historyVersion: driver.version, jumpToken: 0,
historyControlID: "history", onViewport: { _ in },
onLayout: { version, _ in driver.layouts.append(version) }
) { row in
AnyView(ProbeRow(row: row, basePath: basePath, driver: driver))
}
}
}
private struct ProbeRow: View {
let row: Row
let basePath: String
let driver: Driver
@Environment(\.dynamicTypeSize) private var size
var body: some View {
Text(row.id)
.frame(maxWidth: .infinity)
.frame(height: row.height + (size.isAccessibilitySize ? 60 : 0))
.background(Probe(id: row.id, basePath: basePath, driver: driver))
}
}
private struct Probe: UIViewRepresentable {
let id: String
let basePath: String
let driver: Driver
func makeUIView(context: Context) -> UIView { UIView() }
func updateUIView(_ view: UIView, context: Context) {
let environment = context.environment
driver.samples[id] = Sample(basePath: basePath, dark: environment.hapiTheme.isDark,
size: environment.dynamicTypeSize, locale: environment.locale.identifier,
direction: environment.layoutDirection)
driver.actions[id] = environment.hapiOpenURL
}
}
private func host(_ driver: Driver) throws -> (UIWindow, TranscriptCollectionController<Row>, UICollectionView) {
let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
let window = UIWindow(windowScene: scene)
let host = UIHostingController(rootView: Harness(driver: driver))
window.rootViewController = host
window.makeKeyAndVisible()
host.view.layoutIfNeeded()
func find(_ controller: UIViewController) -> TranscriptCollectionController<Row>? {
if let result = controller as? TranscriptCollectionController<Row> { return result }
return controller.children.lazy.compactMap(find).first
}
let controller = try XCTUnwrap(find(host))
return (window, controller, try XCTUnwrap(controller.view as? UICollectionView))
}
private func settle(_ condition: () -> Bool = { true }, file: StaticString = #filePath, line: UInt = #line) async {
for _ in 0..<100 {
try? await Task.sleep(for: .milliseconds(20))
if condition() {
try? await Task.sleep(for: .milliseconds(100))
return
}
}
XCTFail("Transcript did not settle", file: file, line: line)
}
private func browse(_ view: UICollectionView, index: Int) async {
view.delegate?.scrollViewWillBeginDragging?(view)
view.scrollToItem(at: IndexPath(item: index, section: 0), at: .top, animated: false)
await settle()
}
func testOffscreenUpdatesKeepVisibleHostingConfigurationsAndStillResizeChangedRows() async throws {
let driver = Driver()
let (window, controller, view) = try host(driver)
defer { window.isHidden = true }
await settle { driver.layouts.contains(0) }
await browse(view, index: 25)
let cell = try XCTUnwrap(view.cellForItem(at: IndexPath(item: 25, section: 0)))
let offset = cell.frame.minY - view.contentOffset.y
#if DEBUG
let configurations = controller.cellConfigurationCount
#endif
for version in 1...3 {
driver.rows[79].height += 20
driver.version = version
await settle { driver.layouts.contains(version) }
}
#if DEBUG
XCTAssertEqual(controller.cellConfigurationCount, configurations,
"Offscreen streaming must not reinstall unchanged visible hosting roots")
#endif
XCTAssertEqual(cell.frame.minY - view.contentOffset.y, offset, accuracy: 1)
driver.rows[25].height += 70
await settle { abs(cell.frame.height - 190) < 1 }
XCTAssertEqual(cell.frame.minY - view.contentOffset.y, offset, accuracy: 1)
await browse(view, index: 79)
let tail = try XCTUnwrap(view.cellForItem(at: IndexPath(item: 79, section: 0)))
XCTAssertEqual(tail.frame.height, 180, accuracy: 1, "Recycled cells must use the latest offscreen value")
}
func testEqualItemsReceiveLatestEnvironmentValueCapturesAndActions() async throws {
let driver = Driver()
let (window, controller, view) = try host(driver)
defer { window.isHidden = true }
await settle { driver.layouts.contains(0) }
await browse(view, index: 25)
#if DEBUG
let configurations = controller.cellConfigurationCount
#endif
driver.basePath = "/after"
driver.dark = true
driver.actionToken = 1
let expected = Sample(basePath: "/after", dark: true, size: .large, locale: "en", direction: .leftToRight)
await settle { driver.samples["25"] == expected }
XCTAssertEqual(driver.samples["25"], expected)
#if DEBUG
XCTAssertEqual(controller.cellConfigurationCount, configurations)
#endif
try XCTUnwrap(driver.actions["25"])(URL(string: "hapi-file://?path=test")!)
await settle { driver.lastAction == 1 }
// UIKit may itself request cells again when layout-direction traits
// change; only ordinary data/context updates have a zero-config budget.
driver.locale = Locale(identifier: "ar")
driver.direction = .rightToLeft
driver.size = .accessibility2
let recycled = Sample(basePath: "/after", dark: true, size: .accessibility2, locale: "ar", direction: .rightToLeft)
await settle { driver.samples["25"] == recycled }
let cell = try XCTUnwrap(view.cellForItem(at: IndexPath(item: 25, section: 0)))
XCTAssertEqual(cell.frame.height, 180, accuracy: 1, "Environment-only changes must still self-size")
await browse(view, index: 60)
XCTAssertEqual(driver.samples["60"], recycled)
}
}
@@ -1,4 +1,5 @@
#if os(iOS)
import Observation
import SwiftUI
import UIKit
import os
@@ -19,6 +20,7 @@ public struct AnchoredTranscriptList<Item: Identifiable & Equatable>: UIViewCont
public var onViewport: (TranscriptViewport) -> Void
public var onLayout: (Int, Bool) -> Void
public var content: (Item) -> AnyView
fileprivate var environment = EnvironmentValues()
public init(items: [Item], historyVersion: Int, jumpToken: Int, historyControlID: String,
onViewport: @escaping (TranscriptViewport) -> Void,
@@ -38,7 +40,9 @@ public struct AnchoredTranscriptList<Item: Identifiable & Equatable>: UIViewCont
}
public func updateUIViewController(_ controller: TranscriptCollectionController<Item>, context: Context) {
controller.update(self)
var next = self
next.environment = context.environment
controller.update(next)
}
}
@@ -204,6 +208,25 @@ private final class TranscriptCollectionView: UICollectionView {
}
}
/// Keep hosting roots alive across unrelated transcript updates. The small
/// SwiftUI wrapper reads the latest builder and inherited environment,
/// including action captures. SwiftUI can diff the resulting row instead of UIKit
/// reinstalling every visible hosting configuration and measuring it again.
@MainActor @Observable
private final class TranscriptContent<Item> {
var render: (Item) -> AnyView = { _ in AnyView(EmptyView()) }
var environment = EnvironmentValues()
}
private struct TranscriptHostedRow<Item>: View {
let item: Item
let content: TranscriptContent<Item>
var body: some View {
content.render(item).environment(\.self, content.environment)
}
}
public final class TranscriptCollectionController<Item: Identifiable & Equatable>: UIViewController, UICollectionViewDelegate where Item.ID == String {
private let layout = TranscriptLayout()
private lazy var collection = TranscriptCollectionView(frame: .zero, collectionViewLayout: layout)
@@ -218,6 +241,10 @@ public final class TranscriptCollectionController<Item: Identifiable & Equatable
private var lastJumpToken = 0
private var reportScheduled = false
private var lastViewport: TranscriptViewport?
private let content = TranscriptContent<Item>()
#if DEBUG
private(set) var cellConfigurationCount = 0
#endif
private let logger = Logger(subsystem: "run.hapi", category: "Transcript")
public override func loadView() { view = collection }
@@ -237,10 +264,13 @@ public final class TranscriptCollectionController<Item: Identifiable & Equatable
}
source = UICollectionViewDiffableDataSource<Int, String>(collectionView: collection) { [weak self] view, index, id in
let cell = view.dequeueReusableCell(withReuseIdentifier: "message", for: index)
guard let self, let item = self.values[id], let configuration = self.configuration else { return cell }
guard let self, let item = self.values[id] else { return cell }
#if DEBUG
self.cellConfigurationCount += 1
#endif
let width = max(1, view.bounds.width - 24)
cell.contentConfiguration = UIHostingConfiguration {
configuration.content(item)
TranscriptHostedRow(item: item, content: self.content)
.id(id)
.frame(width: width, alignment: .leading)
}.margins(.all, 0)
@@ -303,11 +333,7 @@ public final class TranscriptCollectionController<Item: Identifiable & Equatable
let oldIDs = Set(items.map(\.id))
let oldHeight = layout.collectionViewContentSize.height
let widthChanged = abs(configuredWidth - collection.bounds.width) > 0.5
// Hosting roots inherit a snapshot of SwiftUI's environment. Refresh
// only visible roots for context changes (theme, text size, basePath),
// in addition to rows whose value actually changed.
let visibleIDs = Set(collection.indexPathsForVisibleItems.compactMap { source.itemIdentifier(for: $0) })
let changed = next.items.filter { widthChanged || values[$0.id] != $0 || visibleIDs.contains($0.id) }.map(\.id)
let changed = next.items.filter { widthChanged || values[$0.id] != $0 }.map(\.id)
let structureChanged = items.map(\.id) != next.items.map(\.id)
let jump = next.jumpToken != lastJumpToken
lastJumpToken = next.jumpToken
@@ -315,6 +341,10 @@ public final class TranscriptCollectionController<Item: Identifiable & Equatable
// Capture at COMMIT, after any reader motion during the request.
layout.anchorForUpdate = layout.followsTail ? nil : captureAnchor()
configuration = next
// Do not compare/whitelist EnvironmentValues: custom services and
// closure captures must propagate too, even when every Item is equal.
content.render = next.content
content.environment = next.environment
items = next.items
values = nextValues
configuredWidth = collection.bounds.width