diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index dfcee030..abc58b13 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -38,11 +38,15 @@ jobs: - uses: gradle/actions/setup-gradle@v4 - name: Protocol tests (pure JVM, fixtures-driven) run: ./gradlew :core:protocol:test :core:data:testDebugUnitTest :app:testDebugUnitTest - - name: Assemble debug APK - run: ./gradlew :app:assembleDebug + - name: Assemble debug APK and lint + run: ./gradlew :app:assembleDebug :app:lintDebug transcript-layout: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + api-level: [29, 36] steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 @@ -57,7 +61,7 @@ jobs: sudo udevadm trigger --name-match=kvm - uses: reactivecircus/android-emulator-runner@v2 with: - api-level: 29 + api-level: ${{ matrix.api-level }} arch: x86_64 disable-animations: true script: cd android && ./gradlew :app:connectedDebugAndroidTest diff --git a/android/README.md b/android/README.md index a1250d0f..c9a1b247 100644 --- a/android/README.md +++ b/android/README.md @@ -57,17 +57,27 @@ only the needed projects: ./gradlew --no-configuration-cache --configure-on-demand :core:protocol:test ``` -CI (`.github/workflows/android.yml`) runs the protocol tests and -`:app:assembleDebug` on every PR touching `android/**` or `shared/fixtures/**`. +CI (`.github/workflows/android.yml`) runs protocol/data/app unit tests, +`:app:assembleDebug`, `:app:lintDebug`, and Compose instrumentation on API 29 +and API 36 for PRs touching `android/**` or `shared/fixtures/**`. ## Tool previews -Plan proposals (`ExitPlanMode` / `exit_plan_mode`) start fully expanded, rendering -the complete `input.plan` Markdown before approval controls. Users can still fold -the card. Plan documents are prewarmed in the chat Markdown cache and do not use -the ordinary tool-output paging budget; raw input/result remains under Source. +Ordinary chat tools stay compact summaries. Tap a tool or tool group to open a native +Navigation Compose page; Back returns one level, Close returns to the chat. +Groups start at their latest tool, retain their position when returning from +details, and never follow streaming updates automatically. The **Latest tool** +toolbar action scrolls explicitly. Agent processes have their own page with +lazy child rows. Approvals remain in the conversation or a live process page; +ordinary tool detail pages are read-only. -Expanded cards recognize namespaced command/script/patch calls, unwrap common +Plan proposals (`ExitPlanMode` / `exit_plan_mode`) start fully expanded in the +conversation, rendering the complete `input.plan` Markdown before approval +controls. Tapping the header folds the card. Plan documents are prewarmed in the +chat Markdown cache and do not use the ordinary tool-output paging budget; raw +input/result remains under Source. + +Details recognize namespaced command/script/patch calls, unwrap common nested result envelopes, and keep command exit/status metadata visible. File reads use source-language highlighting; web/agent prose uses Markdown. **Source** reveals the original input/result, including fields omitted from the preview. @@ -79,10 +89,67 @@ historical results; live permission answers take precedence. Answered cards avoid duplicate results, but retain errors and the full input/result/answers under **Source**. The pending answer form remains unchanged. -Long inputs and outputs load in 20,000-character parts with **Copy full content** -and **Load more content**, never silent truncation. Large diffs/Markdown use -paged source rather than eagerly rendering the entire document. JSON formatting -and output preparation run off the UI thread. +Tool inputs/outputs display one part at a time, up to 20,000 Unicode graphemes +or 400 source lines. Previous/Next replace the mounted part; visited parts do +not accumulate. Large diffs/Markdown use paged source. JSON formatting and +output preparation run off the UI thread. File mutation details also offer +**View current file**, distinct from the recorded tool input/result. + +Inspectors share the conversation's pipeline and SSE subscription. Opening one +freezes tail following, cancels hidden history loading and recording, and hides +the keyboard. Returning retains the transcript anchor. Trimmed selections remain +readable as labeled snapshots; an epoch reset closes obsolete inspectors. + +## Long messages and reading layout + +User prompts remain inline through 8,000 graphemes and 120 source lines. Larger +prompts show a 2,000-grapheme / 24-line preview and **View full message** opens a +reader with one 4,000-grapheme / 80-line part mounted. Pagination preserves +whitespace, CRLF, emoji and combining sequences exactly; character counts refer +to Unicode graphemes, not UTF-16 offsets. + +**Copy full content** uses the clipboard up to 64 Ki UTF-16 code units. Larger +content, or a failed clipboard operation, offers UTF-8 file export through +FileProvider and Android's sharesheet; Binder receives a URI, not the text. +Exports older than 24 hours are cleaned on the next export. + +Body/composer/user text uses 16sp/24sp, code/diff/terminal 14sp/20sp, captions +12sp/16sp. Content and composer share a centered 720dp reading column with +16dp minimum side margins. Bubble widths use actual container constraints, +including split-screen; Android font scaling remains enabled. + +## Connection status and home filters + +The chat subtitle reserves its height. **Reconnecting · Tap to retry** appears +after four continuous foreground seconds of outage; retry/backoff transitions +do not restart that grace period. Transport state is separate from message +events. Default-network/interface/route changes wake reconnect immediately, +preserving replay cursors; background retries defer until foreground. A local +hub route does not need Android's internet-validation capability. + +Home keeps the Sessions title and new-session FAB. **Filters** opens a Material +3 single-selection sheet. Choices come from all sessions, including historical +machines; names/IDs determine ordering, never counts. Duplicate names include +IDs; unnamed and unknown machines are labeled. The applied filter has a Clear +action, is transient per home/hub, and is cleared when no longer valid. +The home holder follows the active connection instance, releasing the previous +store and filter even when switching back to a previously used hub URL. + +Pairing and Settings both link to the [privacy policy](https://hapi.run/docs/privacy). +These controls and notices ship in English and Simplified Chinese. + +### Validation status (2026-09-12) + +Protocol/data/app JVM suites: 707 tests passed. Debug APK, instrumentation APK +and lint passed. API 29: 19 chat/reader regressions passed, including large-font +pagination, source/answer rendering, exact clipboard text, and FileProvider URI +export. The opt-in frame probe was skipped. + +The local API 36 software emulator completed boot but Android killed the +instrumentation process for a startup ANR before any tests ran; system services +also timed out on this host without KVM. API 36 remains pending the CI job with +KVM. No 60/120 Hz device frame-time, memory, or predictive-back measurements are +claimed by these checks. ## Pairing diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatFrameProfileTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatFrameProfileTest.kt index 53774bd4..926b4e3b 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatFrameProfileTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatFrameProfileTest.kt @@ -22,11 +22,19 @@ 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 app.hapi.protocol.chat.UserTextBlock +import app.hapi.protocol.chat.ToolGroupBlock +import app.hapi.protocol.chat.ToolGroupingOptions +import app.hapi.protocol.chat.buildVisibleChatBlocks +import app.hapi.companion.feature.chat.blocks.previewToolCall import java.io.File import java.util.concurrent.atomic.AtomicBoolean import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonPrimitive import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertTrue @@ -60,15 +68,36 @@ class ChatFrameProfileTest { loadFailed = false, warning = null, tailRevision = 0, ) + private fun tools(revision: Int): ToolGroupBlock = buildVisibleChatBlocks( + (1..200).map { index -> + previewToolCall("profile-tool-$index", "Read", input = mapOf("file_path" to "/repo/file-$index.kt")).also { + if (index == 200) it.tool = it.tool.copy(state = "running", result = JsonPrimitive("output ".repeat(10_000) + revision)) + } + }, ToolGroupingOptions(hasMoreMessages = false), + ).filterIsInstance().single() + + private fun heapBytes(): Long = Runtime.getRuntime().let { it.totalMemory() - it.freeMemory() } + @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")) { + for (scenarioName in listOf("plain", "rich", "rich-updates", "long-message", "tool-group-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))) + val longText = "Long user message with preserved whitespace.\r\n".repeat(25_000) + val projection = TranscriptProjection() + val initialRows = sources.mapIndexed { index, source -> + when { + scenarioName == "long-message" && index % 20 == 0 -> UserTextBlock( + "profile-$index", null, index.toLong(), null, longText, null, null, null, null, + ) + scenarioName == "tool-group-updates" && index == 340 -> tools(0) + else -> row(index, source) + } + } + val state = mutableStateOf(state(projection.project(initialRows))) lateinit var list: LazyListState ActivityScenario.launch(ComponentActivity::class.java).use { activity -> activity.onActivity { host -> @@ -97,6 +126,7 @@ class ChatFrameProfileTest { var width = 0 var height = 0 var refreshRate = 60f + val heapBefore = heapBytes() shell("dumpsys gfxinfo ${instrumentation.targetContext.packageName} reset") activity.onActivity { host -> startIndex = list.firstVisibleItemIndex @@ -105,11 +135,16 @@ class ChatFrameProfileTest { @Suppress("DEPRECATION") refreshRate = host.windowManager.defaultDisplay.refreshRate probe.start(host.window) - if (scenarioName == "rich-updates") host.lifecycleScope.launch { + if (scenarioName == "rich-updates" || scenarioName == "tool-group-updates") host.lifecycleScope.launch { var revision = 0 while (isActive && probe.active.get()) { + val next = withContext(Dispatchers.Default) { + if (scenarioName == "tool-group-updates") projection.project(initialRows.mapIndexed { index, block -> + if (index == 340) tools(revision) else block + }) else state.value.blocks.dropLast(1) + row(799, updates[revision % updates.size]) + } state.value = state.value.copy( - blocks = state.value.blocks.dropLast(1) + row(799, updates[revision % updates.size]), + blocks = next, messagesVersion = state.value.messagesVersion + 1, ) revision++ @@ -128,11 +163,16 @@ class ChatFrameProfileTest { 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")) + File(output, "$scenarioName-$repetition-memory.txt").writeText(shell("dumpsys meminfo ${instrumentation.targetContext.packageName}")) 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("heapBeforeBytes", heapBefore); put("heapAfterBytes", heapBytes()) + put("nativeHeapAllocatedBytes", android.os.Debug.getNativeHeapAllocatedSize()) + put("longMessageUtf16Units", if (scenarioName == "long-message") longText.length else 0) + put("inspectedGroupTools", if (scenarioName == "tool-group-updates") 200 else 0) put("metric", "window-frame-metrics-and-choreographer-not-presented-fps") } records.appendText(record.toString() + "\n") diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatTranscriptTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatTranscriptTest.kt index 535fc810..fd53ee72 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatTranscriptTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/ChatTranscriptTest.kt @@ -188,25 +188,26 @@ class ChatTranscriptTest { assertFollowing() } - private fun mountWithExpandedGroup(restoration: StateRestorationTester? = null): ToolGroupBlock { + private fun mountWithGroupSummary(restoration: StateRestorationTester? = null): ToolGroupBlock { val tools = (1..12).map { previewToolCall("group-child-$it", "Read", input = mapOf("file_path" to "file-$it.txt")) } val group = buildVisibleChatBlocks(tools, ToolGroupingOptions(hasMoreMessages = false)) .filterIsInstance().single() assertTrue(!group.defaultOpen) mount(rows(0..24) + group + rows(25..79), restoration) - browse(26, 0) + // Keep the preceding row outside the content-padding/spacing band. + // Exercise a partially visible summary, not an item-boundary ambiguity. + browse(26, 20) compose.onNodeWithText("12 tools").performClick() compose.waitForIdle() - // Anchor to a child row, not an ordinary row whose index could happen - // to survive losing the group's expansion map. - compose.runOnIdle { scope.launch { list.scrollToItem(32, 17) } } - compose.waitForIdle() - assertEquals("group-child-6", anchor().first) + // Tapping a summary cannot change transcript membership or height. + assertEquals(group.id, anchor().first) + compose.onNodeWithTag("chat-row-group-child-1").assertDoesNotExist() + compose.runOnIdle { assertEquals(82, list.layoutInfo.totalItemsCount) } return group } - @Test fun navigationReturnPreservesExpandedChildrenAndTheirReadingAnchor() { - mountWithExpandedGroup() + @Test fun navigationReturnPreservesGroupSummaryAnchor() { + mountWithGroupSummary() val before = anchor() compose.runOnIdle { shown.value = false } compose.waitForIdle() @@ -215,18 +216,18 @@ class ChatTranscriptTest { assertHistoryRestored(before) } - @Test fun savedInstanceStateRestoresExpandedChildrenBeforeRestoringTheListIndex() { + @Test fun savedInstanceStateRestoresGroupSummaryAnchor() { val restoration = StateRestorationTester(compose) - mountWithExpandedGroup(restoration) + mountWithGroupSummary(restoration) val before = anchor() viewportReports.set(emptyList()) restoration.emulateSavedInstanceStateRestore() assertHistoryRestored(before) } - @Test fun removedGroupsDoNotRestoreStaleExpansionFlags() { + @Test fun groupReappearanceNeverAddsInlineChildren() { val restoration = StateRestorationTester(compose) - val group = mountWithExpandedGroup(restoration) + val group = mountWithGroupSummary(restoration) compose.runOnIdle { state.value = state.value.copy(blocks = rows(0..79), messagesVersion = 1) } diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt new file mode 100644 index 00000000..f56ae53b --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/InspectionReadersTest.kt @@ -0,0 +1,135 @@ +package app.hapi.companion.feature.chat + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.* +import androidx.compose.ui.test.junit4.StateRestorationTester +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import android.app.Activity +import android.app.Instrumentation +import android.content.ClipboardManager +import android.content.Intent +import android.net.Uri +import androidx.test.platform.app.InstrumentationRegistry +import app.hapi.companion.R +import app.hapi.companion.ui.components.FullTextAction +import app.hapi.companion.feature.chat.blocks.previewToolCall +import app.hapi.companion.ui.theme.HapiTheme +import app.hapi.protocol.chat.* +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import java.util.concurrent.atomic.AtomicReference + +class InspectionReadersTest { + @get:Rule val compose = createComposeRule() + + @Test fun androidGraphemePagingPreservesEmojiCombiningCharactersAndCrLf() { + // Also runs on API 29's regex implementation, independently of the host JVM. + val units = listOf("👩🏽‍💻", "e\u0301", "🇨🇳", "\r\n", " ", "中") + val text = units.joinToString("").repeat(100) + val pages = mutableListOf() + var start = 0 + while (start < text.length) { + val page = readTextPage(text, start, TextBudget(1, 2)) + assertTrue(page.end > start) + pages += page.text + start = page.end + } + assertEquals(List(100) { units }.flatten(), pages) + assertEquals(text, pages.joinToString("")) + assertEquals(2_000, messagePreview("x".repeat(1_000_000)).text.length) + } + + @Test fun largeFontReaderMountsOnlyTheSelectedPageAndRestoresIt() { + val restore = StateRestorationTester(compose) + val text = "a".repeat(4_000) + "b".repeat(4_000) + "c".repeat(992_000) + restore.setContent { + val density = LocalDensity.current.density + CompositionLocalProvider(LocalDensity provides Density(density, fontScale = 2f)) { + HapiTheme { + Box(Modifier.width(360.dp).fillMaxHeight()) { MessageReader(text, false, {}, {}) } + } + } + } + compose.onNodeWithTag("reader-text").assertTextEquals("a".repeat(4_000)) + compose.onNodeWithTag("reader-next").assertIsDisplayed().performClick() + compose.onNodeWithTag("reader-text").assertTextEquals("b".repeat(4_000)) + compose.onAllNodesWithTag("reader-text").assertCountEquals(1) + restore.emulateSavedInstanceStateRestore() + compose.onNodeWithTag("reader-text").assertTextEquals("b".repeat(4_000)) + compose.onNodeWithTag("reader-previous").assertIsDisplayed().performClick() + compose.onNodeWithTag("reader-text").assertTextEquals("a".repeat(4_000)) + compose.onNodeWithTag("inspection-close").assertIsDisplayed() + } + + private fun group(count: Int): ToolGroupBlock = buildVisibleChatBlocks( + (1..count).map { previewToolCall("tool-$it", "Read", input = mapOf("file_path" to "/repo/file-$it.kt")) }, + ToolGroupingOptions(hasMoreMessages = false), + ).filterIsInstance().single() + + @Test fun toolBrowserStartsAtLatestButDoesNotFollowUpdatesWhileReading() { + val inspected = mutableStateOf(Inspected(group(200), false)) + var selected: String? = null + compose.setContent { + HapiTheme { ToolGroupBrowser(inspected.value, "/repo", { selected = it }, {}, {}) } + } + compose.onNodeWithTag("inspection-tool-tool-200").assertIsDisplayed() + compose.onNodeWithTag("inspection-tools").performScrollToIndex(30) + compose.onNodeWithTag("inspection-tool-tool-31").assertIsDisplayed() + compose.runOnIdle { inspected.value = Inspected(group(201), false) } + compose.onNodeWithTag("inspection-tool-tool-31").assertIsDisplayed().performClick() + compose.runOnIdle { assertEquals("tool-31", selected) } + compose.onNodeWithTag("inspection-tool-tool-201").assertDoesNotExist() + compose.onNodeWithTag("inspection-latest-tool").performClick() + compose.onNodeWithTag("inspection-tool-tool-201").assertIsDisplayed() + compose.runOnIdle { inspected.value = inspected.value.copy(stale = true) } + compose.onNodeWithTag("inspection-notice").assertIsDisplayed() + } + + @Test fun fullContentUsesExactClipboardTextOrAReadableGrantedUri() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + val source = mutableStateOf(" 👩🏽‍💻\r\nexact clipboard text\t") + val launched = AtomicReference() + val monitor = object : Instrumentation.ActivityMonitor() { + override fun onStartActivity(intent: Intent?): Instrumentation.ActivityResult? { + if (intent?.action != Intent.ACTION_CHOOSER) return null + launched.set(intent) + // Verify the system handoff without opening a sharing target. + return Instrumentation.ActivityResult(Activity.RESULT_CANCELED, null) + } + } + instrumentation.addMonitor(monitor) + try { + compose.setContent { HapiTheme { FullTextAction(source.value, compact = true) } } + compose.onNodeWithContentDescription(context.getString(R.string.chat_copy_full_content)).performClick() + compose.runOnIdle { + assertEquals(source.value, context.getSystemService(ClipboardManager::class.java).primaryClip!!.getItemAt(0).text.toString()) + source.value = "exact export 👩🏽‍💻\r\n".repeat(50_000) + } + compose.onNodeWithContentDescription(context.getString(R.string.chat_export_full_content)).performClick() + compose.waitUntil(10_000) { launched.get() != null } + @Suppress("DEPRECATION") + val send = launched.get()!!.getParcelableExtra(Intent.EXTRA_INTENT)!! + @Suppress("DEPRECATION") + val uri = send.getParcelableExtra(Intent.EXTRA_STREAM)!! + assertEquals(Intent.ACTION_SEND, send.action) + assertEquals("text/plain", send.type) + assertEquals("content", uri.scheme) + assertEquals(uri, send.clipData!!.getItemAt(0).uri) + assertTrue(send.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION != 0) + assertFalse(send.hasExtra(Intent.EXTRA_TEXT)) + assertEquals(source.value, context.contentResolver.openInputStream(uri)!!.bufferedReader(Charsets.UTF_8).use { it.readText() }) + } finally { + instrumentation.removeMonitor(monitor) + } + } +} diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/PlanProposalTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/PlanProposalTest.kt index afa41680..93be5e55 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/PlanProposalTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/PlanProposalTest.kt @@ -38,8 +38,13 @@ class PlanProposalTest { @Test fun plansStartExpandedUpdateInPlaceAndKeepSourceAndErrors() { val block = mutableStateOf(previewToolCall("proposal", "ExitPlanMode", input = mapOf("plan" to "# 实施计划\n\nRead **input.plan**."))) block.value = block.value.withTool(block.value.tool.copy(result = JsonNull)) + val projection = TranscriptProjection() compose.setContent { - HapiTheme { Column(Modifier.verticalScroll(rememberScrollState())) { ToolCallBlockView(block.value, null) } } + HapiTheme { + Column(Modifier.verticalScroll(rememberScrollState())) { + ToolCallBlockView(projection.project(listOf(block.value)).single() as ToolCallBlock, null) + } + } } compose.onNodeWithText("实施计划").assertIsDisplayed() compose.onNodeWithText("Read input.plan.").assertIsDisplayed() diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt index c04fb79c..26e8e5d4 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/chat/QuestionDetailsTest.kt @@ -54,6 +54,9 @@ class QuestionDetailsTest { compose.onNodeWithText("after tests").performScrollTo().assertIsDisplayed() compose.onNodeWithText("duplicate result").assertDoesNotExist() compose.onNodeWithText("Source").performScrollTo().performClick() + // Source JSON prepares off-main; wait for the content above Answers + // to acquire its final height before checking scroll-to visibility. + compose.waitUntil(10_000) { compose.onAllNodesWithText("\"questions\"", substring = true).fetchSemanticsNodes().isNotEmpty() } compose.onNodeWithText("Answers").performScrollTo().assertIsDisplayed() compose.onNodeWithText("Source").performScrollTo().performClick() compose.runOnIdle { tool.value = tool.value.copy(state = "error", result = JsonPrimitive("answer delivery failed")) } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c36f842c..78987b62 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -4,6 +4,7 @@ + 菜单 设置 + Hub 切换 hub 配对另一个 hub… 退出登录 @@ -541,4 +542,31 @@ 答案 自定义答案 备注 + 查看完整消息 + 完整消息 + 上一段 + 下一段 + 第 %1$d 段 + 重试导出 + 导出全文 + 已复制 + 关闭阅读页面 + 只读快照:此记录已不在当前消息窗口中。 + 更早的调用尚未加载,请返回会话加载历史消息。 + 工具详情 + 此内容暂不可用,请返回会话重新加载。 + 最新工具 + 查看当前文件 + 查看完整输入 + 查看过程 · %1$d 步 + 子任务过程 + 查看图片 + 正在重新连接… 点按重试 + 筛选 + 清除筛选 + 机器 · %1$s + 机器:%1$s + 隐私政策 + 没有可打开此链接的应用。 + 已处理 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 03778240..0da34f37 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -48,6 +48,7 @@ Menu Settings + Hub Switch hub Pair another hub… Sign out @@ -535,4 +536,30 @@ Answers Custom answer Note + View full message + Full message + Previous part + Next part + Part %1$d + Retry export + Export full text + Copied + Close reader + Read-only snapshot. This record is no longer in the current message window. + Earlier calls are not loaded. Return to the conversation to load older history. + Tool details + This content is unavailable. Return to the conversation to load it again. + Latest tool + View current file + View full input + View process · %1$d steps + Agent process + Show image + Reconnecting… Tap to retry + Filters + Clear filter + Machine · %1$s + Machine: %1$s + Privacy Policy + No app can open this link. diff --git a/android/app/src/main/res/xml/attachment_file_paths.xml b/android/app/src/main/res/xml/attachment_file_paths.xml index 054c8eb4..97fd17b7 100644 --- a/android/app/src/main/res/xml/attachment_file_paths.xml +++ b/android/app/src/main/res/xml/attachment_file_paths.xml @@ -3,6 +3,7 @@ cache/attachments/camera-*.jpg handed to TakePicture via FileProvider, deleted right after ingest. --> + diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatInspectionStateTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatInspectionStateTest.kt new file mode 100644 index 00000000..6c6a5ca6 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatInspectionStateTest.kt @@ -0,0 +1,110 @@ +package app.hapi.companion.feature.chat + +import app.hapi.companion.feature.chat.blocks.previewToolCall +import app.hapi.protocol.chat.* +import kotlin.test.* +import kotlinx.serialization.json.JsonPrimitive + +class ChatInspectionStateTest { + private fun tool(id: String, output: String = "first", state: String = "running") = + previewToolCall(id, "Read", state = state, input = mapOf("file_path" to "/repo/$id.kt")).also { + it.tool = it.tool.copy(result = JsonPrimitive(output)) + } + + private fun group(tools: List) = buildVisibleChatBlocks( + tools, ToolGroupingOptions(hasMoreMessages = false), + ).filterIsInstance().single() + + @Test fun `selected content follows live updates then retains a read only snapshot`() { + val state = ChatInspectionState() + val first = tool("read-1") + val message = UserTextBlock("prompt", null, 0, null, " exact\r\ntext ", null, null, null, null) + state.update(listOf(first, message)) + state.retainTool(first.id) + state.retainMessage(message.id) + val updated = tool(first.id, "latest", "completed") + state.update(listOf(updated, message)) + assertSame(updated, state.tool(first.id)?.value) + assertFalse(state.tool(first.id)!!.stale) + state.update(emptyList()) + assertSame(updated, state.tool(first.id)?.value) + assertTrue(state.tool(first.id)!!.stale) + assertEquals(message.text, state.message(message.id)?.value?.text) + assertTrue(state.message(message.id)!!.stale) + state.clearSelections() + assertNull(state.tool(first.id)) + assertNull(state.message(message.id)) + } + + @Test fun `missing group preserves membership while remaining tools keep updating`() { + val state = ChatInspectionState() + val members = (1..12).map { tool("read-$it") } + val original = group(members) + state.update(listOf(original)) + state.retainGroup(original.id) + val remaining = tool("read-12", "new result", "completed") + state.update(listOf(remaining)) + val retained = state.group(original.id)!! + assertTrue(retained.stale) + assertEquals(members.map { it.id }, retained.value.tools.map { it.id }) + assertSame(remaining, retained.value.tools.last()) + assertTrue(state.tool("read-1")!!.stale) + assertFalse(state.tool("read-12")!!.stale) + state.retainTool("read-1") + state.update(emptyList()) + assertEquals("first", (state.tool("read-1")!!.value.tool.result as JsonPrimitive).content) + state.invalidate() + assertNull(state.group(original.id)) + assertNull(state.tool("read-1")) + assertEquals(1L, state.reset.value) + } + + @Test fun `transcript summaries reuse identity during output updates without modifying detail`() { + val projection = TranscriptProjection() + val first = tool("read-1") + val firstProjection = projection.project(listOf(first)).single() as ToolCallBlock + assertNull(firstProjection.tool.result) + assertNotNull(first.tool.result) + val updated = tool(first.id, "x".repeat(1_000_000)) + assertSame(firstProjection, projection.project(listOf(updated)).single()) + val completed = tool(first.id, "complete", "completed") + assertNotSame(firstProjection, projection.project(listOf(completed)).single()) + val grouped = group((1..12).map { tool("group-$it") }) + val summary = projection.project(listOf(grouped)).single() as ToolGroupBlock + assertTrue(summary.tools.isEmpty()) + assertEquals(12, grouped.tools.size) + val outputUpdate = group(grouped.tools.map { tool(it.id, "changed") }) + assertSame(summary, projection.project(listOf(outputUpdate)).single()) + } + + @Test fun `inline plan proposals retain results and refresh diagnostics during output updates`() { + for (name in listOf("ExitPlanMode", "exit_plan_mode")) { + val projection = TranscriptProjection() + fun proposal(result: String) = previewToolCall( + "proposal", name, state = ToolState.ERROR, input = mapOf("plan" to "# Review this plan"), + ).also { it.tool = it.tool.copy(result = JsonPrimitive(result)) } + + val first = proposal("Plan failed to apply") + val firstProjection = projection.project(listOf(first)).single() as ToolCallBlock + assertEquals(first.tool.input, firstProjection.tool.input) + assertEquals(first.tool.result, firstProjection.tool.result) + + val updated = proposal("Updated failure details") + val updatedProjection = projection.project(listOf(updated)).single() as ToolCallBlock + assertNotSame(firstProjection, updatedProjection) + assertEquals(updated.tool.result, updatedProjection.tool.result) + } + } + + @Test fun `epoch replacement clears old selection and publishes new live records atomically`() { + val state = ChatInspectionState() + state.update(listOf(tool("old")), epoch = 1L) + state.retainTool("old") + val fresh = tool("fresh") + state.update(listOf(fresh), epoch = 2L) + assertEquals(1L, state.reset.value) + assertNull(state.tool("old")) + assertSame(fresh, state.tool("fresh")?.value) + assertFalse(state.tool("fresh")!!.stale) + } +} diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt index 414f26f1..97a46aa9 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/ChatViewModelTest.kt @@ -269,7 +269,8 @@ private fun detailSession(): Session = Session( /** Transport that hands each connection a handshake verdict from [verdicts] (last repeats). */ private class ScriptedTransport(private val verdicts: List) : SseTransport { - private var connects = 0 + var connects = 0 + private set override fun open(url: String, lastEventId: String?) = flow { val verdict = verdicts.getOrElse(connects) { verdicts.last() } @@ -336,6 +337,54 @@ private class Harness( @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) class ChatViewModelTest { + @Test + fun `inspection cancels hidden history demand and keeps one session subscription`() = runTest { + val transport = ScriptedTransport(listOf("ok")) + val gate = CompletableDeferred() + // Model an HTTP response already crossing the cancellation boundary. + val api = object : FakeMessagesApi() { + override suspend fun getMessages(sessionId: String, query: MessagesQuery): MessagesResponse = + if (query is MessagesQuery.Before) withContext(kotlinx.coroutines.NonCancellable) { + super.getMessages(sessionId, query) + } else super.getMessages(sessionId, query) + } + val h = Harness(this, transport, api) + api.tailResponses += MessagesResponse( + listOf(agentMessage("latest", 10, 10_000, "latest")), + page("latest", true, nextBeforeAt = 10_000, nextBeforeSeq = 10), + ) + api.beforePage = MessagesResponse( + listOf(agentMessage("older", 9, 9_000, "older")), + page("before", true, nextBeforeAt = 9_000, nextBeforeSeq = 9), + ) + api.beforeGate = gate + h.viewModel.start() + h.viewModel.uiState.first { it.blocks.isNotEmpty() } + runCurrent() + h.viewModel.readingViewportChanged(false, true) + runCurrent() + assertEquals(1, api.queries.value.filterIsInstance().size) + h.viewModel.beginInspection() + // Layout callbacks from the exiting destination must be ignored. + h.viewModel.readingViewportChanged(true, true) + gate.complete(Unit) + runCurrent() + val store = h.messageWindows.open(SESSION_ID) + assertEquals(MessageViewMode.History, store.state.value.viewMode) + assertEquals(listOf("latest"), store.state.value.messages.map { it.id }) + assertEquals(1, transport.connects) + assertEquals(1, api.queries.value.filterIsInstance().size) + h.viewModel.setTranscriptVisible(true) + h.viewModel.start() // Host re-entry / rotation is idempotent. + runCurrent() + assertEquals(1, api.queries.value.filterIsInstance().size) + h.viewModel.readingViewportChanged(false, true) + h.viewModel.uiState.first { it.historyVersion == 1L } + assertEquals(2, api.queries.value.filterIsInstance().size) + assertEquals(1, transport.connects) + h.viewModel.stop() + } + @Test fun `Default workers cannot mutate paging state outside the UI dispatcher`() = runTest { val workers = CoroutineScope(SupervisorJob() + Dispatchers.Default) diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/chat/TextPagingTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/TextPagingTest.kt new file mode 100644 index 00000000..2ce59830 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/chat/TextPagingTest.kt @@ -0,0 +1,38 @@ +package app.hapi.companion.feature.chat + +import org.junit.Assert.* +import org.junit.Test + +class TextPagingTest { + @Test fun ordinaryMultiscreenMessagesStayComplete() { + for (source in listOf("x".repeat(8_000), ("line\n".repeat(119) + "end"))) { + assertEquals(source, messagePreview(source).text) + } + assertEquals(2_000, messagePreview("x".repeat(8_001)).end) + val lines = "x\n".repeat(120) + "end" + assertTrue(messagePreview(lines).end < lines.length) + } + + @Test fun pagesPreserveGraphemesAndExactWhitespace() { + val atoms = listOf("👨‍👩‍👧‍👦", "👩🏽‍💻", "e\u0301", "🇨🇳", "\r\n", "中", " ", "\t") + val source = atoms.joinToString("").repeat(40) + var position = 0 + val parts = mutableListOf() + while (position < source.length) { + val page = readTextPage(source, position, TextBudget(1, 2)) + assertTrue(page.end > position) + assertTrue(page.text in atoms) + parts += page.text + position = page.end + } + assertEquals(source, parts.joinToString("")) + } + + @Test fun giantSingleLinesAndNewlinesHaveBoundedLayoutInput() { + val giant = "x".repeat(1_000_000) + assertEquals(2_000, messagePreview(giant).text.length) + assertEquals(4_000, readTextPage(giant).text.length) + assertTrue(readTextPage("\n".repeat(1_000_000)).text.length <= 80) + assertEquals(TextPage("", 0), readTextPage("")) + } +} diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListViewModelTest.kt index 301105f6..906523c3 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListViewModelTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListViewModelTest.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.runCurrent // ------------------------------------------------------------------ fakes -- @@ -168,6 +169,42 @@ private fun TestScope.buildViewModel( // ------------------------------------------------------------------ tests -- class SessionListViewModelTest { + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + @Test + fun `vanished filter stays cleared when sessions return and is isolated per home`() = runTest { + val (viewModel, sessions, machines) = buildViewModel() + sessions.set(summary("one", machineId = "m1"), summary("two", machineId = "m2")) + viewModel.uiState.first { it.rows.size == 2 } + viewModel.setMachineFilter("m1") + viewModel.uiState.first { it.activeMachineFilter == "m1" } + val (otherHome) = buildViewModel(sessions, machines) + assertNull(otherHome.uiState.first { it.rows.size == 2 }.activeMachineFilter) + sessions.set(summary("two", machineId = "m2")) + viewModel.uiState.first { it.rows.size == 1 && it.activeMachineFilter == null } + runCurrent() + sessions.set(summary("one", machineId = "m1"), summary("two", machineId = "m2")) + assertNull(viewModel.uiState.first { it.rows.size == 2 }.activeMachineFilter) + } + + @Test + fun `machine choices stay name ordered across count changes and include historical unknowns`() = runTest { + val (viewModel, sessions, machines) = buildViewModel() + machines.backing.value = listOf( + machine("z", "z", "Zulu"), machine("a", "a", " Devbox "), machine("b", "b", "devbox"), + ) + sessions.set( + summary("z1", machineId = "z"), summary("a1", machineId = "a"), summary("b1", machineId = "b"), + summary("old", machineId = "retired", active = false), summary("unknown"), + ) + val first = viewModel.uiState.first { it.rows.size == 5 }.machineFilters + assertEquals(listOf("a", "b", "z", "retired", UNKNOWN_MACHINE_ID), first.map { it.id }) + assertEquals(listOf("Devbox · a", "devbox · b"), first.take(2).map { it.label }) + assertTrue(first.first { it.id == "retired" }.unnamed) + sessions.set(*sessions.backing.value.toTypedArray(), summary("z2", machineId = "z"), summary("z3", machineId = "z")) + val updated = viewModel.uiState.first { it.rows.size == 7 }.machineFilters + assertEquals(first.map { it.id }, updated.map { it.id }) + assertEquals(3, updated.first { it.id == "z" }.sessionCount) + } @Test fun `uiState maps rows with titles meta and unread`() = runTest { @@ -194,8 +231,10 @@ class SessionListViewModelTest { // Meta = `project · machine`: last two path segments, then the // machine label (displayName wins; unlisted machines shorten the id; // shown because several machines are known and no filter is active). - assertEquals("repo/app · Devbox", byId.getValue("s1").meta) - assertEquals("repo/app · offline-", byId.getValue("s2").meta) + assertEquals("repo/app", byId.getValue("s1").meta) + assertEquals("Devbox", byId.getValue("s1").machine?.label) + assertEquals("repo/app", byId.getValue("s2").meta) + assertTrue(byId.getValue("s2").machine!!.unnamed) assertEquals("repo/tail-name", byId.getValue("s3").meta) // No baseline seeded (no successful refresh yet) → activity is unread. @@ -212,12 +251,12 @@ class SessionListViewModelTest { ) var state = viewModel.uiState.first { it.rows.size == 3 } - assertTrue(state.showMachineFilterBar) + assertTrue(state.hasMachineFilters) assertEquals(listOf("m1", "m2"), state.machineFilters.map { it.id }) assertEquals(listOf(2, 1), state.machineFilters.map { it.sessionCount }) // Unfiltered multi-machine view carries the machine in the meta line… - assertEquals("repo/app · m1", state.rows.first { it.id == "s1" }.meta) + assertEquals("m1", state.rows.first { it.id == "s1" }.machine?.id) viewModel.setMachineFilter("m1") state = viewModel.uiState.first { it.activeMachineFilter == "m1" } @@ -238,7 +277,7 @@ class SessionListViewModelTest { sessions.set(summary("s1", machineId = "m1"), summary("s2", machineId = "m1")) viewModel.setMachineFilter("m9") val state = viewModel.uiState.first { it.rows.size == 2 } - assertFalse(state.showMachineFilterBar) + assertFalse(state.hasMachineFilters) assertNull(state.activeMachineFilter) // A single machine is not worth naming on every row. assertEquals(listOf("repo/app", "repo/app"), state.rows.map { it.meta }) diff --git a/android/core/data/src/main/kotlin/app/hapi/data/sse/AndroidNetworkMonitor.kt b/android/core/data/src/main/kotlin/app/hapi/data/sse/AndroidNetworkMonitor.kt new file mode 100644 index 00000000..67ee696c --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/sse/AndroidNetworkMonitor.kt @@ -0,0 +1,49 @@ +package app.hapi.data.sse + +import android.content.Context +import android.net.ConnectivityManager +import android.net.LinkProperties +import android.net.Network +import java.io.Closeable + +/** One monitor per active hub; no internet-validation or metering gate. */ +class AndroidNetworkMonitor(context: Context, private val onRoute: (NetworkRoute) -> Unit) : Closeable { + private val manager = context.getSystemService(ConnectivityManager::class.java) + private var current: Network? = manager.activeNetwork + + private fun publish(network: Network?, properties: LinkProperties? = network?.let(manager::getLinkProperties)) { + onRoute(NetworkRoute( + networkId = network?.networkHandle, + interfaceName = properties?.interfaceName, + routes = properties?.routes?.map { it.toString() }?.toSet().orEmpty(), + addresses = properties?.linkAddresses?.map { it.toString() }?.toSet().orEmpty(), + )) + } + + private val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + current = network + // API 26+ delivers link properties immediately after availability. + // Wait for that snapshot: querying here can race, publishing a + // partial route and reconnecting twice for a single network change. + } + + override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { + if (network == current) publish(network, properties) + } + + override fun onLost(network: Network) { + if (network == current) { + current = null + publish(null) + } + } + } + + init { + publish(current) + manager.registerDefaultNetworkCallback(callback) + } + + override fun close() = manager.unregisterNetworkCallback(callback) +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/sse/ConnectionState.kt b/android/core/data/src/main/kotlin/app/hapi/data/sse/ConnectionState.kt new file mode 100644 index 00000000..117e583c --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/sse/ConnectionState.kt @@ -0,0 +1,38 @@ +package app.hapi.data.sse + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.transformLatest + +/** Transport state is separate from the ordered, cursor-bearing message stream. */ +data class ConnectionState( + val phase: Phase = Phase.Idle, + val outageStartedAtMs: Long? = null, +) { + enum class Phase { Idle, Connecting, Connected, Backoff, Suspended } +} + +/** Route identity excludes metering/validation: a LAN hub need not reach the internet. */ +data class NetworkRoute( + val networkId: Long?, + val interfaceName: String? = null, + val routes: Set = emptySet(), + val addresses: Set = emptySet(), +) + +@OptIn(ExperimentalCoroutinesApi::class) +fun Flow.reconnectNotice(nowMs: () -> Long): Flow = transformLatest { state -> + val start = state.outageStartedAtMs + if (start == null) { + emit(false) + } else { + val remaining = start + 4_000 - nowMs() + if (remaining > 0) { + emit(false) + delay(remaining) + } + emit(true) + } +}.distinctUntilChanged() diff --git a/android/core/data/src/main/kotlin/app/hapi/data/sse/SseEngine.kt b/android/core/data/src/main/kotlin/app/hapi/data/sse/SseEngine.kt index fb9dcc4f..e8fe64fd 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/sse/SseEngine.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/sse/SseEngine.kt @@ -6,12 +6,17 @@ import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.coroutineContext import kotlin.random.Random import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.first import kotlinx.coroutines.isActive @@ -110,6 +115,7 @@ class SseEngine( */ private val cursors = mutableMapOf() private val foreground = MutableStateFlow(true) + private val networkRoute = MutableStateFlow(null) private class Subscription { /** @@ -120,20 +126,59 @@ class SseEngine( * acknowledged. */ val events = MutableSharedFlow() + val state = MutableStateFlow(ConnectionState()) + val reconnectRevision = MutableStateFlow(0L) + var phase = ConnectionState.Phase.Idle var job: Job? = null } /** The per-key event stream. Stable across subscribe/unsubscribe cycles. */ fun events(key: SseSubscriptionKey): SharedFlow = subscription(key).events + fun connectionState(key: SseSubscriptionKey): StateFlow = subscription(key).state.asStateFlow() + + fun reconnecting(key: SseSubscriptionKey) = connectionState(key).reconnectNotice(nowMs) + + /** Cancellation joins the previous attempt before opening another socket. */ + fun requestReconnect(key: SseSubscriptionKey) { + synchronized(lock) { + val sub = subscriptions[key.key] ?: return + if (sub.job?.isActive != true) return + publishState(sub, ConnectionState.Phase.Backoff) + sub.reconnectRevision.value += 1 + } + } + + fun networkChanged(route: NetworkRoute) { + synchronized(lock) { + val previous = networkRoute.value + if (previous == route) return + networkRoute.value = route + // The first callback establishes the baseline, not a route change. + if (previous == null) return + subscriptions.values.filter { it.job?.isActive == true }.forEach { sub -> + publishState(sub, ConnectionState.Phase.Backoff) + sub.reconnectRevision.value += 1 + } + } + } + /** Starts the connection loop for [key]. No-op when already running. */ + @OptIn(ExperimentalCoroutinesApi::class) fun subscribe(key: SseSubscriptionKey) { val sub = subscription(key) synchronized(lock) { if (sub.job?.isActive == true) { return } - sub.job = scope.launch { runSubscriptionLoop(key, sub) } + val previous = sub.job + sub.job = scope.launch { + previous?.join() + sub.reconnectRevision.collectLatest { + awaitForeground() + runSubscriptionLoop(key, sub) + } + } } } @@ -141,7 +186,10 @@ class SseEngine( fun unsubscribe(key: SseSubscriptionKey) { val job = synchronized(lock) { val sub = subscriptions[key.key] ?: return - sub.job.also { sub.job = null } + sub.job.also { + it?.cancel() + publishState(sub, ConnectionState.Phase.Idle) + } } job?.cancel() } @@ -155,7 +203,27 @@ class SseEngine( * any error surfacing. */ fun setLifecycleForeground(foreground: Boolean) { - this.foreground.value = foreground + synchronized(lock) { + val resuming = foreground && !this.foreground.value + this.foreground.value = foreground + subscriptions.values.forEach { + publishState(it, it.phase) + if (resuming && it.phase == ConnectionState.Phase.Backoff && it.job?.isActive == true) { + it.reconnectRevision.value++ + } + } + } + } + + private fun publishState(sub: Subscription, phase: ConnectionState.Phase) = synchronized(lock) { + sub.phase = phase + val visiblePhase = if (!foreground.value && phase != ConnectionState.Phase.Idle) ConnectionState.Phase.Suspended else phase + val start = when (visiblePhase) { + ConnectionState.Phase.Backoff -> sub.state.value.outageStartedAtMs ?: nowMs() + ConnectionState.Phase.Connecting -> sub.state.value.outageStartedAtMs + else -> null + } + sub.state.value = ConnectionState(visiblePhase, start) } private fun subscription(key: SseSubscriptionKey): Subscription = synchronized(lock) { @@ -173,14 +241,17 @@ class SseEngine( var authRetriedThisCycle = false var forceTokenRefresh = false while (coroutineContext.isActive) { + publishState(sub, ConnectionState.Phase.Connecting) val token = tokenProvider.freshToken(forceTokenRefresh) forceTokenRefresh = false if (token == null) { + publishState(sub, ConnectionState.Phase.Backoff) attempt = backoffThenAwaitForeground(attempt) continue } val outcome = runAttempt(key, sub, token) + publishState(sub, ConnectionState.Phase.Backoff) if (outcome.handshakeReached) { // "Reset the attempt counter to 0 on every successful open." @@ -218,7 +289,7 @@ class SseEngine( } private suspend fun awaitForeground() { - foreground.first { it } + combine(foreground, networkRoute) { visible, route -> visible && (route == null || route.networkId != null) }.first { it } } private class AttemptState { @@ -330,6 +401,7 @@ class SseEngine( return } state.handshakeReached = true + publishState(sub, ConnectionState.Phase.Connected) sub.events.emit(EngineEvent.Handshake(data.subscriptionId, resumeVerdict(data.resume))) return } diff --git a/android/core/data/src/test/kotlin/app/hapi/data/sse/ConnectionStateTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/sse/ConnectionStateTest.kt new file mode 100644 index 00000000..74de5b53 --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/sse/ConnectionStateTest.kt @@ -0,0 +1,42 @@ +@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + +package app.hapi.data.sse + +import app.cash.turbine.test +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ConnectionStateTest { + @Test fun `notice spans retry phases and clears only on recovery or lifecycle shutdown`() = runTest { + val state = MutableStateFlow(ConnectionState()) + state.reconnectNotice { testScheduler.currentTime }.test { + assertFalse(awaitItem()) + state.value = ConnectionState(ConnectionState.Phase.Backoff, 0) + runCurrent() + advanceTimeBy(2_000) + state.value = ConnectionState(ConnectionState.Phase.Connecting, 0) + runCurrent() + advanceTimeBy(1_999) + expectNoEvents() + advanceTimeBy(1) + runCurrent() + assertTrue(awaitItem()) + state.value = ConnectionState(ConnectionState.Phase.Backoff, 0) + runCurrent() + expectNoEvents() + state.value = ConnectionState(ConnectionState.Phase.Connected) + assertFalse(awaitItem()) + state.value = ConnectionState(ConnectionState.Phase.Backoff, 4_000) + advanceTimeBy(1_000) + state.value = ConnectionState(ConnectionState.Phase.Suspended) + advanceTimeBy(10_000) + runCurrent() + expectNoEvents() + } + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/sse/SseEngineTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/sse/SseEngineTest.kt index 0545769f..5adaad46 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/sse/SseEngineTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/sse/SseEngineTest.kt @@ -62,6 +62,61 @@ private fun TestScope.harness( class SseEngineTest { + @Test + fun `route changes reconnect once preserve cursor and defer while backgrounded`() = runTest { + val h = harness() + val key = SseSubscriptionKey.Global + val wifi = NetworkRoute(1, "wlan0", addresses = setOf("10.0.0.2/24")) + h.engine.networkChanged(wifi) + h.engine.events(key).test { + h.engine.subscribe(key) + val first = h.awaitOpen() + first.handshake() + awaitItem() + first.event("cursor-1", SESSION_REMOVED) + awaitItem() + runCurrent() + h.engine.networkChanged(wifi) + runCurrent() + h.assertNoOpen() + // DHCP can change the socket's source IP without changing the + // default network, interface, or gateway route. + h.engine.networkChanged(wifi.copy(addresses = setOf("10.0.0.3/24"))) + val second = h.awaitOpen() + assertTrue(first.closed) + assertEquals("cursor-1", second.lastEventId) + second.handshake() + awaitItem() + h.engine.setLifecycleForeground(false) + h.engine.networkChanged(NetworkRoute(3)) + runCurrent() + assertTrue(second.closed) + h.assertNoOpen() + h.engine.setLifecycleForeground(true) + val third = h.awaitOpen() + assertEquals("cursor-1", third.lastEventId) + h.engine.unsubscribe(key) + runCurrent() + assertTrue(third.closed) + assertEquals(ConnectionState.Phase.Idle, h.engine.connectionState(key).value.phase) + } + } + + @Test + fun `manual reconnect interrupts backoff without clearing ongoing outage`() = runTest { + val h = harness() + val key = SseSubscriptionKey.Global + h.engine.subscribe(key) + h.awaitOpen().fail(503) + h.awaitOpen().fail(503) + runCurrent() + val outage = h.engine.connectionState(key).value.outageStartedAtMs + assertEquals(0L, outage) + h.engine.requestReconnect(key) + h.awaitOpen() + assertEquals(outage, h.engine.connectionState(key).value.outageStartedAtMs) + } + @Test fun `handshake emits resume verdict and subscription id after connection-changed`() = runTest { val h = harness() diff --git a/docs/native-chat-scrolling.md b/docs/native-chat-scrolling.md index 662bd7aa..7ef4e5f2 100644 --- a/docs/native-chat-scrolling.md +++ b/docs/native-chat-scrolling.md @@ -112,9 +112,21 @@ observed through `snapshotFlow` only while following; corrections are queued outside measurement/placement to avoid reentrant layout. Row heights use size-change callbacks, not callbacks on every global-position change, and unchanged viewport demand is not repeatedly sent to the coordinator. -Group expansion flags are saved with them: the flattened children must exist -before restoring an index/offset within a group. Removed groups' flags are -pruned rather than retained indefinitely. +`ChatHost` hoists the list and reading state above a nested Navigation Compose +host. Groups remain one summary row; tool/group/message/process inspectors use +full-screen native destinations. Opening inspection disables tail following, +cancels hidden history demand and dictation, and hides the IME. Back/Close alone +never jumps to latest. Session events and SSE remain owned by the conversation +host/holder, including while an inspector covers the thread and across rotation. + +`ChatInspectionState` resolves live IDs and retains only selected snapshots for +trimmed tools/messages/groups. A missing group keeps its previous membership; +epoch invalidation clears selections and returns to the thread. Group browsing +starts at the latest tool once, then uses explicit navigation to latest. No +hidden history request originates in the browser. `TranscriptProjection` omits +member payloads and ordinary tool results from the transcript, retaining summary +identity through output-only updates without changing protocol groups or detail +data. Inline plan proposals retain results so diagnostics and Source stay live. The history coordinator uses a dedicated queued Main scope sharing the holder's lifetime, independent of its Default worker scope. Lifecycle, @@ -122,8 +134,8 @@ viewport/layout callbacks, store observation, request completion and retry transitions are main-thread serialized. Network/store work and the chat/ Markdown pipeline stay on workers; only the before-apply veto is atomic. -An explicitly pruned `SaveableStateHolder` retains recycled row interactions, -including collapsed group children. Markdown ASTs are prepared on the pipeline +An explicitly pruned `SaveableStateHolder` retains recycled row interactions. +Markdown ASTs are prepared on the pipeline dispatcher and cached per chat; misses parse off-main. Images retain the existing asynchronous, cached Coil loader. @@ -140,6 +152,11 @@ existing asynchronous, cached Coil loader. - Markdown caches: 800 entries and approximately 8 MiB source/AST cost budget each. Oversized documents render on demand but are not retained in cache. - Not an offline archive; no cross-launch reading-position persistence. +- Android user text: inline through 8,000 graphemes / 120 source lines, otherwise + a 2,000 / 24 preview. The full reader mounts one 4,000 / 80 page. Tool source + mounts one 20,000 / 400 page. Paging never accumulates visited text layouts; + original source remains available for copy/export. These are layout budgets, + not a limit on payload bytes or the size of a single Unicode grapheme. ## Automated checks @@ -151,7 +168,7 @@ ios/scripts/test-transcript.sh cd android ./gradlew :core:protocol:test :core:data:testDebugUnitTest :app:testDebugUnitTest -./gradlew :app:assembleDebug :app:assembleDebugAndroidTest +./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:lintDebug # Run on a dedicated test emulator; avoid installing into a personal device. ./gradlew :app:connectedDebugAndroidTest ``` @@ -175,7 +192,11 @@ after tail sync; Compose tests cover saved-screen and saved-instance-state restoration with consumed and new jump tokens. Android also tests Default workers against a separate UI executor across 20 acknowledged pages (including acknowledgement before request completion), -and restores expanded child-row anchors across navigation and saved state. +and restores group-summary anchors across navigation and saved state. API 29/36 +instrumentation covers grapheme preservation, single-page long-message layout +at 200% font scale, reader restoration, and explicit-only group following. +Unit tests cover retained snapshots, output-only summary reuse, hidden history +cancellation with a late HTTP response, and the shared subscription lifetime. These are deterministic layout regressions, not proof of release-device FPS. @@ -207,15 +228,15 @@ Use a release/profile build on iOS 17 and a recent iPhone (60/120 Hz), plus Android API 26 and a recent Android device, including a lower-end device. 1. Replay a 10,000+ message session with mixed Markdown, long code/diffs, - images, permissions, and tool groups (iOS inspectors / Android expanded rows). + images, permissions, and tool groups in both platforms' inspectors. Traverse well beyond the 800-message window repeatedly. 2. Test slow dragging, fast upward flings, reversing direction during a request, and a response arriving during deceleration. No forced animation, cancelled momentum, or unexplained reading-position jump. 3. Under 200 ms / 1 s / 3 s latency, packet loss, and offline/reconnect, verify serial paging, bounded retries, manual recovery, and no “beginning” lie. -4. Stream into the tail while reading a partial tall row. Expand/collapse - tools, load images, rotate, change text size, show/hide the keyboard, and +4. Stream into the tail while reading a partial tall row. Open/close tool + inspectors, load images, rotate, change text size, show/hide the keyboard, and open/close a media overlay. Text/forms/expansion must survive recycling. 5. Return to latest after history trimming, both online and offline. A failed refresh must not silently claim that an old retained row is the live tail. @@ -227,3 +248,9 @@ Android API 26 and a recent Android device, including a lower-end device. Static prepend anchor regression tolerance: 1 point on iOS / 1 pixel in the Compose test. Fling continuity, real keyboard/accessibility interactions, and release-device frame/memory measurements remain manual acceptance checks. + +Android's opt-in `ChatFrameProfileTest` additionally probes long user-message +previews and a 200-tool group's output updates at 10 Hz, with Java/native heap +samples and `dumpsys meminfo` alongside frame metrics. Run in the profile build +on representative 60/120 Hz devices. A software emulator can validate behavior; +it cannot establish frame-rate or memory acceptance on those devices.