From 35898c09cd0ecff1eccf12276a9a86bc60f8ee3c Mon Sep 17 00:00:00 2001 From: weishu Date: Wed, 11 Nov 2026 09:40:45 +0800 Subject: [PATCH] feat(android): web-parity presence badges, sort/filter and attached jobs The home list showed presence only for connected sessions, offered no sort or status choices, and ignored session-attached jobs. Its strict SessionPatch parser also rejected every `attachedJob` SSE patch, so each job heartbeat fell back to a REST list refetch. - Presence badge follows web #2296: solid green pulsing while working, solid blue pulsing for background tasks only, a green ring when connected and waiting, and a power mark when stopped or archived. - The Sort & filter sheet adds Show (all / active only / archived only) and Unread only next to machines and dates, then Sort by (last message or date created) and Active first (on by default; manual pins still lead). Sort and Active first persist app-wide in hapi_prefs; filters stay transient, keep the open session listed, and Reset leaves the order alone. Search keeps relevance with the base tie-break. The share picker keeps the base order. - Decode AttachedJob on summaries and the versioned `attachedJob` patch, applied only when strictly newer, as on web. Full-session events keep the row's job. A running job counts as working on the badge and as active for the Show filter (web #1404), and adds a row line with label, remaining or percent, elapsed time and a thin bar, amber with "no heartbeat" after 15 minutes. - HomeFilterWindowTest's click helper now scrolls back once it reaches the end; the taller sheet otherwise stranded targets above the viewport. - Docs describe the Android sheet, row and job display. --- android/README.md | 27 ++- .../feature/home/HomeFilterWindowTest.kt | 13 +- .../companion/feature/home/HomeScreenTest.kt | 19 ++ .../kotlin/app/hapi/companion/Navigation.kt | 14 +- .../kotlin/app/hapi/companion/di/AppGraph.kt | 4 + .../hapi/companion/feature/home/HomeScreen.kt | 7 +- .../feature/sessions/SessionFilterSheet.kt | 83 ++++++- .../feature/sessions/SessionListOrderPrefs.kt | 71 ++++++ .../feature/sessions/SessionListScreen.kt | 211 ++++++++++++++---- .../feature/sessions/SessionListViewModel.kt | 149 ++++++++++++- .../main/res/drawable/ic_presence_stopped.xml | 12 + .../app/src/main/res/values-ru/strings.xml | 17 +- .../src/main/res/values-zh-rCN/strings.xml | 17 +- android/app/src/main/res/values/strings.xml | 17 +- .../sessions/SessionListOrderPrefsTest.kt | 50 +++++ .../sessions/SessionListViewModelTest.kt | 75 +++++++ .../feature/sessions/SessionPresenceTest.kt | 37 +++ .../app/hapi/data/store/SessionStore.kt | 6 +- .../app/hapi/data/store/SessionStoreTest.kt | 28 +++ .../app/hapi/protocol/wire/AttachedJob.kt | 83 +++++++ .../app/hapi/protocol/wire/SessionPatch.kt | 13 +- .../app/hapi/protocol/wire/SessionSorting.kt | 66 +++++- .../app/hapi/protocol/wire/SessionSummary.kt | 4 + .../app/hapi/protocol/wire/SummaryPatching.kt | 10 + .../app/hapi/protocol/wire/AttachedJobTest.kt | 93 ++++++++ .../hapi/protocol/wire/SessionSortingTest.kt | 31 +++ docs/guide/native-apps.md | 14 +- docs/guide/session-jobs.md | 9 +- 28 files changed, 1090 insertions(+), 90 deletions(-) create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefs.kt create mode 100644 android/app/src/main/res/drawable/ic_presence_stopped.xml create mode 100644 android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefsTest.kt create mode 100644 android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionPresenceTest.kt create mode 100644 android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AttachedJob.kt create mode 100644 android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/AttachedJobTest.kt diff --git a/android/README.md b/android/README.md index ccc50e6a..7d3ee0dc 100644 --- a/android/README.md +++ b/android/README.md @@ -384,13 +384,30 @@ preserving replay cursors; background retries defer until foreground. A local hub route does not need Android's internet-validation capability. Home centers the Sessions title between a **Hubs and settings** icon and a -**Filters** icon, keeping the new-session FAB. The hub menu is the only entry +**Sort & filter** icon, keeping the new-session FAB. The hub menu is the only entry for switching/adding hubs, app settings and sign-out; the active hub is checked. -The filter icon marks an applied filter and opens a Material 3 single-selection -sheet. Choices come from all sessions, including historical +The icon carries a dot for any applied filter or a non-default order and opens +one Material 3 sheet that mirrors the web sort and filter menu: machines, +activity dates, **Show** all / active only / archived only and **Unread only**, +then **Sort by** last message (default) or date created and **Active first** +(on by default: connected sessions lead the pinned and recent sections, below +manual pins), both persisted app-wide in `hapi_prefs`. Status and unread +filters keep the open session listed; search ranks by relevance with the base +order as tie-break, as on web. Machine 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. +IDs; unnamed and unknown machines are labeled. **Reset** clears the filters (not +the order); filters are transient per home/hub and cleared when no longer valid. +The share picker reuses the list model with the base order. + +Each row's agent icon carries the web presence badge (one mark per state): +solid green pulsing while working, solid blue pulsing when only background +tasks run, a green ring when connected and waiting, and a power mark when +stopped or archived. A running [attached job](../docs/guide/session-jobs.md) +counts as working even when the agent is idle or disconnected, keeps the session +under **Active only**, and adds a line under the meta line: +`label · remaining or percent · elapsed` with a thin bar (determinate only for +an honest fraction), amber with `no heartbeat` after 15 minutes. Job patches are +versioned like web's: a lagged heartbeat cannot resurrect a cleared job. The home holder follows the active connection instance, releasing the previous store and filter even when switching back to a previously used hub URL. diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeFilterWindowTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeFilterWindowTest.kt index bff47ffa..19be2fad 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeFilterWindowTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeFilterWindowTest.kt @@ -51,11 +51,20 @@ class HomeFilterWindowTest { } private fun click(text: String) { + // The sheet scrolls; a retry while it is still opening must not strand + // the target above the viewport, so sweep back once the end is reached. + var direction = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD await("click $text") { val candidates = nodes(text).filter { it.isVisibleToUser } if (candidates.isEmpty()) { - descendants().firstOrNull { it.isScrollable } - ?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + val scrollable = descendants().firstOrNull { it.isScrollable } + if (scrollable != null && !scrollable.performAction(direction)) { + direction = if (direction == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) { + AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD + } else { + AccessibilityNodeInfo.ACTION_SCROLL_FORWARD + } + } } candidates.any { node -> var target = node diff --git a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeScreenTest.kt b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeScreenTest.kt index 617252c3..8b71a52c 100644 --- a/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeScreenTest.kt +++ b/android/app/src/androidTest/kotlin/app/hapi/companion/feature/home/HomeScreenTest.kt @@ -212,6 +212,25 @@ class HomeScreenTest { .assert(SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, label(R.string.sessions_filters_active))) } + @Test fun sheetShowsStatusAndSortChoicesBelowTheFilters() { + sessions.sessions.value = sessions.sessions.value.map { if (it.id == "research") it.copy(active = false) else it } + mount() + openFilters() + compose.onNodeWithTag("session-filters").performScrollToNode(hasText(label(R.string.sessions_view_status_archived))) + compose.onNodeWithText(label(R.string.sessions_view_status_archived)).performClick() + compose.waitUntil(10_000) { viewModel.uiState.value.rows.map { it.id } == listOf("research") } + compose.onNodeWithTag("session-filters").performScrollToNode(hasTestTag("session-active-first")) + compose.onNodeWithTag("session-active-first").assertIsDisplayed().performClick() + compose.waitUntil(10_000) { !viewModel.uiState.value.order.activeFirst && viewModel.uiState.value.isCustomized } + compose.onNodeWithTag("session-active-first").performClick() + compose.waitUntil(10_000) { viewModel.uiState.value.order.activeFirst } + compose.onNodeWithText(label(R.string.sessions_filters_reset)).performClick() + compose.waitUntil(10_000) { !viewModel.uiState.value.hasActiveFilters && viewModel.uiState.value.rows.size == 3 } + compose.onNodeWithText(label(R.string.sessions_filters_done)).performClick() + compose.onNodeWithContentDescription(label(R.string.sessions_filters)) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, label(R.string.sessions_filter_all))) + } + @Test fun singleMachineStillOffersDateFilteringAndReset() { sessions.sessions.value = sessions.sessions.value.filter { it.metadata?.machineId == "laptop" } viewModel.setDateRange(today, today) diff --git a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt index eb2d4fa6..9d08fd9a 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt @@ -65,6 +65,8 @@ import app.hapi.companion.feature.scratchlist.ContentResolverAttachmentImporter import app.hapi.companion.feature.scratchlist.ScratchlistMedia import app.hapi.companion.feature.scratchlist.ScratchlistScreen import app.hapi.companion.feature.scratchlist.ScratchlistViewModel +import app.hapi.companion.feature.sessions.InMemorySessionListOrderStore +import app.hapi.companion.feature.sessions.SessionListOrderStore import app.hapi.companion.feature.sessions.SessionListViewModel import app.hapi.companion.feature.share.ShareScreen import app.hapi.companion.feature.share.ShareSessionGateway @@ -79,6 +81,7 @@ import app.hapi.companion.feature.settings.UsageScreen import app.hapi.companion.feature.settings.UsageViewModel import app.hapi.data.auth.AuthTerminalReason import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.protocol.wire.SessionListOrder import java.util.Base64 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -360,7 +363,7 @@ fun HapiNavigation() { factory = viewModelFactory { SessionListViewModelHolder() }, ) HomeScreen( - viewModel = holder.forHub(hubGraph), + viewModel = holder.forHub(hubGraph, graph.sessionListOrderPrefs), activeHubUrl = activeHubUrl, pairedHubs = registryState.hubs, onSwitchHub = { hub -> scope.launch { graph.hubRegistry.setActiveHub(hub) } }, @@ -772,7 +775,11 @@ private class ShareViewModelHolder : ViewModel() { } } return ShareModels( - SessionListViewModel(hub.sessionStore, hub.machineStore, hub.lastSeenStore, nextScope, hub.hubUrl), + SessionListViewModel( + hub.sessionStore, hub.machineStore, hub.lastSeenStore, nextScope, hub.hubUrl, + // The picker keeps the base order, not Home's sort preference. + orderStore = InMemorySessionListOrderStore(SessionListOrder.Base), + ), ShareTargetController(gateway, nextScope), ).also { models = it } } @@ -796,7 +803,7 @@ private class SessionListViewModelHolder : ViewModel() { private var scope: CoroutineScope? = null private var model: SessionListViewModel? = null - fun forHub(hubGraph: HubGraph): SessionListViewModel { + fun forHub(hubGraph: HubGraph, orderStore: SessionListOrderStore): SessionListViewModel { model?.takeIf { graph === hubGraph }?.let { return it } model?.stop() scope?.cancel() @@ -810,6 +817,7 @@ private class SessionListViewModelHolder : ViewModel() { scope = nextScope, hubKey = hubGraph.hubUrl, connectionState = hubGraph.sseEngine.connectionState(SseSubscriptionKey.Global), + orderStore = orderStore, ).also { model = it } } diff --git a/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt b/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt index 65aeece3..43fd615a 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt @@ -9,6 +9,7 @@ import app.hapi.companion.feature.pairing.PairingClient import app.hapi.companion.feature.pairing.PairingClientFactory import app.hapi.companion.feature.settings.AppLanguage import app.hapi.companion.feature.settings.LanguagePrefs +import app.hapi.companion.feature.sessions.SessionListOrderPrefs import app.hapi.companion.feature.settings.ThemePrefs import app.hapi.companion.feature.share.ContentResolverShareReader import app.hapi.companion.feature.share.ShareInbox @@ -121,6 +122,9 @@ class AppGraph(context: Context) { /** Appearance choice (B-M4e); MainActivity reads it at setContent. */ val themePrefs: ThemePrefs = ThemePrefs(appContext.hapiDataStore) + /** Session-list sort + Active first, app-wide like web's localStorage view keys. */ + val sessionListOrderPrefs: SessionListOrderPrefs = SessionListOrderPrefs(appContext.hapiDataStore) + /** Language choice (B-M5a: applied via per-app locales; Settings writes it). */ val languagePrefs: LanguagePrefs = LanguagePrefs(appContext.hapiDataStore) diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/home/HomeScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/home/HomeScreen.kt index 1f442607..198f402d 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/home/HomeScreen.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/home/HomeScreen.kt @@ -53,7 +53,8 @@ fun HomeScreen( HomeTopBar( activeHubUrl = activeHubUrl, pairedHubs = pairedHubs, - hasActiveFilters = state.hasActiveFilters, + // Web's dot: any filter or a non-default order. + hasActiveFilters = state.isCustomized, connectionStatus = state.connectionStatus, searchExpanded = searchExpanded, searchQuery = state.searchQuery, @@ -86,6 +87,10 @@ fun HomeScreen( if (filterDestination == FilterDestination.Filters) { SessionFilterSheet( state = state, + onSelectSort = viewModel::setSort, + onSetActiveFirst = viewModel::setActiveFirst, + onSelectStatus = viewModel::setStatusFilter, + onSetUnreadOnly = viewModel::setUnreadOnly, onSelectMachine = viewModel::setMachineFilter, onOpenDates = { filterDestination = FilterDestination.Dates }, onClearDates = viewModel::clearDateRange, diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionFilterSheet.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionFilterSheet.kt index fe4e1aa6..38423421 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionFilterSheet.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionFilterSheet.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.selection.toggleable import androidx.compose.material3.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close @@ -19,6 +20,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp import app.hapi.companion.R +import app.hapi.protocol.wire.SessionListSort import kotlinx.coroutines.launch @Composable @@ -28,10 +30,19 @@ internal fun machineFilterLabel(filter: MachineFilterUi): String = when { else -> filter.label } +/** + * One sheet for every list view choice (web "Sort and filter"): the machine / + * date / status / unread filters (transient), then sort key and Active first + * (persisted). Choices apply immediately; Reset clears filters only. + */ @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun SessionFilterSheet( state: SessionListUiState, + onSelectSort: (SessionListSort) -> Unit, + onSetActiveFirst: (Boolean) -> Unit, + onSelectStatus: (SessionListStatus) -> Unit, + onSetUnreadOnly: (Boolean) -> Unit, onSelectMachine: (String?) -> Unit, onOpenDates: () -> Unit, onClearDates: () -> Unit, @@ -59,7 +70,7 @@ internal fun SessionFilterSheet( } LazyColumn( Modifier.fillMaxWidth().weight(1f, fill = false).heightIn(max = 480.dp) - .selectableGroup().testTag("session-filters"), + .testTag("session-filters"), ) { if (state.hasMachineFilters) { item("machines-title") { @@ -69,12 +80,14 @@ internal fun SessionFilterSheet( modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) } - item("all") { - FilterOption(stringResource(R.string.sessions_filter_all), state.activeMachineFilter == null) { onSelectMachine(null) } - } - items(state.machineFilters, key = { "machine:${it.id}" }) { filter -> - FilterOption("${machineFilterLabel(filter)} · ${filter.sessionCount}", state.activeMachineFilter == filter.id) { - onSelectMachine(filter.id) + item("machines") { + Column(Modifier.selectableGroup()) { + FilterOption(stringResource(R.string.sessions_filter_all), state.activeMachineFilter == null) { onSelectMachine(null) } + state.machineFilters.forEach { filter -> + FilterOption("${machineFilterLabel(filter)} · ${filter.sessionCount}", state.activeMachineFilter == filter.id) { + onSelectMachine(filter.id) + } + } } } item("divider") { HorizontalDivider(Modifier.padding(vertical = 8.dp)) } @@ -110,6 +123,41 @@ internal fun SessionFilterSheet( }.testTag("session-date-filter"), ) } + // Filters first (machines and dates keep their place), then the + // rarely changed ordering at the bottom. + item("status-divider") { HorizontalDivider(Modifier.padding(vertical = 8.dp)) } + item("status-title") { SectionTitle(stringResource(R.string.sessions_view_status)) } + item("status") { + Column(Modifier.selectableGroup()) { + FilterOption(stringResource(R.string.sessions_view_status_all), state.statusFilter == SessionListStatus.All) { + onSelectStatus(SessionListStatus.All) + } + FilterOption(stringResource(R.string.sessions_view_status_active), state.statusFilter == SessionListStatus.Active) { + onSelectStatus(SessionListStatus.Active) + } + FilterOption(stringResource(R.string.sessions_view_status_archived), state.statusFilter == SessionListStatus.Archived) { + onSelectStatus(SessionListStatus.Archived) + } + } + } + item("unread-only") { + SwitchOption(stringResource(R.string.sessions_view_unread_only), state.unreadOnly, onSetUnreadOnly, "session-unread-only") + } + item("sort-divider") { HorizontalDivider(Modifier.padding(vertical = 8.dp)) } + item("sort-title") { SectionTitle(stringResource(R.string.sessions_view_sort)) } + item("sort") { + Column(Modifier.selectableGroup()) { + FilterOption(stringResource(R.string.sessions_view_sort_last_message), state.order.sort == SessionListSort.LastMessage) { + onSelectSort(SessionListSort.LastMessage) + } + FilterOption(stringResource(R.string.sessions_view_sort_created), state.order.sort == SessionListSort.Created) { + onSelectSort(SessionListSort.Created) + } + } + } + item("active-first") { + SwitchOption(stringResource(R.string.sessions_view_active_first), state.order.activeFirst, onSetActiveFirst, "session-active-first") + } } Button( onClick = { scope.launch { sheetState.hide(); onDismiss() } }, @@ -120,6 +168,27 @@ internal fun SessionFilterSheet( } } +@Composable +private fun SectionTitle(text: String) { + Text( + text, + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) +} + +@Composable +private fun SwitchOption(label: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit, tag: String) { + Row( + Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = onCheckedChange) + .heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp).testTag(tag), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(label, modifier = Modifier.weight(1f)) + Switch(checked = checked, onCheckedChange = null) + } +} + @Composable private fun FilterOption(label: String, selected: Boolean, select: () -> Unit) { Row( diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefs.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefs.kt new file mode 100644 index 00000000..2fbb1bf4 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefs.kt @@ -0,0 +1,71 @@ +package app.hapi.companion.feature.sessions + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.emptyPreferences +import androidx.datastore.preferences.core.stringPreferencesKey +import app.hapi.protocol.wire.SessionListOrder +import app.hapi.protocol.wire.SessionListSort +import java.io.IOException +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update + +/** + * Session-list ordering (sort key + Active first). Row-hiding filters stay + * transient on the ViewModel; only ordering persists, like web's + * `useSessionListView` localStorage keys. + */ +interface SessionListOrderStore { + val order: Flow + suspend fun setSort(sort: SessionListSort) + suspend fun setActiveFirst(enabled: Boolean) +} + +/** Not persisted: tests, previews and surfaces that keep a fixed order (share picker passes the base order). */ +class InMemorySessionListOrderStore(initial: SessionListOrder = SessionListOrder.Default) : SessionListOrderStore { + private val state = MutableStateFlow(initial) + override val order: Flow = state + override suspend fun setSort(sort: SessionListSort) = state.update { it.copy(sort = sort) } + override suspend fun setActiveFirst(enabled: Boolean) = state.update { it.copy(activeFirst = enabled) } +} + +/** + * App-wide persistence over the `hapi_prefs` DataStore. Defaults are stored + * as absent keys (web removes its keys too), so a changed default reaches + * users who never chose; unreadable prefs degrade to defaults. + */ +class SessionListOrderPrefs(private val dataStore: DataStore) : SessionListOrderStore { + + override val order: Flow = dataStore.data + .catch { error -> if (error is IOException) emit(emptyPreferences()) else throw error } + .map { prefs -> + SessionListOrder( + sort = SessionListSort.fromStorageKey(prefs[SORT_KEY]), + activeFirst = prefs[ACTIVE_FIRST_KEY] ?: SessionListOrder.Default.activeFirst, + ) + } + .distinctUntilChanged() + + override suspend fun setSort(sort: SessionListSort) { + dataStore.edit { + if (sort == SessionListOrder.Default.sort) it.remove(SORT_KEY) else it[SORT_KEY] = sort.storageKey + } + } + + override suspend fun setActiveFirst(enabled: Boolean) { + dataStore.edit { + if (enabled == SessionListOrder.Default.activeFirst) it.remove(ACTIVE_FIRST_KEY) else it[ACTIVE_FIRST_KEY] = enabled + } + } + + companion object { + val SORT_KEY: Preferences.Key = stringPreferencesKey("session_list_sort") + val ACTIVE_FIRST_KEY: Preferences.Key = booleanPreferencesKey("session_list_active_first") + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListScreen.kt index a90327ea..bf2d1d79 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListScreen.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListScreen.kt @@ -12,6 +12,7 @@ import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.isSystemInDarkTheme @@ -22,6 +23,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -39,6 +41,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet @@ -67,6 +70,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription @@ -83,7 +87,10 @@ import androidx.lifecycle.compose.LocalLifecycleOwner import app.hapi.companion.R import app.hapi.companion.ui.components.AgentFlavorIcon import app.hapi.companion.ui.theme.HapiTheme +import app.hapi.protocol.wire.AttachedJob import app.hapi.protocol.wire.PendingRequest +import app.hapi.protocol.wire.formatCompactElapsed +import app.hapi.protocol.wire.formatJobQuantity import app.hapi.protocol.wire.SessionSummary import app.hapi.protocol.wire.SessionSummaryMetadata import app.hapi.protocol.wire.SummaryText @@ -103,12 +110,15 @@ import kotlinx.coroutines.delay * stubs hidden (ViewModel pipeline, web sidebar parity); * - pinned section first (the sort already puts globalPinned/pinned rows on * top; compact "Pinned" / "Recent" headers mark the boundary); - * - per row: a two-line-tall flavor icon whose presence badge marks - * connected sessions (pulsing while a turn is in flight), title with a + * - rows follow the persisted order (Active first and the sort key within + * the pin tiers), except while searching; + * - per row: a two-line-tall flavor icon whose presence badge gives every + * state its own mark (working / background / waiting / stopped), title with a * right-aligned relative `updatedAt` (unread: semibold title + accent * time, no dot), summary line, `project · worktree · machine` meta line * (machine only when it disambiguates) with todo chip and pending badge - * trailing. Disconnected rows are not dimmed and have no spinner; + * trailing, and a running attached job's progress line. Disconnected rows + * are not dimmed and have no spinner; * - swipe: start→end pin/unpin (project), end→start archive (live) or * delete with confirmation (inactive); the row snaps back; * - long-press → actions sheet: mark read (unread rows), pin @@ -208,7 +218,12 @@ fun SessionListScreen( if (state.isSearching) { SearchEmptyState(query = state.searchQuery) } else { - EmptyState(hasLoaded = state.hasLoaded, isOffline = state.isOffline, hasDateFilter = state.dateRange != null) + EmptyState( + hasLoaded = state.hasLoaded, + isOffline = state.isOffline, + hasDateFilter = state.dateRange != null, + hasFilters = state.hasActiveFilters, + ) } } else { SessionRows( @@ -415,6 +430,9 @@ private val ICON_SIZE = 30.dp private val ICON_SPACING = 12.dp private val PRESENCE_GREEN = Color(0xFF34C759) +/** Tailwind blue-400, web's background-work colour in both themes. */ +private val PRESENCE_BLUE = Color(0xFF60A5FA) + @OptIn(ExperimentalFoundationApi::class) @Composable private fun SessionRow( @@ -436,8 +454,7 @@ private fun SessionRow( verticalAlignment = Alignment.CenterVertically, ) { // The agent owns a two-line-tall leading column; its presence badge - // marks connected sessions (pulsing while running) instead of - // dimming every disconnected row. + // carries the session state instead of dimming disconnected rows. AgentIconWithPresence(row) Spacer(modifier = Modifier.width(ICON_SPACING)) // The divider starts under the text column, as in Mail/Messages. @@ -456,6 +473,7 @@ private fun SessionRow( ) } MetaLine(row) + row.runningJob?.let { AttachedJobLine(it) } } HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)) } @@ -464,7 +482,6 @@ private fun SessionRow( @Composable private fun AgentIconWithPresence(row: SessionRowUi) { - val summary = row.summary Box(modifier = Modifier.size(ICON_SIZE)) { AgentFlavorIcon( row.flavor, @@ -472,42 +489,156 @@ private fun AgentIconWithPresence(row: SessionRowUi) { .size(ICON_SIZE * 0.8f) .align(Alignment.Center), ) - if (summary.active) { - val running = summary.thinking - val alpha = if (running) { - val transition = rememberInfiniteTransition(label = "presence") - transition.animateFloat( - initialValue = 1f, - targetValue = 0.35f, - animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse), - label = "presence-pulse", - ).value - } else { - 1f - } - val presence = stringResource( - if (running) R.string.sessions_presence_running else R.string.sessions_presence_connected, + PresenceBadge( + row.presence, + Modifier + .align(Alignment.BottomEnd) + .offset(x = 2.dp, y = 2.dp), + ) + } +} + +/** + * Web presence badge (#2296): shape carries the state, colour keeps its old + * meaning. Solid green = working, solid blue = background tasks only (both + * pulse), green ring = connected and waiting, power mark = stopped or + * archived. The surface-coloured halo separates it from the agent icon. + */ +@Composable +internal fun PresenceBadge(presence: SessionPresence, modifier: Modifier = Modifier) { + val alpha = if (presence.pulses) { + val transition = rememberInfiniteTransition(label = "presence") + transition.animateFloat( + initialValue = 1f, + targetValue = 0.35f, + animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse), + label = "presence-pulse", + ).value + } else { + 1f + } + val description = stringResource( + when (presence) { + SessionPresence.Working -> R.string.sessions_presence_running + SessionPresence.Background -> R.string.sessions_presence_background + SessionPresence.Waiting -> R.string.sessions_presence_connected + SessionPresence.Stopped -> R.string.sessions_presence_stopped + }, + ) + Box( + modifier = modifier + .size(12.dp) + .background(MaterialTheme.colorScheme.surface, CircleShape) + .padding(2.dp) + .semantics { contentDescription = description } + .testTag("session-presence-${presence.name.lowercase()}"), + ) { + val mark = Modifier.fillMaxSize() + when (presence) { + SessionPresence.Working, SessionPresence.Background -> Box( + mark + .graphicsLayer { this.alpha = alpha } + .background(if (presence == SessionPresence.Working) PRESENCE_GREEN else PRESENCE_BLUE, CircleShape), + ) + SessionPresence.Waiting -> Box(mark.border(1.8.dp, PRESENCE_GREEN, CircleShape)) + SessionPresence.Stopped -> Icon( + painterResource(R.drawable.ic_presence_stopped), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + modifier = mark, ) - Box( - modifier = Modifier - .align(Alignment.BottomEnd) - .offset(x = 2.dp, y = 2.dp) - .size(12.dp) - .background(MaterialTheme.colorScheme.surface, CircleShape) - .padding(2.dp) - .semantics { contentDescription = presence }, - ) { - Box( - modifier = Modifier - .fillMaxSize() - .graphicsLayer { this.alpha = alpha } - .background(PRESENCE_GREEN, CircleShape), - ) - } } } } +/** + * A running attached job (web `SessionRowSummary` job line): label, then + * remaining or percent, then elapsed wall time — never an ETA — with a thin + * bar (determinate when the hub sends an honest fraction). After 15 minutes + * without a heartbeat it turns amber and says so instead of passing frozen + * progress off as live. + */ +@Composable +private fun AttachedJobLine(job: AttachedJob) { + // Minute ticks: elapsed and stale age are minute-granular. + val now by produceState(System.currentTimeMillis(), job) { + while (true) { + value = System.currentTimeMillis() + delay(60_000) + } + } + val context = LocalContext.current + val dark = isSystemInDarkTheme() + val color = when { + job.isStale(now) -> if (dark) Color(0xFFE3B341) else Color(0xFF9A6700) + dark -> PRESENCE_GREEN + // Darker success green for text on a light surface. + else -> Color(0xFF16A34A) + } + val text = attachedJobText( + job, + now, + left = { context.getString(R.string.sessions_job_left, it) }, + noHeartbeat = { context.getString(R.string.sessions_job_no_heartbeat, it) }, + ) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(top = 2.dp).testTag("session-attached-job"), + ) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = color, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Spacer(modifier = Modifier.width(8.dp)) + val fraction = job.fraction + val barModifier = Modifier.width(56.dp).height(3.dp) + if (fraction != null) { + LinearProgressIndicator( + progress = { fraction }, + modifier = barModifier, + color = color, + trackColor = MaterialTheme.colorScheme.surfaceContainerHighest, + drawStopIndicator = {}, + ) + } else { + LinearProgressIndicator( + modifier = barModifier, + color = color, + trackColor = MaterialTheme.colorScheme.surfaceContainerHighest, + ) + } + } +} + +/** `label · remaining or percent · elapsed` (web `formatAttachedJobProgress`, compact). */ +internal fun attachedJobText( + job: AttachedJob, + nowMs: Long, + left: (String) -> String, + noHeartbeat: (String) -> String, +): String { + val unit = job.unit?.let { " $it" } ?: "" + val parts = mutableListOf(job.label) + val remaining = job.remaining + val percent = job.percent + if (remaining != null) { + parts += left(formatJobQuantity(remaining) + unit) + } else if (percent != null) { + parts += "$percent%" + parts += "${formatJobQuantity(job.done ?: 0.0)}/${formatJobQuantity(job.total ?: 0.0)}$unit" + } + parts += if (job.isStale(nowMs)) { + noHeartbeat(formatCompactElapsed(maxOf(0, nowMs - job.heartbeatAt))) + } else { + formatCompactElapsed(maxOf(0, nowMs - job.startedAt)) + } + return parts.joinToString(" · ") +} + /** * Title + right-aligned relative age. Unread is a semibold title plus an * accent timestamp — no dot, so the presence badge stays the row's only dot @@ -687,7 +818,7 @@ private fun SearchEmptyState(query: String) { } @Composable -private fun EmptyState(hasLoaded: Boolean, isOffline: Boolean, hasDateFilter: Boolean = false) { +private fun EmptyState(hasLoaded: Boolean, isOffline: Boolean, hasDateFilter: Boolean = false, hasFilters: Boolean = false) { // verticalScroll keeps the pull-to-refresh gesture available even though // there is nothing to scroll. Column( @@ -704,6 +835,7 @@ private fun EmptyState(hasLoaded: Boolean, isOffline: Boolean, hasDateFilter: Bo !hasLoaded && !isOffline -> R.string.sessions_empty_loading_title isOffline -> R.string.sessions_empty_offline_title hasDateFilter -> R.string.sessions_time_filter_empty_title + hasFilters -> R.string.sessions_filter_empty_title else -> R.string.sessions_empty_title }, ), @@ -716,6 +848,7 @@ private fun EmptyState(hasLoaded: Boolean, isOffline: Boolean, hasDateFilter: Bo !hasLoaded && !isOffline -> R.string.sessions_empty_loading_hint isOffline -> R.string.sessions_empty_offline_hint hasDateFilter -> R.string.sessions_time_filter_empty_hint + hasFilters -> R.string.sessions_filter_empty_hint else -> R.string.sessions_empty_hint }, ), diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListViewModel.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListViewModel.kt index 56d71358..ded203f5 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListViewModel.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListViewModel.kt @@ -6,7 +6,10 @@ import app.hapi.data.store.LastSeenState import app.hapi.data.store.LastSeenStore import app.hapi.data.store.MachineListStore import app.hapi.data.store.SessionListStore +import app.hapi.protocol.wire.AttachedJob import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.SessionListOrder +import app.hapi.protocol.wire.SessionListSort import app.hapi.protocol.wire.SessionSummary import app.hapi.protocol.wire.sortSessionSummaries import java.time.ZoneId @@ -56,6 +59,60 @@ data class SessionRowUi( val machine: MachineFilterUi? = null, ) { val id: String get() = summary.id + val presence: SessionPresence get() = SessionPresence.of(summary) + + /** Only a running job is shown; finished ones leave no trace on the row. */ + val runningJob: AttachedJob? get() = summary.runningAttachedJob +} + +/** Work that outlives the agent (tiann/hapi#1404); web `hasRunningAttachedJob`. */ +val SessionSummary.runningAttachedJob: AttachedJob? + get() = attachedJob?.takeIf { it.isRunning } + +/** + * The agent icon's presence badge (web `SessionRowSummary`, #2296). Every + * state has its own mark, so none is shown by the absence of one: solid and + * pulsing while working (blue when only background tasks run), a ring when + * connected and waiting, a power mark when stopped or archived. A running + * attached job counts as working even when the agent is idle or gone. + */ +enum class SessionPresence { + Working, + Background, + Waiting, + Stopped; + + val pulses: Boolean get() = this == Working || this == Background + + companion object { + /** Same precedence as web: background-only before an attached job. */ + fun of(summary: SessionSummary): SessionPresence = when { + summary.active && !summary.thinking && summary.backgroundTaskCount > 0 -> Background + (summary.active && summary.thinking) || summary.runningAttachedJob != null -> Working + summary.active -> Waiting + else -> Stopped + } + } +} + +/** + * Web "Show" filter. Archived means not connected: closed sessions and ones + * whose CLI went away. A running attached job keeps an idle session under + * Active and out of Archived (web #1404 exception). + */ +enum class SessionListStatus { + All, + Active, + Archived; + + fun includes(summary: SessionSummary): Boolean { + val live = summary.active || summary.runningAttachedJob != null + return when (this) { + All -> true + Active -> live + Archived -> !live + } + } } data class MachineFilterUi( @@ -79,6 +136,15 @@ data class SessionListUiState( val isOffline: Boolean, /** Transient date-range lens (web `customStart`/`customEnd` `useState`); null = off, never persisted. */ val dateRange: SessionDateRange? = null, + /** Transient "Show" filter; the open session always stays listed. */ + val statusFilter: SessionListStatus = SessionListStatus.All, + /** Transient unread lens; the open session always stays listed. */ + val unreadOnly: Boolean = false, + /** + * Persisted sort key + Active first (ignored while searching). Defaults to + * the uncustomized order so the toolbar dot never flashes before prefs load. + */ + val order: SessionListOrder = SessionListOrder.Default, /** * Local epoch-days that carry any session activity — the picker's * activity hint, derived before any list filtering (web @@ -97,7 +163,11 @@ data class SessionListUiState( val connectionStatus: HomeConnectionStatus? = null, ) { val hasMachineFilters: Boolean get() = machineFilters.size >= 2 - val hasActiveFilters: Boolean get() = activeMachineFilter != null || dateRange != null + val hasActiveFilters: Boolean + get() = activeMachineFilter != null || dateRange != null || statusFilter != SessionListStatus.All || unreadOnly + + /** Filters or a non-default order: the toolbar button carries a dot (web). */ + val isCustomized: Boolean get() = hasActiveFilters || !order.isDefault val isSearching: Boolean get() = searchQuery.isNotBlank() } @@ -132,8 +202,15 @@ class SessionListViewModel( /** Global SSE transport state (`SseEngine.connectionState(Global)`); none in tests by default. */ connectionState: Flow = emptyFlow(), private val nowMs: () -> Long = System::currentTimeMillis, + /** + * Sort key + Active first. Home passes the persisted prefs; the default is + * Home's unpersisted default, and the share picker passes the base order. + */ + private val orderStore: SessionListOrderStore = InMemorySessionListOrderStore(), ) { private val machineFilter = MutableStateFlow(null) + private val statusFilter = MutableStateFlow(SessionListStatus.All) + private val unreadOnly = MutableStateFlow(false) private val searchQuery = MutableStateFlow("") private val selectedSessionId = MutableStateFlow(null) private val isRefreshing = MutableStateFlow(false) @@ -185,8 +262,8 @@ class SessionListViewModel( combine(sessionStore.sessions, machineStore.machines, lastSeenStore.state) { sessions, machines, lastSeen -> Triple(sessions, machines, lastSeen) }, - combine(machineFilter, searchQuery, selectedSessionId) { filter, query, selected -> - Triple(filter, query, selected) + combine(machineFilter, searchQuery, selectedSessionId, statusFilter, unreadOnly) { filter, query, selected, status, unread -> + ListInputs(filter, query, selected, status, unread) }, combine( combine(isRefreshing, isOffline, hasRefreshedOnce, dateRange, timeZone) { refreshing, offline, loaded, range, _ -> @@ -195,18 +272,22 @@ class SessionListViewModel( lastRefreshedAt, connectionStatus, ) { chrome, refreshedAt, status -> chrome.copy(lastRefreshedAt = refreshedAt, connectionStatus = status) }, - ) { (sessions, machines, lastSeen), (filter, query, selected), chrome -> + orderStore.order, + ) { (sessions, machines, lastSeen), inputs, chrome, order -> buildUiState( sessions = sessions, machines = machines, lastSeen = lastSeen, - filter = filter, - searchQuery = query, - selectedSessionId = selected, + filter = inputs.machineFilter, + searchQuery = inputs.searchQuery, + selectedSessionId = inputs.selectedSessionId, isRefreshing = chrome.refreshing, isOffline = chrome.offline, hasLoaded = chrome.refreshedOnce || sessions.isNotEmpty(), dateRange = chrome.dateRange, + statusFilter = inputs.statusFilter, + unreadOnly = inputs.unreadOnly, + order = order, ).copy(lastRefreshedAt = chrome.lastRefreshedAt, connectionStatus = chrome.connectionStatus) }.stateIn( scope = scope, @@ -307,10 +388,32 @@ class SessionListViewModel( dateRange.value = null } - /** Reset the consolidated sheet's conditions without changing the search. */ + /** Web "Show" filter (transient, like the other sheet conditions). */ + fun setStatusFilter(status: SessionListStatus) { + statusFilter.value = status + } + + /** Web "Unread only" lens (transient). */ + fun setUnreadOnly(enabled: Boolean) { + unreadOnly.value = enabled + } + + /** Persisted sort key (app-wide). */ + fun setSort(sort: SessionListSort) { + scope.launch { orderStore.setSort(sort) } + } + + /** Persisted Active first (app-wide). */ + fun setActiveFirst(enabled: Boolean) { + scope.launch { orderStore.setActiveFirst(enabled) } + } + + /** Reset the consolidated sheet's conditions without changing the search or the order. */ fun clearFilters() { machineFilter.value = null dateRange.value = null + statusFilter.value = SessionListStatus.All + unreadOnly.value = false } /** Search-box input; blank disables filtering/ranking entirely. */ @@ -428,6 +531,9 @@ class SessionListViewModel( isOffline: Boolean, hasLoaded: Boolean, dateRange: SessionDateRange? = null, + statusFilter: SessionListStatus = SessionListStatus.All, + unreadOnly: Boolean = false, + order: SessionListOrder = SessionListOrder.Base, ): SessionListUiState { // Use one current zone for both filtering and the calendar activity marks. val zone = zoneProvider() @@ -485,16 +591,25 @@ class SessionListViewModel( prepared.filter { SessionDateRangeFilter.matches(it.updatedAt, dateRange, zone) } } - val visible = if (activeFilter == null) { + val machineScoped = if (activeFilter == null) { timeScoped } else { timeScoped.filter { (it.metadata?.machineId ?: UNKNOWN_MACHINE_ID) == activeFilter } } + // Status and unread lenses never hide the open session (web). + val visible = machineScoped.filter { summary -> + summary.id == selectedSessionId || ( + statusFilter.includes(summary) && + (!unreadOnly || LastSeenStore.isUnread(summary, lastSeen)) + ) + } + // Text search: relevance ranking over the already-prepared corpus, - // pins kept contiguous ahead of ordinary rows. + // pins kept contiguous ahead of ordinary rows, base-order ties (web + // keeps the default order while a query is active). val searched = if (searchQuery.isBlank()) { - visible + if (order == SessionListOrder.Base) visible else sortSessionSummaries(visible, order) } else { val machineLabels = filters.associate { it.id to it.label } val index = SessionListSearch.buildSessionSearchScoreIndex(visible, searchQuery) { machineId -> @@ -537,9 +652,21 @@ class SessionListViewModel( isOffline = isOffline, dateRange = dateRange, dateActivityEpochDays = activityDays, + statusFilter = statusFilter, + unreadOnly = unreadOnly, + order = order, ) } + /** Row-selection inputs, aggregated so [combine] stays within its typed arity. */ + private data class ListInputs( + val machineFilter: String?, + val searchQuery: String, + val selectedSessionId: String?, + val statusFilter: SessionListStatus, + val unreadOnly: Boolean, + ) + /** Aggregated non-session inputs so [combine] stays within its typed arity. */ private data class ChromeState( val refreshing: Boolean, diff --git a/android/app/src/main/res/drawable/ic_presence_stopped.xml b/android/app/src/main/res/drawable/ic_presence_stopped.xml new file mode 100644 index 00000000..2ae6106c --- /dev/null +++ b/android/app/src/main/res/drawable/ic_presence_stopped.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml index b3ffa92c..efdd9e93 100644 --- a/android/app/src/main/res/values-ru/strings.xml +++ b/android/app/src/main/res/values-ru/strings.xml @@ -239,6 +239,21 @@ Не прочитано Подключено Выполняется + Выполняются фоновые задачи + Остановлена + Сортировать по + Последнему сообщению + Дате создания + Сначала активные + Показывать + Все сессии + Только активные + Только архивные + Только непрочитанные + Нет подходящих сессий + Измените или сбросьте фильтры, чтобы увидеть больше сессий. + осталось %1$s + нет heartbeat %1$s Не удалось отметить как прочитанное Поиск сессий Поиск сессий @@ -656,7 +671,7 @@ Воспроизвести Пауза Переподключение… Нажмите, чтобы повторить - Фильтры + Сортировка и фильтр Фильтры применены Сбросить Готово diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml index 7dd9f0fe..fb2cbacb 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -246,6 +246,21 @@ 未读 已连接 运行中 + 后台任务运行中 + 已停止 + 排序方式 + 最后消息时间 + 创建时间 + 活跃会话优先 + 显示 + 全部会话 + 仅活跃 + 仅已归档 + 仅未读 + 没有匹配的会话 + 调整或重置筛选以查看更多会话。 + 剩余 %1$s + 无心跳 %1$s 标记已读失败 搜索会话 搜索会话 @@ -663,7 +678,7 @@ 播放 暂停 正在重新连接… 点按重试 - 筛选 + 排序与筛选 已应用筛选 重置 完成 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 2ffe467b..c5d74424 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -239,6 +239,21 @@ Unread Connected Running + Background tasks running + Stopped + Sort by + Last message + Date created + Active first + Show + All sessions + Active only + Archived only + Unread only + No matching sessions + Change or reset the filters to see more sessions. + %1$s left + no heartbeat %1$s Couldn’t mark as read Search sessions Search sessions @@ -656,7 +671,7 @@ Play Pause Reconnecting… Tap to retry - Filters + Sort & filter Filters applied Reset Done diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefsTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefsTest.kt new file mode 100644 index 00000000..e11b6ca0 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListOrderPrefsTest.kt @@ -0,0 +1,50 @@ +package app.hapi.companion.feature.sessions + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import app.hapi.protocol.wire.SessionListOrder +import app.hapi.protocol.wire.SessionListSort +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +/** Sort + Active first persist app-wide; defaults are absent keys. */ +class SessionListOrderPrefsTest { + @get:Rule + val tmp = TemporaryFolder() + + @Test + fun `choices round-trip across a cold start and defaults stay absent`() = runTest { + val file = File(tmp.root, "order.preferences_pb") + val firstScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + try { + val dataStore = PreferenceDataStoreFactory.create(scope = firstScope) { file } + val prefs = SessionListOrderPrefs(dataStore) + assertEquals(SessionListOrder.Default, prefs.order.first()) + prefs.setSort(SessionListSort.Created) + prefs.setActiveFirst(false) + assertEquals(SessionListOrder(SessionListSort.Created, activeFirst = false), prefs.order.first()) + prefs.setActiveFirst(true) + assertNull(dataStore.data.first()[SessionListOrderPrefs.ACTIVE_FIRST_KEY], "Defaults are stored as absent keys") + } finally { + firstScope.coroutineContext[Job]?.cancelAndJoin() + } + + val secondScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + try { + val prefs = SessionListOrderPrefs(PreferenceDataStoreFactory.create(scope = secondScope) { file }) + assertEquals(SessionListOrder(SessionListSort.Created, activeFirst = true), prefs.order.first()) + } finally { + secondScope.coroutineContext[Job]?.cancelAndJoin() + } + } +} 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 bbb427f6..be7eea36 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 @@ -4,7 +4,10 @@ import app.hapi.data.sse.ConnectionState import app.hapi.data.store.LastSeenStore import app.hapi.data.store.MachineListStore import app.hapi.data.store.SessionListStore +import app.hapi.protocol.wire.AttachedJob import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.SessionListOrder +import app.hapi.protocol.wire.SessionListSort import app.hapi.protocol.wire.MachineMetadata import app.hapi.protocol.wire.SessionSummary import app.hapi.protocol.wire.SessionSummaryMetadata @@ -172,6 +175,7 @@ private fun TestScope.buildViewModel( machines: FakeMachineStore = FakeMachineStore(), zoneProvider: () -> ZoneId = { ZoneId.of("UTC") }, connection: MutableStateFlow = MutableStateFlow(ConnectionState(ConnectionState.Phase.Connected)), + orderStore: SessionListOrderStore = InMemorySessionListOrderStore(), ): Triple { val viewModel = SessionListViewModel( sessionStore = sessions, @@ -182,6 +186,7 @@ private fun TestScope.buildViewModel( zoneProvider = zoneProvider, connectionState = connection, nowMs = { currentTime }, + orderStore = orderStore, ) return Triple(viewModel, sessions, machines) } @@ -233,6 +238,76 @@ class SessionListViewModelTest { assertEquals(5_000L, offline.lastRefreshedAt) } + @Test + fun `status and unread filters keep the open session and a running job counts as live`() = runTest { + val (viewModel, sessions) = buildViewModel() + val job = AttachedJob(key = "k", label = "Import", heartbeatAt = 0, startedAt = 0, updatedAt = 0) + sessions.set( + summary("live", active = true, updatedAt = 3).copy(contentRevision = 1), + summary("stopped", updatedAt = 2), + summary("idle-job", updatedAt = 1).copy(attachedJob = job), + ) + viewModel.uiState.first { it.rows.size == 3 } + + viewModel.setStatusFilter(SessionListStatus.Active) + val active = viewModel.uiState.first { it.statusFilter == SessionListStatus.Active } + assertEquals(setOf("live", "idle-job"), active.rows.map { it.id }.toSet(), "A running job is live work (web #1404)") + assertTrue(active.hasActiveFilters) + + viewModel.setStatusFilter(SessionListStatus.Archived) + assertEquals(listOf("stopped"), viewModel.uiState.first { it.statusFilter == SessionListStatus.Archived }.rows.map { it.id }) + viewModel.setUnreadOnly(true) + assertTrue(viewModel.uiState.first { it.unreadOnly }.rows.isEmpty(), "Archived and unread: nothing matches") + viewModel.onSessionOpened("live") + assertEquals(listOf("live"), viewModel.uiState.first { it.rows.isNotEmpty() }.rows.map { it.id }, "The open session never disappears") + + viewModel.clearFilters() + val cleared = viewModel.uiState.first { !it.hasActiveFilters } + assertEquals(SessionListStatus.All, cleared.statusFilter) + assertFalse(cleared.unreadOnly) + assertEquals(3, cleared.rows.size) + } + + @Test + fun `active first is the home default and pins still lead`() = runTest { + val (viewModel, sessions) = buildViewModel(orderStore = InMemorySessionListOrderStore(SessionListOrder.Default)) + sessions.set( + summary("old-live", active = true, name = "Review old").copy(createdAt = 3, lastUserMessageAt = 100), + summary("new-stopped", name = "Review new").copy(createdAt = 1, lastUserMessageAt = 200), + summary("pinned-stopped", name = "Review pinned", pinned = true), + ) + val initial = viewModel.uiState.first { it.rows.size == 3 } + assertEquals(listOf("pinned-stopped", "old-live", "new-stopped"), initial.rows.map { it.id }) + assertFalse(initial.isCustomized) + + viewModel.setActiveFirst(false) + val inputOrder = viewModel.uiState.first { !it.order.activeFirst } + assertEquals(listOf("pinned-stopped", "new-stopped", "old-live"), inputOrder.rows.map { it.id }) + viewModel.setSort(SessionListSort.Created) + val created = viewModel.uiState.first { it.order.sort == SessionListSort.Created } + assertEquals(listOf("pinned-stopped", "old-live", "new-stopped"), created.rows.map { it.id }) + assertTrue(created.isCustomized) + assertFalse(created.hasActiveFilters, "Ordering is a preference, not a filter") + viewModel.clearFilters() + assertEquals(SessionListSort.Created, viewModel.uiState.value.order.sort, "Reset clears filters only") + + // Search keeps relevance with the base order as tie-break, as on web. + viewModel.setActiveFirst(true) + viewModel.setSearchQuery("Review") + val searched = viewModel.uiState.first { it.isSearching && it.order.activeFirst } + assertEquals(listOf("pinned-stopped", "new-stopped", "old-live"), searched.rows.map { it.id }) + } + + @Test + fun `the share picker's base order ignores liveness`() = runTest { + val (viewModel, sessions) = buildViewModel(orderStore = InMemorySessionListOrderStore(SessionListOrder.Base)) + sessions.set( + summary("old-live", active = true).copy(lastUserMessageAt = 100), + summary("new-stopped").copy(lastUserMessageAt = 200), + ) + assertEquals(listOf("new-stopped", "old-live"), viewModel.uiState.first { it.rows.size == 2 }.rows.map { it.id }) + } + @Test fun `reset clears machine and date filters while preserving search`() = runTest { val (viewModel, sessions) = buildViewModel() diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionPresenceTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionPresenceTest.kt new file mode 100644 index 00000000..f5651e26 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionPresenceTest.kt @@ -0,0 +1,37 @@ +package app.hapi.companion.feature.sessions + +import app.hapi.protocol.wire.AttachedJob +import app.hapi.protocol.wire.SessionSummary +import kotlin.test.Test +import kotlin.test.assertEquals + +/** Web #2296 presence marks and the #1404 attached-job row line. */ +class SessionPresenceTest { + private val job = AttachedJob(key = "k", label = "Import", heartbeatAt = 0, startedAt = 0, updatedAt = 0) + + @Test + fun `every state has its own mark and a running job is work`() { + val idle = SessionSummary(id = "s", active = true) + assertEquals(SessionPresence.Waiting, SessionPresence.of(idle)) + assertEquals(SessionPresence.Background, SessionPresence.of(idle.copy(backgroundTaskCount = 2))) + assertEquals(SessionPresence.Working, SessionPresence.of(idle.copy(backgroundTaskCount = 2, thinking = true)), "A turn outranks background tasks") + assertEquals(SessionPresence.Stopped, SessionPresence.of(idle.copy(active = false, thinking = true)), "Stale thinking is not work") + assertEquals(SessionPresence.Stopped, SessionPresence.of(idle.copy(active = false, backgroundTaskCount = 1))) + + assertEquals(SessionPresence.Working, SessionPresence.of(idle.copy(active = false, attachedJob = job)), "Work that outlives the agent") + assertEquals(SessionPresence.Background, SessionPresence.of(idle.copy(backgroundTaskCount = 1, attachedJob = job)), "Same precedence as web") + assertEquals(SessionPresence.Stopped, SessionPresence.of(idle.copy(active = false, attachedJob = job.copy(status = "completed")))) + assertEquals(listOf(true, true, false, false), SessionPresence.entries.map { it.pulses }) + } + + @Test + fun `job line says progress and elapsed and admits staleness`() { + val minute = 60_000L + fun text(job: AttachedJob, now: Long) = attachedJobText(job, now, left = { "$it left" }, noHeartbeat = { "no heartbeat $it" }) + val counted = job.copy(done = 12.0, total = 30.0, unit = "files", heartbeatAt = 184 * minute) + assertEquals("Import · 40% · 12/30 files · 3h 5m", text(counted, 185 * minute)) + assertEquals("Import · 18 files left · 5m", text(counted.copy(remaining = 18.0, heartbeatAt = 5 * minute), 5 * minute), "Remaining wins, as on web") + assertEquals("Import · <1m", text(job, 0)) + assertEquals("Import · no heartbeat 20m", text(job, 20 * minute), "A frozen job is not passed off as live") + } +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/store/SessionStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/SessionStore.kt index c45f9136..8009c351 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/store/SessionStore.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/SessionStore.kt @@ -428,14 +428,16 @@ class SessionStore( val index = list.indexOfFirst { it.id == session.id } val existing = if (index >= 0) list[index] else null // The projection cannot derive the hub-computed scheduled-message - // fields — carry them over from the previous row (web - // `upsertSessionSummary`). + // fields or the attached job — carry them over from the previous + // row (web `upsertSessionSummary`). val summary = SummaryPatching.toSessionSummary(session).copy( contentRevision = listOfNotNull(existing?.contentRevision, session.contentRevision).maxOrNull(), readState = SessionReadState.merge(existing?.readState, session.readState), lastUserMessageAt = session.lastUserMessageAt?.let { maxOf(existing?.lastUserMessageAt ?: 0, it) } ?: existing?.lastUserMessageAt, futureScheduledMessageCount = existing?.futureScheduledMessageCount ?: 0, nextScheduledAt = existing?.nextScheduledAt, + attachedJob = existing?.attachedJob, + attachedJobUpdatedAt = existing?.attachedJobUpdatedAt ?: 0, ) val next = list.toMutableList() if (index >= 0) next[index] = summary else next.add(summary) diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/SessionStoreTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/SessionStoreTest.kt index 28aefa42..5bc7fa53 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/store/SessionStoreTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/SessionStoreTest.kt @@ -188,6 +188,34 @@ class SessionStoreTest { assertSame(before, store.sessions.value) } + @Test + fun `attached job patches update the row without a refetch and survive full sessions`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 100))) + store.refresh() + store.applySessionEvent( + globalScope, + sessionUpdatedEvent( + "s1", + """{"attachedJob":{"version":3,"value":{"key":"import","label":"Import","status":"running",""" + + """"heartbeatAt":10,"startedAt":5,"updatedAt":10}}}""", + ), + ) + assertEquals("Import", store.sessions.value.single().attachedJob?.label) + assertEquals(3L, store.sessions.value.single().attachedJobUpdatedAt) + + // A full-session event cannot carry the job; the row keeps it. + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(session("s1", updatedAt = 200)))) + assertEquals("Import", store.sessions.value.single().attachedJob?.label) + assertEquals(200, store.sessions.value.single().updatedAt) + + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", """{"attachedJob":{"version":4,"value":null}}""")) + assertNull(store.sessions.value.single().attachedJob) + // A rejected patch would schedule a batched list refetch. + testScheduler.advanceTimeBy(10_000) + testScheduler.runCurrent() + assertEquals(1, server.requestCount, "Job patches are applied, not refetched") + } + @Test fun `patch for an unlisted session falls back to a list refetch`() = runStoreTest { store, server -> server.enqueueJson(sessionsResponseJson(summary("brand-new", updatedAt = 10))) diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AttachedJob.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AttachedJob.kt new file mode 100644 index 00000000..173887fd --- /dev/null +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/AttachedJob.kt @@ -0,0 +1,83 @@ +package app.hapi.protocol.wire + +import kotlin.math.roundToInt +import kotlinx.serialization.Serializable + +/** + * Session-attached long-running work (tiann/hapi#1404): the primary job on a + * [SessionSummary], independent of agent `active` / `thinking` — work that + * outlives the agent. Mirrors `AttachedJobSchema` (`shared/src/schemas.ts`); + * supervisor-only fields (`runId`, wake options) are ignored on decode. + * [status] stays a string so a status this client does not know cannot fail + * the whole list; only [STATUS_RUNNING] is live work. + */ +@Serializable +data class AttachedJob( + val key: String, + val label: String, + val status: String = STATUS_RUNNING, + val done: Double? = null, + val total: Double? = null, + val remaining: Double? = null, + val unit: String? = null, + val detail: String? = null, + val heartbeatAt: Long, + val startedAt: Long, + val updatedAt: Long, +) { + val isRunning: Boolean get() = status == STATUS_RUNNING + + /** No heartbeat for [STALE_AFTER_MS]: the row turns amber but keeps its progress. */ + fun isStale(nowMs: Long): Boolean = nowMs - heartbeatAt > STALE_AFTER_MS + + /** + * Whole percent from `done`/`total`, capped at 100; null without a positive + * total. `remaining` takes precedence in labels (web + * `formatAttachedJobProgress`), so callers check it first. + */ + val percent: Int? + get() { + val done = done ?: return null + val total = total?.takeIf { it > 0 } ?: return null + return minOf(100, (done / total * 100).roundToInt()) + } + + /** + * Determinate bar fill in 0..1, or null for an indeterminate bar (web + * `attachedJobFraction`: `remaining` wins over `done`/`total`). + */ + val fraction: Float? + get() { + val total = total?.takeIf { it > 0 } ?: return null + val done = remaining?.let { maxOf(0.0, total - it) } ?: done ?: return null + return (done / total).coerceIn(0.0, 1.0).toFloat() + } + + companion object { + const val STATUS_RUNNING: String = "running" + + /** Web `ATTACHED_JOB_STALE_MS`. */ + const val STALE_AFTER_MS: Long = 15 * 60 * 1000L + } +} + +/** + * Lettered elapsed time for list chrome, at most two units (web + * `formatCompactElapsed`), never an ETA. Rows tick per minute, so anything + * under a minute reads `<1m` rather than a seconds count that would freeze. + */ +fun formatCompactElapsed(elapsedMs: Long): String { + if (elapsedMs < 60_000) return "<1m" + val totalMinutes = elapsedMs / 60_000 + if (totalMinutes < 60) return "${totalMinutes}m" + val hours = totalMinutes / 60 + val minutes = totalMinutes % 60 + if (hours < 24) return if (minutes > 0) "${hours}h ${minutes}m" else "${hours}h" + val days = hours / 24 + val remainingHours = hours % 24 + return if (remainingHours > 0) "${days}d ${remainingHours}h" else "${days}d" +} + +/** Progress counts as the hub sent them: integers without a decimal point. */ +fun formatJobQuantity(value: Double): String = + if (value % 1.0 == 0.0 && kotlin.math.abs(value) < 1e15) value.toLong().toString() else value.toString() diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionPatch.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionPatch.kt index 6f599cee..90d59514 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionPatch.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionPatch.kt @@ -59,6 +59,11 @@ data class SessionPatch( val backgroundTaskCount: Int? = null, /** Bare refetch trigger for `GET /sessions/:id/scratchlist`; carries no data. */ val scratchlistUpdatedAt: Long? = null, + /** + * tiann/hapi#1404: the list row's primary attached job; a null value + * clears it. Summary-only — the detail [Session] has no such field. + */ + val attachedJob: VersionedValue? = null, val contentRevision: Long? = null, val readState: SessionReadState? = null, ) @@ -70,7 +75,7 @@ object SessionPatches { "metadata", "agentState", "todos", "teamState", "model", "modelReasoningEffort", "effort", "serviceTier", "permissionMode", "collaborationMode", "copilotAgentMode", - "backgroundTaskCount", "scratchlistUpdatedAt", + "backgroundTaskCount", "scratchlistUpdatedAt", "attachedJob", // Web-only status-panel list; accepted so the patch is not refetched. "backgroundTasks", ) @@ -144,6 +149,12 @@ object SessionPatches { }, backgroundTaskCount = obj["backgroundTaskCount"]?.let { it.intOrNull ?: return null }, scratchlistUpdatedAt = obj["scratchlistUpdatedAt"]?.let { it.longOrNull ?: return null }, + attachedJob = obj["attachedJob"]?.let { wrapper -> + versioned(wrapper) { value -> + if (value is JsonNull) null + else HapiJson.decodeFromJsonElement(AttachedJob.serializer(), value) + } ?: return null + }, ) } catch (_: Exception) { null diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSorting.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSorting.kt index 620a4ed4..46caf85e 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSorting.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSorting.kt @@ -1,15 +1,69 @@ package app.hapi.protocol.wire -/** Mirrors shared/src/sessionOrder.ts. Output and liveness do not affect order. */ -val SessionOrderComparator: Comparator = - compareByDescending { it.lastUserMessageAt ?: it.createdAt ?: 0L } +/** Session-list sort key (web `SessionListSort`, `web/src/hooks/useSessionListView.ts`). */ +enum class SessionListSort(val storageKey: String) { + /** The user's latest prompt, falling back to creation. Agent output never moves it. */ + LastMessage("last-message"), + + /** Newest sessions first. */ + Created("created"); + + companion object { + /** Unknown/corrupt stored values (e.g. web's dropped "activity") degrade to [LastMessage]. */ + fun fromStorageKey(raw: String?): SessionListSort = entries.firstOrNull { it.storageKey == raw } ?: LastMessage + } +} + +/** + * Session-list ordering choices: a sort key and whether connected sessions + * lead each pin tier (web `SessionListView.sort` / `.activeFirst`). + */ +data class SessionListOrder( + val sort: SessionListSort = SessionListSort.LastMessage, + val activeFirst: Boolean = true, +) { + val isDefault: Boolean get() = this == Default + + companion object { + /** The list default (web `DEFAULT_SESSION_LIST_VIEW`). */ + val Default = SessionListOrder() + + /** The base order every store keeps: user input only, no liveness. */ + val Base = SessionListOrder(SessionListSort.LastMessage, activeFirst = false) + } +} + +/** Mirrors web `getSessionSortKey` (`web/src/lib/sessionListOrder.ts`). */ +fun sessionSortKey(session: SessionSummary, sort: SessionListSort): Long = when (sort) { + SessionListSort.Created -> session.createdAt ?: 0L + SessionListSort.LastMessage -> session.lastUserMessageAt ?: session.createdAt ?: 0L +} + +/** The chosen key descending, then creation descending, then id. */ +fun sessionOrderComparator(sort: SessionListSort): Comparator = + compareByDescending { sessionSortKey(it, sort) } .thenByDescending { it.createdAt ?: 0L } .thenBy { it.id } -val SessionSummaryComparator: Comparator = - compareByDescending { it.globalPinned == true } +/** + * Global pins, project pins, then (with `activeFirst`) connected sessions, + * then the sort key. Web `createSessionComparator` under the flat native + * list's pin tiers: manual pins still come first. + */ +fun sessionSummaryComparator(order: SessionListOrder): Comparator { + val pins = compareByDescending { it.globalPinned == true } .thenByDescending { it.pinned == true } - .then(SessionOrderComparator) + val live = if (order.activeFirst) pins.thenByDescending { it.active } else pins + return live.then(sessionOrderComparator(order.sort)) +} + +/** Mirrors shared/src/sessionOrder.ts. Output and liveness do not affect order. */ +val SessionOrderComparator: Comparator = sessionOrderComparator(SessionListSort.LastMessage) + +val SessionSummaryComparator: Comparator = sessionSummaryComparator(SessionListOrder.Base) fun sortSessionSummaries(sessions: List): List = sessions.sortedWith(SessionSummaryComparator) + +fun sortSessionSummaries(sessions: List, order: SessionListOrder): List = + sessions.sortedWith(sessionSummaryComparator(order)) diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSummary.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSummary.kt index 3aa22843..efc2332a 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSummary.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSummary.kt @@ -36,6 +36,10 @@ data class SessionSummary( val futureScheduledMessageCount: Int = 0, /** Epoch ms of the soonest uninvoked future scheduled message, or null. */ val nextScheduledAt: Long? = null, + /** Primary session-attached job (tiann/hapi#1404), or null. */ + val attachedJob: AttachedJob? = null, + /** Watermark for versioned `attachedJob` patches; absent (older hub) gates as 0. */ + val attachedJobUpdatedAt: Long = 0, val model: String? = null, val modelReasoningEffort: String? = null, val effort: String? = null, diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SummaryPatching.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SummaryPatching.kt index e7e01d32..860a57fb 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SummaryPatching.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SummaryPatching.kt @@ -210,6 +210,8 @@ object SummaryPatching { * (see the class doc for why equality is safe here and only here), then * recompute the derived fields. `pendingRequests`' fallback `since` is * the summary's post-patch `updatedAt`, matching the reference. + * - `attachedJob` gates strictly (`>`) on `attachedJobUpdatedAt`, like + * the reference: a lagged heartbeat must not resurrect a clear. * - `teamState` is a summary no-op (not rendered on the list). * - `activeTurnStartedAt` / `scratchlistUpdatedAt` / `serviceTier` / * `permissionMode` / `collaborationMode` / `copilotAgentMode` have no @@ -269,6 +271,11 @@ object SummaryPatching { ) } } + patch.attachedJob?.let { job -> + if (job.version > current.attachedJobUpdatedAt) { + next = next.copy(attachedJob = job.value, attachedJobUpdatedAt = job.version) + } + } return next } @@ -340,6 +347,9 @@ object SummaryPatching { && current.metadataVersion == next.metadataVersion && current.agentStateVersion == next.agentStateVersion && current.todosUpdatedAt == next.todosUpdatedAt + // Heartbeats move only `heartbeatAt`, which drives the stale state. + && current.attachedJob == next.attachedJob + && current.attachedJobUpdatedAt == next.attachedJobUpdatedAt } /** diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/AttachedJobTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/AttachedJobTest.kt new file mode 100644 index 00000000..fc7185c3 --- /dev/null +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/AttachedJobTest.kt @@ -0,0 +1,93 @@ +package app.hapi.protocol.wire + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement + +/** + * tiann/hapi#1404 on the list row: wire decoding, the strict `>` version gate + * of web `patchSessionSummary`, render relevance and the row helpers. + */ +class AttachedJobTest { + private val jobJson = """{"key":"import","label":"Import","status":"running","done":12,"total":30,""" + + """"unit":"files","runId":"r1","wakeOnTerminal":true,"heartbeatAt":5000,"startedAt":1000,"updatedAt":5000}""" + + private fun element(json: String): JsonElement = Json.parseToJsonElement(json) + + private fun patch(json: String): SessionPatch = assertNotNull(SessionPatches.parse(element(json))) + + @Test + fun `list rows decode jobs leniently`() { + val row = """{"id":"s1","active":false,"attachedJob":$jobJson,"attachedJobUpdatedAt":7}""" + val decoded = HapiJson.decodeFromString(SessionSummary.serializer(), row) + assertEquals("Import", decoded.attachedJob?.label) + assertEquals(true, decoded.attachedJob?.isRunning) + assertEquals(7L, decoded.attachedJobUpdatedAt) + + val paused = HapiJson.decodeFromString(SessionSummary.serializer(), row.replace("\"running\"", "\"paused\"")) + assertEquals(false, paused.attachedJob?.isRunning, "A new status must not fail the list") + + val legacy = HapiJson.decodeFromString(SessionSummary.serializer(), """{"id":"s1","active":false}""") + assertNull(legacy.attachedJob) + assertEquals(0L, legacy.attachedJobUpdatedAt) + } + + @Test + fun `job patches parse instead of forcing a refetch`() { + val parsed = patch("""{"attachedJob":{"version":5,"value":$jobJson}}""") + assertEquals(5L, parsed.attachedJob?.version) + assertEquals(12.0, parsed.attachedJob?.value?.done) + assertNull(patch("""{"attachedJob":{"version":6,"value":null}}""").attachedJob?.value) + assertNull(SessionPatches.parse(element("""{"attachedJob":{"version":6}}""")), "value key is required") + } + + @Test + fun `patches apply only when strictly newer`() { + val empty = SessionSummary(id = "s1", active = false) + val start = patch("""{"attachedJob":{"version":5,"value":$jobJson}}""") + val running = SummaryPatching.applySessionSummaryPatch(empty, start) + assertEquals(12.0, running.attachedJob?.done) + assertEquals(5L, running.attachedJobUpdatedAt) + assertFalse(SummaryPatching.isRenderIrrelevantPatch(empty, running)) + + val cleared = SummaryPatching.applySessionSummaryPatch(running, patch("""{"attachedJob":{"version":6,"value":null}}""")) + assertNull(cleared.attachedJob) + assertEquals(6L, cleared.attachedJobUpdatedAt) + + // Dual SSE: a lagged heartbeat cannot resurrect the clear; an equal + // version is a replay. + assertNull(SummaryPatching.applySessionSummaryPatch(cleared, start).attachedJob) + val heartbeat = running.attachedJob!!.copy(heartbeatAt = 9_000) + val replay = SummaryPatching.applySessionSummaryPatch(running, SessionPatch(attachedJob = VersionedValue(5, heartbeat))) + assertEquals(running, replay) + val beat = SummaryPatching.applySessionSummaryPatch(running, SessionPatch(attachedJob = VersionedValue(7, heartbeat))) + assertFalse(SummaryPatching.isRenderIrrelevantPatch(running, beat), "Heartbeats drive staleness") + assertTrue(SummaryPatching.isRenderIrrelevantPatch(running, running.copy(activeAt = 99))) + } + + @Test + fun `row helpers match the web labels`() { + val job = AttachedJob(key = "k", label = "Import", done = 12.0, total = 30.0, heartbeatAt = 0, startedAt = 0, updatedAt = 0) + assertEquals(40, job.percent) + assertEquals(0.4f, job.fraction) + assertEquals(100, job.copy(done = 45.0).percent, "Capped") + assertEquals(0.6f, job.copy(remaining = 12.0).fraction, "Remaining wins, as on web") + assertNull(job.copy(total = null).percent) + assertNull(job.copy(total = null).fraction, "No honest fraction: indeterminate bar") + assertFalse(job.isStale(AttachedJob.STALE_AFTER_MS)) + assertTrue(job.isStale(AttachedJob.STALE_AFTER_MS + 1)) + + assertEquals("<1m", formatCompactElapsed(59_999)) + assertEquals("5m", formatCompactElapsed(5 * 60_000L)) + assertEquals("3h 5m", formatCompactElapsed(3 * 3_600_000L + 5 * 60_000L)) + assertEquals("2h", formatCompactElapsed(2 * 3_600_000L)) + assertEquals("1d 2h", formatCompactElapsed(26 * 3_600_000L)) + assertEquals("12", formatJobQuantity(12.0)) + assertEquals("1.5", formatJobQuantity(1.5)) + } +} diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SessionSortingTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SessionSortingTest.kt index 876a60f7..81fe0d1d 100644 --- a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SessionSortingTest.kt +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SessionSortingTest.kt @@ -16,6 +16,37 @@ class SessionSortingTest { assertEquals(listOf("old", "new"), sortSessionSummaries(listOf(old.copy(lastUserMessageAt = 300), newer)).map { it.id }) } + @Test + fun `active first leads each pin tier without beating pins`() { + val rows = listOf( + summary("new-stopped", 2, 200), + summary("old-live", 1, 100).copy(active = true), + summary("pinned-stopped", at = 1).copy(pinned = true), + summary("global", at = 0).copy(globalPinned = true), + summary("pinned-live", at = 0).copy(pinned = true, active = true), + ) + assertEquals( + listOf("global", "pinned-live", "pinned-stopped", "old-live", "new-stopped"), + sortSessionSummaries(rows, SessionListOrder.Default).map { it.id }, + ) + assertEquals( + listOf("global", "pinned-stopped", "pinned-live", "new-stopped", "old-live"), + sortSessionSummaries(rows, SessionListOrder.Base).map { it.id }, + ) + assertEquals(sortSessionSummaries(rows), sortSessionSummaries(rows, SessionListOrder.Base)) + } + + @Test + fun `created sort ignores input and stored keys match web`() { + val rows = listOf(summary("early", 1, 900), summary("unknown", at = 999), summary("late", 5, 10)) + val created = SessionListOrder(SessionListSort.Created, activeFirst = false) + assertEquals(listOf("late", "early", "unknown"), sortSessionSummaries(rows, created).map { it.id }) + assertEquals(listOf("unknown", "early", "late"), sortSessionSummaries(rows, SessionListOrder.Base).map { it.id }) + assertEquals("last-message", SessionListSort.LastMessage.storageKey) + assertEquals(SessionListSort.LastMessage, SessionListSort.fromStorageKey("activity")) + assertEquals(SessionListOrder(SessionListSort.LastMessage, activeFirst = true), SessionListOrder.Default) + } + @Test fun `manual pins still come first`() { val rows = listOf(summary("new", at = 99), summary("project", at = 2).copy(pinned = true), summary("global", at = 1).copy(globalPinned = true)) diff --git a/docs/guide/native-apps.md b/docs/guide/native-apps.md index 3708628f..d341a517 100644 --- a/docs/guide/native-apps.md +++ b/docs/guide/native-apps.md @@ -118,12 +118,14 @@ project-pinned sessions, then your most recent input (`lastUserMessageAt`, falling back to creation time) descending, with creation time and session ID breaking ties; see [Session list](./session-list.md#ordering-and-grouping). The Web sidebar adds directory grouping, client-side search ranking and a sort and -filter menu. Both native apps offer machine filtering and relevance-ranked text -search. Android adds a date range. iOS mirrors the Web sort and filter menu: -sort by last message or date created, **Active first** (on by default; manual -pins still come first), show all, active or archived sessions, plus an -unread-only lens and **Mark All as Read**. Android and iOS README files describe -their platform-specific filter presentation and session-row differences. +filter menu. Both native apps mirror that menu: sort by last message or date +created, **Active first** (on by default; manual pins still come first), show +all, active or archived sessions, and an unread-only lens, alongside machine +filtering and relevance-ranked text search. Android adds a date range; iOS adds +**Mark All as Read**. Rows in all three clients use the same presence badges +and show a running [attached job](./session-jobs.md). Android and iOS README +files describe their platform-specific filter presentation and session-row +differences. Selecting an attachment starts its upload after preparation, before you send the message or save the Scratchlist entry. Removing it requests cleanup of diff --git a/docs/guide/session-jobs.md b/docs/guide/session-jobs.md index 53f30f9f..06f8073b 100644 --- a/docs/guide/session-jobs.md +++ b/docs/guide/session-jobs.md @@ -67,10 +67,11 @@ Prefer `"$HAPI_SESSION_ID"` only when it matches the operator chat URL uuid. Rem | `fraction` | `--remaining N --total M` **or** `--done N --total M` | determinate fill | | `until` | `--until ` | determinate countdown (`s`); `job run` heartbeats re-stamp `remaining` | -The bar and stripes are the Web list. The iOS list shows the same job as one -text line in place of the project name (`label · remaining or percent · -elapsed`, amber with `no heartbeat` after ~15m) and a working presence badge, -without a bar. Android does not show attached jobs yet. +The bar and stripes are the Web list. The native lists show the same job as one +text line (`label · remaining or percent · elapsed`, amber with `no heartbeat` +after ~15m) and a working presence badge: Android adds a thin bar under the +row's meta line (Material indeterminate animation instead of stripes); iOS puts +the line in place of the project name, without a bar. #### Alive-only / indeterminate (`--progress unknown`)