From f702cbf844cd155bac3d50b73822ae9a0db28446 Mon Sep 17 00:00:00 2001 From: weishu Date: Mon, 17 Aug 2026 15:47:05 +0800 Subject: [PATCH] feat(android): session/machine stores + session list (B-M2b) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit :core:protocol — summary-side patch path ported from the web reference: - wire/SummaryPatching.kt: patchSessionSummary port with the summary path's >= versioned gates (replicated web divergence vs the detail path's strict >, documented), derived-field recompute (pendingRequestsCount/Kinds/Requests capped 5, todoProgress), render-irrelevance filter (activeAt-only keep-alive suppression), toSessionSummary/toSessionSummaryMetadata projection, and the deprecated canApplyVersionedSummaryPatch legacy gate. - wire/SessionSorting.kt: exact sortSessionSummaries comparator (globalPinned > pinned > active > pendingRequestsCount among active > updatedAt desc; Long-safe, stable). - SessionMetadata grows the per-flavor agent session id fields the agentSessionId projection needs. :core:data store/ — StateFlow stores with per-hub JSON snapshots: - JsonSnapshotStore: debounced (500 ms) atomic tmp+fsync+rename snapshots, synchronous cold-start load, corrupt files degrade to null. - SessionStore: sorted summary list + per-id detail cache (strict-> detail patching via SessionPatching), full-session upsert preserving hub-computed scheduled fields, REST fallback for unparseable payloads, coalesced refresh (16 ms batch like the web), optimistic pin/archive. - MachineStore: full/patch/null machine-updated decision tree per sse.md. - LastSeenStore: per-session last-seen watermarks + once-per-scope baseline seeding + unread derivation (sessionLastSeen.ts/sessionAttention.ts port). - StoreSyncTargets: SyncEventRouter fan-in — global-scope message-stream events refresh the list, gap handshakes full-resync. :app feature/sessions/ — standalone screen + plain-constructor ViewModel: - SessionListScreen: pinned section, status dot with thinking pulse, flavor/ machine/worktree meta line, pending badge, todo chip, unread dot, machine filter chips, PullToRefreshBox, offline banner, empty states, long-press pin/archive sheet; taps emit onOpenSession only (no navigation). - SessionListViewModel: store combine -> UiState, owns the global SSE subscription while started (subscribe after collector registration), entry refresh, error SharedFlow for snackbars. Tests: SummaryPatching/SessionSorting JVM tests (cases mined from useSSE.test.ts), store tests (stale/equal/newer patches, full replace, keep-alive identity, snapshot round-trips, optimistic rollback), ViewModel combine + handshake tests with fake stores. All of :core:protocol:test, :core:data:test, :app:testDebugUnitTest, :app:assembleDebug green. --- android/app/build.gradle.kts | 5 + .../feature/sessions/RelativeTime.kt | 22 + .../feature/sessions/SessionListScreen.kt | 571 ++++++++++++++++++ .../feature/sessions/SessionListViewModel.kt | 323 ++++++++++ .../sessions/SessionListViewModelTest.kt | 301 +++++++++ .../app/hapi/data/store/JsonSnapshotStore.kt | 102 ++++ .../app/hapi/data/store/LastSeenStore.kt | 97 +++ .../app/hapi/data/store/MachineStore.kt | 152 +++++ .../app/hapi/data/store/SessionStore.kt | 345 +++++++++++ .../app/hapi/data/store/StoreSyncTargets.kt | 82 +++ .../hapi/data/store/JsonSnapshotStoreTest.kt | 88 +++ .../app/hapi/data/store/LastSeenStoreTest.kt | 66 ++ .../app/hapi/data/store/MachineStoreTest.kt | 109 ++++ .../app/hapi/data/store/SessionStoreTest.kt | 313 ++++++++++ .../hapi/data/store/StoreSyncTargetsTest.kt | 164 +++++ .../app/hapi/data/store/StoreTestFixtures.kt | 127 ++++ .../app/hapi/protocol/wire/SessionMetadata.kt | 13 + .../app/hapi/protocol/wire/SessionSorting.kt | 41 ++ .../app/hapi/protocol/wire/SummaryPatching.kt | 351 +++++++++++ .../hapi/protocol/wire/SessionSortingTest.kt | 109 ++++ .../hapi/protocol/wire/SummaryPatchingTest.kt | 435 +++++++++++++ 21 files changed, 3816 insertions(+) create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/sessions/RelativeTime.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListScreen.kt create mode 100644 android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListViewModel.kt create mode 100644 android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListViewModelTest.kt create mode 100644 android/core/data/src/main/kotlin/app/hapi/data/store/JsonSnapshotStore.kt create mode 100644 android/core/data/src/main/kotlin/app/hapi/data/store/LastSeenStore.kt create mode 100644 android/core/data/src/main/kotlin/app/hapi/data/store/MachineStore.kt create mode 100644 android/core/data/src/main/kotlin/app/hapi/data/store/SessionStore.kt create mode 100644 android/core/data/src/main/kotlin/app/hapi/data/store/StoreSyncTargets.kt create mode 100644 android/core/data/src/test/kotlin/app/hapi/data/store/JsonSnapshotStoreTest.kt create mode 100644 android/core/data/src/test/kotlin/app/hapi/data/store/LastSeenStoreTest.kt create mode 100644 android/core/data/src/test/kotlin/app/hapi/data/store/MachineStoreTest.kt create mode 100644 android/core/data/src/test/kotlin/app/hapi/data/store/SessionStoreTest.kt create mode 100644 android/core/data/src/test/kotlin/app/hapi/data/store/StoreSyncTargetsTest.kt create mode 100644 android/core/data/src/test/kotlin/app/hapi/data/store/StoreTestFixtures.kt create mode 100644 android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSorting.kt create mode 100644 android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SummaryPatching.kt create mode 100644 android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SessionSortingTest.kt create mode 100644 android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SummaryPatchingTest.kt diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index c56f6359..56cc4caa 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -67,4 +67,9 @@ dependencies { implementation(libs.androidx.compose.material3) implementation(libs.androidx.compose.ui.tooling.preview) debugImplementation(libs.androidx.compose.ui.tooling) + + // JVM unit tests (ViewModel combine logic with fake stores). + testImplementation(libs.junit) + testImplementation(libs.kotlin.test) + testImplementation(libs.kotlinx.coroutines.test) } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/RelativeTime.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/RelativeTime.kt new file mode 100644 index 00000000..99b5d3a5 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/RelativeTime.kt @@ -0,0 +1,22 @@ +package app.hapi.companion.feature.sessions + +/** + * Compact relative-age label for list rows ("now", "5m", "3h", "2d"). + * Minute granularity is deliberate: it is why sub-minute `activeAt` churn can + * be dropped as render-irrelevant (`sse.md#keep-alive-noise`). + */ +fun formatRelativeAge(nowMs: Long, thenMs: Long): String { + val delta = nowMs - thenMs + if (delta < 60_000) return "now" + val minutes = delta / 60_000 + if (minutes < 60) return "${minutes}m" + val hours = minutes / 60 + if (hours < 24) return "${hours}h" + val days = hours / 24 + if (days < 7) return "${days}d" + val weeks = days / 7 + if (weeks < 5) return "${weeks}w" + val months = days / 30 + if (months < 12) return "${months}mo" + return "${days / 365}y" +} 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 new file mode 100644 index 00000000..54a7e538 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListScreen.kt @@ -0,0 +1,571 @@ +package app.hapi.companion.feature.sessions + +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +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.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import app.hapi.companion.ui.theme.HapiTheme +import app.hapi.protocol.catalog.Flavors +import app.hapi.protocol.wire.PendingRequest +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SessionSummaryMetadata +import app.hapi.protocol.wire.SummaryText +import app.hapi.protocol.wire.TodoProgress + +/** + * The session list (B-M2b) — standalone screen: navigation and app graph stay + * outside; taps surface through [onOpenSession]. + * + * Inventory (mirrors the web sidebar semantics): + * - offline banner over snapshot data, machine filter chips (≥ 2 machines), + * pull-to-refresh, empty state; + * - pinned section first (the sort already puts globalPinned/pinned rows on + * top; a header + divider make the boundary visible); + * - per row: status dot (active / thinking pulse), title, flavor + machine + * labels, summary/path line, relative `updatedAt`, pending-request badge, + * todo-progress chip, unread dot; + * - long-press → pin (none/project/global) + archive sheet with optimistic + * store updates; failures land in a snackbar. + * + * WIRING(M-integration): host constructs the ViewModel from AppGraph and + * passes a real `onOpenSession` (navigation). This screen starts/stops the + * ViewModel — and with it the global SSE subscription — with its composition. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SessionListScreen( + viewModel: SessionListViewModel, + onOpenSession: (sessionId: String) -> Unit, + modifier: Modifier = Modifier, +) { + val state by viewModel.uiState.collectAsState() + val snackbarHostState = remember { SnackbarHostState() } + var sheetRow by remember { mutableStateOf(null) } + + DisposableEffect(viewModel) { + viewModel.start() + onDispose { viewModel.stop() } + } + + LaunchedEffect(viewModel) { + viewModel.errors.collect { error -> + val label = when (error) { + is SessionListError.PinFailed -> "Pin failed" + is SessionListError.ArchiveFailed -> "Archive failed" + } + snackbarHostState.showSnackbar(error.message?.let { "$label: $it" } ?: label) + } + } + + Box(modifier = modifier.fillMaxSize()) { + Column(modifier = Modifier.fillMaxSize()) { + if (state.isOffline) { + OfflineBanner() + } + if (state.showMachineFilterBar) { + MachineFilterRow( + filters = state.machineFilters, + activeFilter = state.activeMachineFilter, + onSelect = viewModel::setMachineFilter, + ) + } + PullToRefreshBox( + isRefreshing = state.isRefreshing, + onRefresh = viewModel::refresh, + modifier = Modifier + .fillMaxWidth() + .weight(1f), + ) { + if (state.rows.isEmpty()) { + EmptyState(hasLoaded = state.hasLoaded, isOffline = state.isOffline) + } else { + SessionRows( + rows = state.rows, + onOpen = { sessionId -> + viewModel.onSessionOpened(sessionId) + onOpenSession(sessionId) + }, + onLongPress = { sheetRow = it }, + ) + } + } + } + SnackbarHost( + hostState = snackbarHostState, + modifier = Modifier.align(Alignment.BottomCenter), + ) + } + + sheetRow?.let { row -> + SessionActionsSheet( + row = row, + onDismiss = { sheetRow = null }, + onSetPinMode = { mode -> + viewModel.setPinMode(row.id, mode) + sheetRow = null + }, + onArchive = { + viewModel.archiveSession(row.id) + sheetRow = null + }, + ) + } +} + +// ------------------------------------------------------------------ list -- + +@Composable +private fun SessionRows( + rows: List, + onOpen: (String) -> Unit, + onLongPress: (SessionRowUi) -> Unit, +) { + // The sort contract puts globalPinned/pinned rows first; the boundary + // index is where the pinned section ends. + val pinnedCount = rows.takeWhile { + it.summary.globalPinned == true || it.summary.pinned == true + }.size + + LazyColumn(modifier = Modifier.fillMaxSize()) { + if (pinnedCount > 0) { + item(key = "header-pinned") { SectionHeader("Pinned") } + } + items(rows.take(pinnedCount), key = { it.id }) { row -> + SessionRow(row, onOpen = onOpen, onLongPress = onLongPress) + } + if (pinnedCount in 1 until rows.size) { + item(key = "divider-pinned") { + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + SectionHeader("Sessions") + } + } + items(rows.drop(pinnedCount), key = { it.id }) { row -> + SessionRow(row, onOpen = onOpen, onLongPress = onLongPress) + } + } +} + +@Composable +private fun SectionHeader(text: String) { + Text( + text = text, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp), + ) +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun SessionRow( + row: SessionRowUi, + onOpen: (String) -> Unit, + onLongPress: (SessionRowUi) -> Unit, +) { + val summary = row.summary + Row( + modifier = Modifier + .fillMaxWidth() + .combinedClickable( + onClick = { onOpen(row.id) }, + onLongClick = { onLongPress(row) }, + ) + .padding(horizontal = 16.dp, vertical = 10.dp), + verticalAlignment = Alignment.Top, + ) { + StatusIndicator( + active = summary.active, + thinking = summary.thinking, + modifier = Modifier.padding(top = 5.dp), + ) + Spacer(modifier = Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = row.title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (row.unread) FontWeight.SemiBold else FontWeight.Normal, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + if (row.unread) { + Spacer(modifier = Modifier.width(6.dp)) + UnreadDot() + } + Spacer(modifier = Modifier.weight(1f)) + Text( + text = formatRelativeAge(System.currentTimeMillis(), summary.updatedAt), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + MetaLine(row) + row.subtitle?.let { subtitle -> + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + BadgeLine(summary) + } + } +} + +@Composable +private fun MetaLine(row: SessionRowUi) { + val flavorLabel = row.flavor?.let(Flavors::label) + val worktree = row.summary.metadata?.worktree + val parts = buildList { + flavorLabel?.let(::add) + row.machineLabel?.let(::add) + worktree?.let { add(it.name.ifBlank { it.branch }) } + } + if (parts.isEmpty()) return + Text( + text = parts.joinToString(" · "), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) +} + +@Composable +private fun BadgeLine(summary: SessionSummary) { + val hasPending = summary.pendingRequestsCount > 0 + val todoProgress = summary.todoProgress + if (!hasPending && todoProgress == null) return + Row( + modifier = Modifier.padding(top = 4.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (hasPending) { + PendingBadge( + count = summary.pendingRequestsCount, + kinds = summary.pendingRequestKinds, + requests = summary.pendingRequests, + ) + } + todoProgress?.let { TodoChip(it) } + } +} + +/** + * Pending badge: authoritative `pendingRequestsCount` + kind wording; the + * capped `pendingRequests` slice names the first tool. + */ +@Composable +private fun PendingBadge(count: Int, kinds: List, requests: List) { + val needsInput = kinds.contains("input") && !kinds.contains("permission") + val label = when { + needsInput -> "needs input" + requests.isNotEmpty() -> "approve ${requests.first().tool}" + else -> "pending" + } + val text = if (count > 1) "$count · $label" else label + Surface( + color = MaterialTheme.colorScheme.tertiaryContainer, + contentColor = MaterialTheme.colorScheme.onTertiaryContainer, + shape = RoundedCornerShape(6.dp), + ) { + Text( + text = text, + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } +} + +@Composable +private fun TodoChip(progress: TodoProgress) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + shape = RoundedCornerShape(6.dp), + ) { + Text( + text = "☑ ${progress.completed}/${progress.total}", + style = MaterialTheme.typography.labelSmall, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } +} + +@Composable +private fun UnreadDot() { + Box( + modifier = Modifier + .size(8.dp) + .background(MaterialTheme.colorScheme.primary, CircleShape), + ) +} + +/** Solid dot for active, pulsing while thinking, hollow-ish gray when idle. */ +@Composable +private fun StatusIndicator(active: Boolean, thinking: Boolean, modifier: Modifier = Modifier) { + val color = when { + active -> Color(0xFF34C759) + else -> MaterialTheme.colorScheme.outlineVariant + } + val alpha = if (thinking) { + val transition = rememberInfiniteTransition(label = "thinking-pulse") + transition.animateFloat( + initialValue = 1f, + targetValue = 0.25f, + animationSpec = infiniteRepeatable( + animation = tween(durationMillis = 700, easing = LinearEasing), + repeatMode = RepeatMode.Reverse, + ), + label = "thinking-alpha", + ).value + } else { + 1f + } + Box( + modifier = modifier + .size(10.dp) + .alpha(alpha) + .background(color, CircleShape), + ) +} + +// --------------------------------------------------------------- chrome -- + +@Composable +private fun MachineFilterRow( + filters: List, + activeFilter: String?, + onSelect: (String?) -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 12.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + FilterChip( + selected = activeFilter == null, + onClick = { onSelect(null) }, + label = { Text("All") }, + ) + filters.forEach { filter -> + val label = filter.label.ifBlank { "Unknown machine" } + FilterChip( + selected = activeFilter == filter.id, + onClick = { onSelect(if (activeFilter == filter.id) null else filter.id) }, + label = { Text("$label · ${filter.sessionCount}") }, + ) + } + } +} + +@Composable +private fun OfflineBanner() { + Surface( + color = MaterialTheme.colorScheme.errorContainer, + contentColor = MaterialTheme.colorScheme.onErrorContainer, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = "Offline — showing cached sessions", + style = MaterialTheme.typography.labelMedium, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp), + ) + } +} + +@Composable +private fun EmptyState(hasLoaded: Boolean, isOffline: Boolean) { + // verticalScroll keeps the pull-to-refresh gesture available even though + // there is nothing to scroll. + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(32.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = when { + !hasLoaded && !isOffline -> "Loading sessions…" + isOffline -> "Hub unreachable" + else -> "No sessions yet" + }, + style = MaterialTheme.typography.titleMedium, + ) + Spacer(modifier = Modifier.size(8.dp)) + Text( + text = when { + !hasLoaded && !isOffline -> "Fetching the session list from the hub." + isOffline -> "Pull to retry once you are back online." + else -> "Start an agent with the hapi CLI and it will appear here." + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun SessionActionsSheet( + row: SessionRowUi, + onDismiss: () -> Unit, + onSetPinMode: (PinMode) -> Unit, + onArchive: () -> Unit, +) { + val summary = row.summary + ModalBottomSheet(onDismissRequest = onDismiss) { + Text( + text = row.title, + style = MaterialTheme.typography.titleMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + HorizontalDivider() + if (summary.pinned == true || summary.globalPinned == true) { + SheetAction("Unpin") { onSetPinMode(PinMode.None) } + } + if (summary.pinned != true) { + SheetAction("Pin to project") { onSetPinMode(PinMode.Project) } + } + if (summary.globalPinned != true) { + SheetAction("Pin globally") { onSetPinMode(PinMode.Global) } + } + SheetAction("Archive", destructive = true, onClick = onArchive) + Spacer(modifier = Modifier.size(16.dp)) + } +} + +@Composable +private fun SheetAction(text: String, destructive: Boolean = false, onClick: () -> Unit) { + ListItem( + headlineContent = { + Text( + text = text, + color = if (destructive) MaterialTheme.colorScheme.error else Color.Unspecified, + ) + }, + modifier = Modifier.clickable(onClick = onClick), + ) +} + +// -------------------------------------------------------------- preview -- + +private fun previewRow( + id: String, + title: String, + active: Boolean = false, + thinking: Boolean = false, + unread: Boolean = false, + pinned: Boolean = false, + pending: Int = 0, + todo: TodoProgress? = null, +): SessionRowUi = SessionRowUi( + summary = SessionSummary( + id = id, + active = active, + thinking = thinking, + activeAt = 0, + updatedAt = System.currentTimeMillis() - 300_000, + pinned = pinned, + metadata = SessionSummaryMetadata( + path = "/data/github/hapi", + flavor = "claude", + summary = SummaryText("Porting the session list to Compose"), + ), + todoProgress = todo, + pendingRequestsCount = pending, + pendingRequestKinds = if (pending > 0) listOf("permission") else emptyList(), + pendingRequests = if (pending > 0) { + listOf(PendingRequest(id = "r1", kind = "permission", tool = "Bash", since = 0)) + } else { + emptyList() + }, + ), + title = title, + subtitle = "Porting the session list to Compose", + machineLabel = "devbox", + flavor = "claude", + unread = unread, +) + +@Preview(showBackground = true) +@Composable +private fun SessionRowsPreview() { + HapiTheme { + Surface { + SessionRows( + rows = listOf( + previewRow("s1", "Pinned build fix", pinned = true), + previewRow("s2", "Session list UI", active = true, thinking = true, unread = true, todo = TodoProgress(3, 5)), + previewRow("s3", "Fixture sweep", active = true, pending = 2), + previewRow("s4", "Old research"), + ), + onOpen = {}, + onLongPress = {}, + ) + } + } +} 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 new file mode 100644 index 00000000..90ae0b69 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/sessions/SessionListViewModel.kt @@ -0,0 +1,323 @@ +package app.hapi.companion.feature.sessions + +import app.hapi.data.sse.SseEngine +import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.data.sse.SyncEventRouter +import app.hapi.data.store.LastSeenStore +import app.hapi.data.store.MachineListStore +import app.hapi.data.store.SessionListStore +import app.hapi.data.store.StoreSyncTargets +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SyncEvent +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.onSubscription +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +/** Sessions whose metadata carries no machine id group under this filter id. */ +const val UNKNOWN_MACHINE_ID: String = "__unknown__" + +/** One rendered list row: the summary plus everything derived for display. */ +data class SessionRowUi( + val summary: SessionSummary, + /** `getSessionTitle` port: name → summary text → path tail → id prefix. */ + val title: String, + /** Secondary line: summary text when it is not already the title, else the path. */ + val subtitle: String?, + val machineLabel: String?, + /** Raw flavor id (`claude`, `codex`, …); resolve labels via the catalog. */ + val flavor: String?, + val unread: Boolean, +) { + val id: String get() = summary.id +} + +data class MachineFilterUi( + /** Machine id or [UNKNOWN_MACHINE_ID]. */ + val id: String, + val label: String, + val sessionCount: Int, +) + +data class SessionListUiState( + val rows: List, + /** Render the chip bar only when at least two machines have sessions. */ + val machineFilters: List, + /** `null` = All. Always one of [machineFilters] ids (stale picks fall back). */ + val activeMachineFilter: String?, + val isRefreshing: Boolean, + /** True once either the snapshot or a refresh produced a list. */ + val hasLoaded: Boolean, + /** Last refresh failed — show the offline banner over snapshot data. */ + val isOffline: Boolean, +) { + val showMachineFilterBar: Boolean get() = machineFilters.size >= 2 +} + +/** + * Session-list state machine: combines [SessionListStore] / [MachineListStore] + * / [LastSeenStore] with the machine-filter selection into [uiState], owns the + * global SSE subscription while started, and forwards pin/archive actions with + * store-side optimistic updates. + * + * Plain constructor — no Android dependency, so JVM tests drive it with fake + * stores and `AppGraph` wiring is a one-liner. + * + * WIRING(M-integration): construct as + * `SessionListViewModel(sessionStore, machineStore, lastSeenStore, sseEngine, scope, hubKey)` + * from AppGraph, call [start]/[stop] from the screen's composition lifecycle + * (foreground/background belongs to `SseEngine.setLifecycleForeground`, wired + * at the Application level), and hand [errors] to the host's snackbar. + */ +class SessionListViewModel( + private val sessionStore: SessionListStore, + private val machineStore: MachineListStore, + private val lastSeenStore: LastSeenStore, + private val sseEngine: SseEngine, + private val scope: CoroutineScope, + /** Last-seen baseline scope, e.g. the hub origin. */ + private val hubKey: String = "default", + private val onToast: (SyncEvent.Toast) -> Unit = {}, +) { + private val machineFilter = MutableStateFlow(null) + private val isRefreshing = MutableStateFlow(false) + private val isOffline = MutableStateFlow(false) + private val hasRefreshedOnce = MutableStateFlow(false) + + private val _errors = MutableSharedFlow(extraBufferCapacity = 8) + + /** Transient action failures (pin/archive) for a snackbar. */ + val errors: SharedFlow = _errors.asSharedFlow() + + private val router = SyncEventRouter(StoreSyncTargets(sessionStore, machineStore, scope, onToast)) + private var sseJob: Job? = null + private var refreshJob: Job? = null + + val uiState: StateFlow = combine( + sessionStore.sessions, + machineStore.machines, + lastSeenStore.state, + machineFilter, + combine(isRefreshing, isOffline, hasRefreshedOnce) { refreshing, offline, loaded -> + Triple(refreshing, offline, loaded) + }, + ) { sessions, machines, lastSeen, filter, (refreshing, offline, refreshedOnce) -> + buildUiState( + sessions = sessions, + machines = machines, + lastSeen = lastSeen.lastSeen, + filter = filter, + isRefreshing = refreshing, + isOffline = offline, + hasLoaded = refreshedOnce || sessions.isNotEmpty(), + ) + }.stateIn( + scope = scope, + started = SharingStarted.Eagerly, + initialValue = SessionListUiState( + rows = emptyList(), + machineFilters = emptyList(), + activeMachineFilter = null, + isRefreshing = false, + hasLoaded = sessionStore.sessions.value.isNotEmpty(), + isOffline = false, + ), + ) + + /** + * Opens the global SSE pipe (dual-subscription model: this connection + * drives the list; the open chat adds its own in M2d2) and kicks an + * initial refresh. Safe to call repeatedly. + */ + fun start() { + if (sseJob?.isActive == true) return + val key = SseSubscriptionKey.Global + sseJob = scope.launch { + sseEngine.events(key) + // Subscribe only after this collector is registered — the + // engine's SharedFlow has zero replay, so a handshake emitted + // before registration would be lost. + .onSubscription { sseEngine.subscribe(key) } + .collect { router.route(key, it) } + } + // Explicit fetch on entry: the snapshot may be stale and a + // `resume: ok` handshake deliberately skips the REST resync. + refresh() + } + + /** Tears the global pipe down (the engine keeps the resume cursor). */ + fun stop() { + sseJob?.cancel() + sseJob = null + sseEngine.unsubscribe(SseSubscriptionKey.Global) + } + + /** Pull-to-refresh / initial load. Coalesces concurrent calls. */ + fun refresh() { + if (refreshJob?.isActive == true) return + refreshJob = scope.launch { + isRefreshing.value = true + try { + sessionStore.refresh() + machineStore.refresh() + isOffline.value = false + hasRefreshedOnce.value = true + // First successful list for this hub seeds the unread baseline + // so historical sessions do not all light up as unread. + lastSeenStore.initializeBaseline(hubKey, sessionStore.sessions.value) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + isOffline.value = true + } finally { + isRefreshing.value = false + } + } + } + + fun setMachineFilter(machineId: String?) { + machineFilter.value = machineId + } + + /** Call when navigating into a session: stamps the last-seen watermark. */ + fun onSessionOpened(sessionId: String) { + val summary = sessionStore.sessions.value.firstOrNull { it.id == sessionId } ?: return + lastSeenStore.markSeen(sessionId, summary.updatedAt) + } + + /** `PUT /sessions/:id/pin` with optimistic re-sort; failures surface on [errors]. */ + fun setPinMode(sessionId: String, mode: PinMode) { + scope.launch { + try { + sessionStore.setPinMode(sessionId, mode.wire) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + _errors.tryEmit(SessionListError.PinFailed(sessionId, error.message)) + } + } + } + + /** `POST /sessions/:id/archive` with optimistic removal; failures surface on [errors]. */ + fun archiveSession(sessionId: String) { + scope.launch { + try { + sessionStore.archiveSession(sessionId) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + _errors.tryEmit(SessionListError.ArchiveFailed(sessionId, error.message)) + } + } + } + + // ------------------------------------------------------------ mapping -- + + private fun buildUiState( + sessions: List, + machines: List, + lastSeen: Map, + filter: String?, + isRefreshing: Boolean, + isOffline: Boolean, + hasLoaded: Boolean, + ): SessionListUiState { + val machinesById = machines.associateBy { it.id } + + fun machineLabel(machineId: String?): String? { + if (machineId == null) return null + val metadata = machinesById[machineId]?.metadata ?: return machineId.take(8) + val displayName = metadata.displayName?.takeIf { it.isNotBlank() } + return displayName ?: metadata.host + } + + // Filter chips derive from ALL sessions (pre-filter), like the web — + // filtering first would drop chips and silently clear the selection. + val filters = sessions + .groupBy { it.metadata?.machineId ?: UNKNOWN_MACHINE_ID } + .map { (id, group) -> + MachineFilterUi( + id = id, + label = if (id == UNKNOWN_MACHINE_ID) "" else machineLabel(id).orEmpty(), + sessionCount = group.size, + ) + } + .sortedByDescending { it.sessionCount } + + // A persisted pick whose machine no longer has sessions falls back to + // All; with fewer than two machines the bar hides and never filters. + val activeFilter = filter + ?.takeIf { filters.size >= 2 && filters.any { chip -> chip.id == it } } + + val visible = if (activeFilter == null) { + sessions + } else { + sessions.filter { (it.metadata?.machineId ?: UNKNOWN_MACHINE_ID) == activeFilter } + } + + val rows = visible.map { summary -> + val title = sessionTitle(summary) + val summaryText = summary.metadata?.summary?.text?.takeIf { it.isNotBlank() } + SessionRowUi( + summary = summary, + title = title, + subtitle = when { + summaryText != null && summaryText != title -> summaryText + else -> summary.metadata?.path + }, + machineLabel = machineLabel(summary.metadata?.machineId), + flavor = summary.metadata?.flavor, + unread = LastSeenStore.isUnread(summary, lastSeen[summary.id] ?: 0), + ) + } + + return SessionListUiState( + rows = rows, + machineFilters = filters, + activeMachineFilter = activeFilter, + isRefreshing = isRefreshing, + hasLoaded = hasLoaded, + isOffline = isOffline, + ) + } + + companion object { + /** `getSessionTitle` (`web/src/lib/sessionTitle.ts`). */ + fun sessionTitle(summary: SessionSummary): String { + val metadata = summary.metadata + metadata?.name?.takeIf { it.isNotEmpty() }?.let { return it } + metadata?.summary?.text?.takeIf { it.isNotEmpty() }?.let { return it } + metadata?.path?.let { path -> + val tail = path.split('/').lastOrNull { it.isNotEmpty() } + if (tail != null) return tail + } + return summary.id.take(8) + } + } +} + +/** `PUT /sessions/:id/pin` modes. */ +enum class PinMode(val wire: String) { + None("none"), + Project("project"), + Global("global"), +} + +sealed interface SessionListError { + val sessionId: String + val message: String? + + data class PinFailed(override val sessionId: String, override val message: String?) : SessionListError + data class ArchiveFailed(override val sessionId: String, override val message: String?) : SessionListError +} 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 new file mode 100644 index 00000000..4b253a1d --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/sessions/SessionListViewModelTest.kt @@ -0,0 +1,301 @@ +package app.hapi.companion.feature.sessions + +import app.hapi.data.sse.SseEngine +import app.hapi.data.sse.SseRawEvent +import app.hapi.data.sse.SseTransport +import app.hapi.data.sse.TransportEvent +import app.hapi.data.store.LastSeenStore +import app.hapi.data.store.MachineListStore +import app.hapi.data.store.SessionListStore +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.MachineMetadata +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SessionSummaryMetadata +import app.hapi.protocol.wire.SummaryText +import app.hapi.protocol.wire.SyncEvent +import app.hapi.protocol.wire.sortSessionSummaries +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest + +// ------------------------------------------------------------------ fakes -- + +private class FakeSessionStore : SessionListStore { + val backing = MutableStateFlow>(emptyList()) + override val sessions: StateFlow> = backing + val calls = MutableStateFlow>(emptyList()) + var failRefresh = false + + fun set(vararg rows: SessionSummary) { + backing.value = sortSessionSummaries(rows.toList()) + } + + private fun record(call: String) { + calls.value = calls.value + call + } + + override suspend fun refresh() { + record("refresh") + if (failRefresh) throw RuntimeException("offline") + } + + override fun scheduleRefresh() = record("scheduleRefresh") + + override suspend fun fullResync() = record("fullResync") + + override fun applySessionEvent(scope: app.hapi.data.sse.SseSubscriptionKey, event: SyncEvent) { + record("event:${event::class.simpleName}") + } + + override suspend fun setPinMode(sessionId: String, mode: String) { + record("pin:$sessionId:$mode") + if (mode == "global") throw RuntimeException("pin exploded") + } + + override suspend fun archiveSession(sessionId: String) = record("archive:$sessionId") +} + +private class FakeMachineStore : MachineListStore { + val backing = MutableStateFlow>(emptyList()) + override val machines: StateFlow> = backing + var refreshes = 0 + + override suspend fun refresh() { + refreshes++ + } + + override fun scheduleRefresh() {} + override fun applyMachineEvent(event: SyncEvent.MachineUpdated) {} +} + +private fun summary( + id: String, + updatedAt: Long = 0, + active: Boolean = false, + machineId: String? = null, + name: String? = null, + summaryText: String? = null, + path: String = "/repo/app", +): SessionSummary = SessionSummary( + id = id, + active = active, + thinking = false, + activeAt = 0, + updatedAt = updatedAt, + metadata = SessionSummaryMetadata( + name = name, + path = path, + machineId = machineId, + summary = summaryText?.let { SummaryText(it) }, + flavor = "claude", + ), + metadataVersion = 0, + agentStateVersion = 0, + todosUpdatedAt = 0, + todoProgress = null, + pendingRequestsCount = 0, + pendingRequestKinds = emptyList(), + pendingRequests = emptyList(), + backgroundTaskCount = 0, + futureScheduledMessageCount = 0, + nextScheduledAt = null, + model = null, + modelReasoningEffort = null, + effort = null, +) + +private fun machine(id: String, host: String, displayName: String? = null): Machine = Machine( + id = id, + namespace = "default", + seq = 1, + createdAt = 1, + updatedAt = 1, + active = true, + activeAt = 1, + metadata = MachineMetadata( + host = host, + platform = "linux", + happyCliVersion = "1.0.0", + displayName = displayName, + ), + metadataVersion = 1, + runnerState = null, + runnerStateVersion = 1, +) + +/** Transport whose only connection sends a handshake with the given verdict, then stays open. */ +private fun handshakeTransport(resume: String): SseTransport = object : SseTransport { + override fun open(url: String, lastEventId: String?) = flow { + emit(TransportEvent.Connected) + emit( + TransportEvent.Event( + SseRawEvent( + id = null, + data = """{"type":"connection-changed","data":{"status":"connected","subscriptionId":"sub-1","resume":"$resume"}}""", + ) + ) + ) + awaitCancellation() + } +} + +private fun TestScope.buildViewModel( + sessions: FakeSessionStore = FakeSessionStore(), + machines: FakeMachineStore = FakeMachineStore(), + transport: SseTransport = handshakeTransport("ok"), +): Triple { + val engine = SseEngine( + baseUrl = "http://hub.test", + transport = transport, + tokenProvider = { "jwt" }, + scope = backgroundScope, + ) + val viewModel = SessionListViewModel( + sessionStore = sessions, + machineStore = machines, + lastSeenStore = LastSeenStore(backgroundScope), + sseEngine = engine, + scope = backgroundScope, + hubKey = "hub-test", + ) + return Triple(viewModel, sessions, machines) +} + +// ------------------------------------------------------------------ tests -- + +class SessionListViewModelTest { + + @Test + fun `uiState maps rows with titles machine labels and unread`() = runTest { + val (viewModel, sessions, machines) = buildViewModel() + machines.backing.value = listOf(machine("m1", host = "devbox.local", displayName = "Devbox")) + sessions.set( + summary("s1", updatedAt = 900, name = "Named session", machineId = "m1", summaryText = "working on it"), + summary("s2", updatedAt = 500, summaryText = "summary title", machineId = "offline-machine-id"), + summary("s3", updatedAt = 100, path = "/repo/tail-name"), + ) + + val state = viewModel.uiState.first { it.rows.size == 3 } + val byId = state.rows.associateBy { it.id } + + // Title cascade: name → summary text → path tail. + assertEquals("Named session", byId.getValue("s1").title) + assertEquals("working on it", byId.getValue("s1").subtitle) + assertEquals("summary title", byId.getValue("s2").title) + // Summary text already used as the title → path becomes the subtitle. + assertEquals("/repo/app", byId.getValue("s2").subtitle) + assertEquals("tail-name", byId.getValue("s3").title) + + // Machine labels: displayName wins; unlisted machines shorten the id. + assertEquals("Devbox", byId.getValue("s1").machineLabel) + assertEquals("offline-", byId.getValue("s2").machineLabel) + assertNull(byId.getValue("s3").machineLabel) + + // No baseline seeded (no successful refresh yet) → activity is unread. + assertTrue(byId.getValue("s1").unread) + } + + @Test + fun `machine filter chips need two machines and filter the rows`() = runTest { + val (viewModel, sessions, _) = buildViewModel() + sessions.set( + summary("s1", updatedAt = 900, machineId = "m1"), + summary("s2", updatedAt = 800, machineId = "m2"), + summary("s3", updatedAt = 700, machineId = "m1"), + ) + + var state = viewModel.uiState.first { it.rows.size == 3 } + assertTrue(state.showMachineFilterBar) + assertEquals(listOf("m1", "m2"), state.machineFilters.map { it.id }) + assertEquals(listOf(2, 1), state.machineFilters.map { it.sessionCount }) + + viewModel.setMachineFilter("m1") + state = viewModel.uiState.first { it.activeMachineFilter == "m1" } + assertEquals(listOf("s1", "s3"), state.rows.map { it.id }) + + // A filter whose machine lost its sessions falls back to All. + sessions.set(summary("s2", updatedAt = 800, machineId = "m2")) + state = viewModel.uiState.first { it.rows.size == 1 } + assertNull(state.activeMachineFilter) + assertEquals(listOf("s2"), state.rows.map { it.id }) + } + + @Test + fun `single machine hides the filter bar and never filters`() = runTest { + val (viewModel, sessions, _) = buildViewModel() + 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) + assertNull(state.activeMachineFilter) + } + + @Test + fun `refresh flips the flags and failure marks offline`() = runTest { + val (viewModel, sessions, machines) = buildViewModel() + viewModel.refresh() + var state = viewModel.uiState.first { it.hasLoaded } + assertFalse(state.isOffline) + assertEquals(1, machines.refreshes) + assertEquals(listOf("refresh"), sessions.calls.value) + + sessions.failRefresh = true + viewModel.refresh() + state = viewModel.uiState.first { it.isOffline } + assertFalse(state.isRefreshing) + } + + @Test + fun `start subscribes globally and a gap handshake full-resyncs the stores`() = runTest { + val (viewModel, sessions, machines) = buildViewModel(transport = handshakeTransport("gap")) + viewModel.start() + // start() also runs the entry refresh; the gap verdict adds fullResync. + sessions.calls.first { "fullResync" in it && "refresh" in it } + assertTrue(machines.refreshes >= 1) + viewModel.stop() + } + + @Test + fun `ok handshake skips the gap resync but the entry refresh still runs`() = runTest { + val (viewModel, sessions, _) = buildViewModel(transport = handshakeTransport("ok")) + viewModel.start() + sessions.calls.first { "refresh" in it } + assertFalse("fullResync" in sessions.calls.value) + viewModel.stop() + } + + @Test + fun `pin failure surfaces on the errors flow`() = runTest { + val (viewModel, sessions, _) = buildViewModel() + sessions.set(summary("s1")) + viewModel.setPinMode("s1", PinMode.Project) + sessions.calls.first { "pin:s1:project" in it } + + var seen: SessionListError? = null + val collector = launch { seen = viewModel.errors.first() } + viewModel.setPinMode("s1", PinMode.Global) // fake throws for global + sessions.calls.first { "pin:s1:global" in it } + collector.join() + assertTrue(seen is SessionListError.PinFailed) + } + + @Test + fun `onSessionOpened stamps the last-seen watermark and clears unread`() = runTest { + val (viewModel, sessions, _) = buildViewModel() + sessions.set(summary("s1", updatedAt = 900)) + assertTrue(viewModel.uiState.first { it.rows.size == 1 }.rows.single().unread) + + viewModel.onSessionOpened("s1") + assertFalse(viewModel.uiState.first { !it.rows.single().unread }.rows.single().unread) + } +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/store/JsonSnapshotStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/JsonSnapshotStore.kt new file mode 100644 index 00000000..febcdd1e --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/JsonSnapshotStore.kt @@ -0,0 +1,102 @@ +package app.hapi.data.store + +import app.hapi.protocol.wire.HapiJson +import java.io.File +import java.io.FileOutputStream +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.Json + +/** + * Generic debounced JSON snapshot: one value ↔ one file. Backs the stores' + * cold-start cache (no database, per the plan) — load synchronously at + * construction, [scheduleWrite] on every state change, and the debounce + * collapses SSE bursts into one atomic write. + * + * Atomicity is write-to-temp + fsync + rename (same guarantee as androidx + * `AtomicFile`, without the Android dependency so JVM tests run as-is). A + * torn/corrupt snapshot degrades to `null` on load — the stores then start + * empty and REST refetch repopulates. + */ +class JsonSnapshotStore( + private val file: File, + private val serializer: KSerializer, + private val scope: CoroutineScope, + private val debounceMs: Long = DEFAULT_DEBOUNCE_MS, + private val json: Json = HapiJson, +) { + private val lock = Any() + private var pending: T? = null + private var writeJob: Job? = null + + /** Synchronous load for cold start; `null` when absent or undecodable. */ + fun load(): T? { + val text = try { + if (!file.isFile) return null + file.readText() + } catch (_: Exception) { + return null + } + return try { + json.decodeFromString(serializer, text) + } catch (_: Exception) { + null + } + } + + /** Records [value] as the latest state and (re)starts the debounce window. */ + fun scheduleWrite(value: T) { + synchronized(lock) { + pending = value + writeJob?.cancel() + writeJob = scope.launch { + delay(debounceMs) + flushPending() + } + } + } + + /** Writes any pending value immediately (app background / tests). */ + suspend fun flush() { + synchronized(lock) { writeJob?.also { writeJob = null } }?.cancel() + flushPending() + } + + private suspend fun flushPending() { + // Cleared only after the write completed — a cancellation between the + // read and the write leaves the value pending for the next flush. + val value = synchronized(lock) { pending } ?: return + withContext(Dispatchers.IO) { + try { + writeAtomically(value) + } catch (_: Exception) { + // A failed snapshot write only costs the next cold start. + } + } + synchronized(lock) { if (pending === value) pending = null } + } + + private fun writeAtomically(value: T) { + file.parentFile?.mkdirs() + val tmp = File(file.parentFile, file.name + ".tmp") + FileOutputStream(tmp).use { out -> + out.write(json.encodeToString(serializer, value).toByteArray(Charsets.UTF_8)) + out.fd.sync() + } + if (!tmp.renameTo(file)) { + // Windows-style rename-over-existing failure; not expected on + // Android/Linux but keep the fallback total. + file.delete() + tmp.renameTo(file) + } + } + + companion object { + const val DEFAULT_DEBOUNCE_MS: Long = 500 + } +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/store/LastSeenStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/LastSeenStore.kt new file mode 100644 index 00000000..3fdeb0be --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/LastSeenStore.kt @@ -0,0 +1,97 @@ +package app.hapi.data.store + +import app.hapi.protocol.wire.SessionSummary +import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.Serializable + +/** Snapshot payload: watermarks + which scopes already got their baseline. */ +@Serializable +data class LastSeenState( + val lastSeen: Map = emptyMap(), + val baselines: Set = emptySet(), +) + +/** + * Per-session last-seen watermarks — port of `web/src/lib/sessionLastSeen.ts` + * (localStorage → per-hub JSON snapshot) plus the unread derivation from + * `web/src/lib/sessionAttention.ts`. + * + * The watermark is the session `updatedAt` the operator last had on screen; + * a session is **unread** when its current `updatedAt` moved past it + * ([isUnread] — the reference compares `updatedAt` only; message `seq` never + * reaches the summary). [initializeBaseline] seeds missing watermarks from + * the first session list so a fresh install does not mark every historical + * session unread — once per [LastSeenState.baselines] scope, exactly like the + * web's per-scope baseline flag. + */ +class LastSeenStore( + scope: CoroutineScope, + snapshotDir: File? = null, +) { + private val snapshot: JsonSnapshotStore? = snapshotDir?.let { dir -> + JsonSnapshotStore( + file = File(dir, "last-seen.json"), + serializer = LastSeenState.serializer(), + scope = scope, + ) + } + + private val _state = MutableStateFlow(snapshot?.load() ?: LastSeenState()) + val state: StateFlow = _state.asStateFlow() + + fun lastSeenAt(sessionId: String): Long = _state.value.lastSeen[sessionId] ?: 0 + + /** Forces the debounced snapshot to disk (app background / tests). */ + suspend fun flushPersistence() { + snapshot?.flush() + } + + /** `markSessionSeen`: monotonic max — a stale screen never rewinds the watermark. */ + fun markSeen(sessionId: String, seenAt: Long) { + if (sessionId.isEmpty()) return + updateState { state -> + val current = state.lastSeen[sessionId] ?: 0 + val next = maxOf(current, seenAt) + if (next == current && state.lastSeen.containsKey(sessionId)) state + else state.copy(lastSeen = state.lastSeen + (sessionId to next)) + } + } + + /** + * `initializeSessionLastSeen`: on the first list load for [scopeKey] + * (e.g. the hub id), seed every session without a watermark at its + * current `updatedAt`, then never again for that scope. + */ + fun initializeBaseline(scopeKey: String, sessions: Iterable) { + updateState { state -> + if (scopeKey in state.baselines) return@updateState state + val seeded = state.lastSeen.toMutableMap() + for (session in sessions) { + seeded.getOrPut(session.id) { session.updatedAt } + } + state.copy(lastSeen = seeded, baselines = state.baselines + scopeKey) + } + } + + private inline fun updateState(transform: (LastSeenState) -> LastSeenState) { + while (true) { + val previous = _state.value + val next = transform(previous) + if (next === previous) return + if (_state.compareAndSet(previous, next)) { + snapshot?.scheduleWrite(next) + return + } + } + } + + companion object { + /** `sessionIsUnread`: activity newer than the operator's watermark. */ + fun isUnread(summary: SessionSummary, lastSeenAt: Long): Boolean = + summary.updatedAt > lastSeenAt + } +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/store/MachineStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/MachineStore.kt new file mode 100644 index 00000000..ff18fb2f --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/MachineStore.kt @@ -0,0 +1,152 @@ +package app.hapi.data.store + +import app.hapi.data.api.HapiApi +import app.hapi.protocol.wire.HapiJson +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.MachinePatches +import app.hapi.protocol.wire.OptionalField +import app.hapi.protocol.wire.SyncEvent +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.JsonNull + +/** Machine-list store surface (production impl [MachineStore]; tests fake it). */ +interface MachineListStore { + /** API order preserved (the reference never re-sorts machines). */ + val machines: StateFlow> + + /** `GET /api/machines`. Throws on failure. */ + suspend fun refresh() + + /** Coalesced fire-and-forget [refresh]. */ + fun scheduleRefresh() + + /** Routes the `machine-updated` SSE event. */ + fun applyMachineEvent(event: SyncEvent.MachineUpdated) +} + +/** + * Online machines for one hub. `machine-updated` handling is the exact web + * decision tree (`web/src/hooks/useSSE.ts` + `sse.md#syncevent-union-13-types`): + * + * 1. full `Machine` → upsert — except `active: false`, which removes; + * 2. explicit `null` data → machine removed; + * 3. strict `MachinePatch` with `active: false` → remove; any other patch + * carries too little to upsert → refetch; + * 4. absent / unparseable data → refetch. + */ +class MachineStore( + private val api: HapiApi, + private val scope: CoroutineScope, + snapshotDir: File? = null, + private val refreshBatchMs: Long = REFRESH_BATCH_MS, +) : MachineListStore { + + private val snapshot: JsonSnapshotStore>? = snapshotDir?.let { dir -> + JsonSnapshotStore( + file = File(dir, "machines.json"), + serializer = ListSerializer(Machine.serializer()), + scope = scope, + ) + } + + private val _machines = MutableStateFlow(snapshot?.load() ?: emptyList()) + override val machines: StateFlow> = _machines.asStateFlow() + + private val refreshMutex = Mutex() + private val refreshQueued = AtomicBoolean(false) + + /** Forces the debounced snapshot to disk (app background / tests). */ + suspend fun flushPersistence() { + snapshot?.flush() + } + + override suspend fun refresh() { + refreshMutex.withLock { + val response = api.getMachines() + updateMachines { response.machines } + } + } + + override fun scheduleRefresh() { + if (!refreshQueued.compareAndSet(false, true)) return + scope.launch { + delay(refreshBatchMs) + refreshQueued.set(false) + try { + refresh() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // Retried by the next event or manual refresh. + } + } + } + + override fun applyMachineEvent(event: SyncEvent.MachineUpdated) { + when (val data = event.data) { + OptionalField.Absent -> scheduleRefresh() + is OptionalField.Present -> { + val element = data.value + val machine = if (element is JsonNull) null else runCatching { + HapiJson.decodeFromJsonElement(Machine.serializer(), element) + }.getOrNull() + when { + machine != null -> upsert(machine) + element is JsonNull -> remove(event.machineId) + else -> { + val patch = MachinePatches.parse(element) + if (patch?.active == false) remove(event.machineId) else scheduleRefresh() + } + } + } + } + } + + /** Web `upsertMachine`: inactive rows are dropped, order preserved. */ + private fun upsert(machine: Machine) { + updateMachines { list -> + val index = list.indexOfFirst { it.id == machine.id } + if (!machine.active) { + if (index >= 0) list.toMutableList().also { it.removeAt(index) } else list + } else { + val next = list.toMutableList() + if (index >= 0) next[index] = machine else next.add(machine) + next + } + } + } + + private fun remove(machineId: String) { + updateMachines { list -> + val next = list.filter { it.id != machineId } + if (next.size == list.size) list else next + } + } + + private fun updateMachines(transform: (List) -> List) { + while (true) { + val previous = _machines.value + val next = transform(previous) + if (next === previous) return + if (_machines.compareAndSet(previous, next)) { + snapshot?.scheduleWrite(next) + return + } + } + } + + private companion object { + const val REFRESH_BATCH_MS: Long = 16 + } +} 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 new file mode 100644 index 00000000..6d58efc7 --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/SessionStore.kt @@ -0,0 +1,345 @@ +package app.hapi.data.store + +import app.hapi.data.api.HapiApi +import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.protocol.patch.applySessionDetailPatch +import app.hapi.protocol.wire.HapiJson +import app.hapi.protocol.wire.Session +import app.hapi.protocol.wire.SessionPatch +import app.hapi.protocol.wire.SessionPatches +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SummaryPatching +import app.hapi.protocol.wire.SyncEvent +import app.hapi.protocol.wire.sortSessionSummaries +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.JsonElement + +/** + * The session-facing store surface the UI layer depends on ([SessionStore] is + * the production implementation; ViewModel tests substitute fakes). + */ +interface SessionListStore { + /** Sorted with `sortSessionSummaries` (globalPinned > pinned > active > pending > recency). */ + val sessions: StateFlow> + + /** `GET /api/sessions` — replaces the list wholesale. Throws on failure. */ + suspend fun refresh() + + /** Coalesced fire-and-forget [refresh] (the web's 16 ms invalidation batch). */ + fun scheduleRefresh() + + /** Handshake-`gap` recovery: list + every cached detail. */ + suspend fun fullResync() + + /** Routes `session-added/updated/removed/ended` into the caches. */ + fun applySessionEvent(scope: SseSubscriptionKey, event: SyncEvent) + + /** `PUT /sessions/:id/pin`, optimistic. [mode] is `none|project|global`. */ + suspend fun setPinMode(sessionId: String, mode: String) + + /** `POST /sessions/:id/archive`, optimistic removal. */ + suspend fun archiveSession(sessionId: String) +} + +/** + * Session list + detail cache for one hub, fed by the global SSE pipe through + * [applySessionEvent] (see `SyncEventRouter`/`StoreSyncTargets`) and by REST + * ([refresh]). Mirrors the web reference's cache handlers in + * `web/src/hooks/useSSE.ts`: + * + * - **Summaries** (the list): full-`Session` payloads upsert via + * `toSessionSummary` (preserving the hub-computed scheduled-message fields + * the projection cannot derive); `SessionPatch` payloads apply through + * [SummaryPatching.applySessionSummaryPatch] — versioned fields gated `>=` + * against the summary's own watermarks — and keep-alive churn is dropped by + * [SummaryPatching.isRenderIrrelevantPatch] before re-sorting. + * - **Details** (per-id [Session]): populated only by [loadSessionDetail] + * (a screen opened the session) or a full-session SSE payload; patches + * apply with the **strict-`>`** versioned gates of + * `applySessionDetailPatch`. Where the web queues a React-Query detail + * invalidation for an uncached session, this store does nothing — an + * uncached detail has no observers, and opening the session fetches fresh. + * - Unparseable/absent `session-updated` data falls back to REST + * (`sse.md#versioned-patch-algorithm` step 3): list refetch + refetch of + * the cached detail, if any. + * + * The summary list persists as a debounced JSON snapshot per hub + * ([snapshotDir]) for instant cold start; details are memory-only (message + * windows own their snapshots in M2c). + */ +class SessionStore( + private val api: HapiApi, + private val scope: CoroutineScope, + snapshotDir: File? = null, + private val refreshBatchMs: Long = REFRESH_BATCH_MS, +) : SessionListStore { + + private val snapshot: JsonSnapshotStore>? = snapshotDir?.let { dir -> + JsonSnapshotStore( + file = File(dir, "sessions.json"), + serializer = ListSerializer(SessionSummary.serializer()), + scope = scope, + ) + } + + private val _sessions = MutableStateFlow(snapshot?.load()?.let(::sortSessionSummaries) ?: emptyList()) + override val sessions: StateFlow> = _sessions.asStateFlow() + + private val _details = MutableStateFlow>(emptyMap()) + + /** All cached details; per-id observation via [sessionDetail]. */ + val details: StateFlow> = _details.asStateFlow() + + private val refreshMutex = Mutex() + private val refreshQueued = AtomicBoolean(false) + + fun sessionDetail(sessionId: String): Flow = + _details.map { it[sessionId] }.distinctUntilChanged() + + fun currentDetail(sessionId: String): Session? = _details.value[sessionId] + + /** `GET /api/sessions/:id` into the detail cache (chat open / resync). */ + suspend fun loadSessionDetail(sessionId: String): Session { + val session = api.getSession(sessionId).session + _details.update { it + (sessionId to session) } + return session + } + + /** Drops a detail nobody observes anymore (chat closed). */ + fun releaseDetail(sessionId: String) { + _details.update { it - sessionId } + } + + /** Forces the debounced snapshot to disk (app background / tests). */ + suspend fun flushPersistence() { + snapshot?.flush() + } + + override suspend fun refresh() { + refreshMutex.withLock { + val response = api.getSessions() + updateSummaries { sortSessionSummaries(response.sessions) } + } + } + + override fun scheduleRefresh() { + if (!refreshQueued.compareAndSet(false, true)) return + scope.launch { + delay(refreshBatchMs) + refreshQueued.set(false) + try { + refresh() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // Offline burst — the next SSE event or manual refresh retries. + } + } + } + + override suspend fun fullResync() { + refresh() + for (sessionId in _details.value.keys.toList()) { + try { + loadSessionDetail(sessionId) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // Keep the stale cached detail; the session pipe re-syncs it. + } + } + } + + override fun applySessionEvent(scope: SseSubscriptionKey, event: SyncEvent) { + when (event) { + is SyncEvent.SessionAdded -> upsertOrPatch(event.sessionId, event.data) + is SyncEvent.SessionUpdated -> upsertOrPatch(event.sessionId, event.data) + is SyncEvent.SessionRemoved -> { + _details.update { it - event.sessionId } + updateSummaries { list -> + val next = list.filter { it.id != event.sessionId } + if (next.size == list.size) list else next + } + } + // The reference has no session-ended cache branch: the state + // change always arrives through the session-updated flow too. + is SyncEvent.SessionEnded -> Unit + else -> Unit + } + } + + override suspend fun setPinMode(sessionId: String, mode: String) { + // Optimistic flip mirroring the hub flag mapping + // (`hub/src/store/sessions.ts setSessionPinMode`): project → pinned, + // global → globalPinned, none → neither. + updateSummaries { list -> + if (list.none { it.id == sessionId }) list + else sortSessionSummaries( + list.map { + if (it.id != sessionId) it + else it.copy(pinned = mode == "project", globalPinned = mode == "global") + } + ) + } + try { + api.setSessionPinMode(sessionId, mode) + } catch (error: Exception) { + // Roll forward to server truth instead of restoring a stale list + // (SSE may have moved other rows since the optimistic write). + scheduleRefresh() + throw error + } + } + + override suspend fun archiveSession(sessionId: String) { + val removed = _sessions.value.firstOrNull { it.id == sessionId } + updateSummaries { list -> list.filter { it.id != sessionId } } + try { + api.archiveSession(sessionId) + } catch (error: Exception) { + if (removed != null) { + updateSummaries { list -> + if (list.any { it.id == sessionId }) list + else sortSessionSummaries(list + removed) + } + } + throw error + } + } + + // ------------------------------------------------------------ internal -- + + private fun upsertOrPatch(sessionId: String, data: JsonElement?) { + // Order matters and mirrors the reference: full-session check first + // (`isSessionRecord && data.id === sessionId`), then the strict patch + // parse, then the REST fallback. + val full = parseFullSession(data)?.takeIf { it.id == sessionId } + if (full != null) { + _details.update { it + (sessionId to full) } + upsertSummary(full) + return + } + val patch = SessionPatches.parse(data) + if (patch != null) { + patchDetail(sessionId, patch) + val summaryPatched = patchSummary(sessionId, patch) + if (!summaryPatched) { + // Row not in the list yet (fresh spawn raced the refetch). + scheduleRefresh() + } + // patch.scratchlistUpdatedAt is a bare refetch trigger for the + // scratchlist query — owned by M4d, nothing to do here. + return + } + // Absent or unparseable payload → REST fallback. + if (_details.value.containsKey(sessionId)) { + scope.launch { + try { + loadSessionDetail(sessionId) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // Stale detail survives until the next successful sync. + } + } + } + scheduleRefresh() + } + + private fun parseFullSession(data: JsonElement?): Session? { + if (data == null) return null + return try { + HapiJson.decodeFromJsonElement(Session.serializer(), data) + } catch (_: Exception) { + null + } + } + + private fun upsertSummary(session: Session) { + updateSummaries { list -> + 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`). + val summary = SummaryPatching.toSessionSummary(session).copy( + futureScheduledMessageCount = existing?.futureScheduledMessageCount ?: 0, + nextScheduledAt = existing?.nextScheduledAt, + ) + val next = list.toMutableList() + if (index >= 0) next[index] = summary else next.add(summary) + sortSessionSummaries(next) + } + } + + /** Detail patch with strict-`>` versioned gates; true when a row was cached. */ + private fun patchDetail(sessionId: String, patch: SessionPatch): Boolean { + var present = false + _details.update { map -> + val current = map[sessionId] ?: return@update map + present = true + // Null result = render-irrelevant → keep the previous identity. + val next = applySessionDetailPatch(current, patch) ?: return@update map + map + (sessionId to next) + } + return present + } + + /** Summary patch (`>=` gates + keep-alive suppression); true when the row exists. */ + private fun patchSummary(sessionId: String, patch: SessionPatch): Boolean { + var present = false + updateSummaries { list -> + val index = list.indexOfFirst { it.id == sessionId } + if (index < 0) return@updateSummaries list + present = true + val current = list[index] + val next = SummaryPatching.applySessionSummaryPatch(current, patch) + // Keep-alive noise: activeAt-only movement keeps the previous + // list identity (no emission, no re-sort, no snapshot write). + if (SummaryPatching.isRenderIrrelevantPatch(current, next)) return@updateSummaries list + sortSessionSummaries(list.toMutableList().also { it[index] = next }) + } + return present + } + + /** CAS update; snapshots only when the transform produced a new list. */ + private fun updateSummaries(transform: (List) -> List) { + while (true) { + val previous = _sessions.value + val next = transform(previous) + if (next === previous) return + if (_sessions.compareAndSet(previous, next)) { + snapshot?.scheduleWrite(next) + return + } + } + } + + private companion object { + /** `INVALIDATION_BATCH_MS` in the web reference. */ + const val REFRESH_BATCH_MS: Long = 16 + } +} + +/** CAS-loop update for [MutableStateFlow] maps (kotlinx's update, minus the inline reified). */ +private inline fun MutableStateFlow>.update(transform: (Map) -> Map) { + while (true) { + val previous = value + val next = transform(previous) + if (next === previous || compareAndSet(previous, next)) return + } +} diff --git a/android/core/data/src/main/kotlin/app/hapi/data/store/StoreSyncTargets.kt b/android/core/data/src/main/kotlin/app/hapi/data/store/StoreSyncTargets.kt new file mode 100644 index 00000000..b271c508 --- /dev/null +++ b/android/core/data/src/main/kotlin/app/hapi/data/store/StoreSyncTargets.kt @@ -0,0 +1,82 @@ +package app.hapi.data.store + +import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.data.sse.SyncTargets +import app.hapi.protocol.wire.SyncEvent +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch + +/** + * Wires `SyncEventRouter` to the stores — the M2b (session list) half of the + * event fan-out, mirroring the global-scope rules of `web/src/hooks/useSSE.ts`: + * + * - session lifecycle events → [SessionListStore.applySessionEvent]; + * - `machine-updated` → [MachineListStore.applyMachineEvent]; + * - global-scope message-stream events refresh the session list where the web + * invalidates it (`messages-invalidated`, `messages-consumed`, + * `message-cancelled`, `scheduled-matured`, and a `message-received` + * carrying `scheduledAt` — they all move the hub-computed scheduled/queued + * fields the client cannot derive); + * - a `gap` handshake verdict triggers the full REST resync. + * + * WIRING(M2c): the message-window bookkeeping the web also performs here + * (`markMessagesConsumed` / `removeOptimisticMessage` / ingest into the open + * window) belongs to the message-window store — extend [onMessageEvent] when + * it lands; the session-list handling below stays as is. + */ +class StoreSyncTargets( + private val sessions: SessionListStore, + private val machines: MachineListStore, + private val scope: CoroutineScope, + private val onToastEvent: (SyncEvent.Toast) -> Unit = {}, +) : SyncTargets { + + override fun onSessionEvent(scope: SseSubscriptionKey, event: SyncEvent) { + sessions.applySessionEvent(scope, event) + } + + override fun onMachineEvent(scope: SseSubscriptionKey, event: SyncEvent.MachineUpdated) { + machines.applyMachineEvent(event) + } + + override fun onMessageEvent(scope: SseSubscriptionKey, event: SyncEvent) { + // Session-scoped message traffic feeds the message window (M2c). + if (scope !is SseSubscriptionKey.Global) return + when (event) { + is SyncEvent.MessagesInvalidated, + is SyncEvent.MessagesConsumed, + is SyncEvent.MessageCancelled, + is SyncEvent.ScheduledMatured, + -> sessions.scheduleRefresh() + + is SyncEvent.MessageReceived -> { + if (event.message.scheduledAt != null) sessions.scheduleRefresh() + } + + else -> Unit + } + } + + override fun onToast(event: SyncEvent.Toast) { + onToastEvent(event) + } + + override fun requestFullResync(scope: SseSubscriptionKey) { + this.scope.launch { + try { + sessions.fullResync() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // Offline: snapshot state stays; the next reconnect retries. + } + try { + machines.refresh() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + } + } + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/JsonSnapshotStoreTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/JsonSnapshotStoreTest.kt new file mode 100644 index 00000000..9f48e8a4 --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/JsonSnapshotStoreTest.kt @@ -0,0 +1,88 @@ +package app.hapi.data.store + +import java.io.File +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer + +class JsonSnapshotStoreTest { + + private fun tempDir(): File = Files.createTempDirectory("snapshot-test").toFile() + + private fun store(file: File, scope: kotlinx.coroutines.CoroutineScope) = JsonSnapshotStore( + file = file, + serializer = ListSerializer(String.serializer()), + scope = scope, + ) + + @Test + fun `load returns null for a missing file`() = runTest { + val file = File(tempDir(), "missing.json") + assertNull(store(file, backgroundScope).load()) + } + + @Test + fun `load returns null for a corrupt file`() = runTest { + val file = File(tempDir(), "corrupt.json") + file.writeText("{ not json") + assertNull(store(file, backgroundScope).load()) + } + + @Test + fun `write round-trips through a fresh store`() = runTest { + val file = File(tempDir(), "data.json") + val writer = store(file, backgroundScope) + writer.scheduleWrite(listOf("a", "b")) + writer.flush() + assertEquals(listOf("a", "b"), store(file, backgroundScope).load()) + } + + @Test + fun `debounce delays the write and keeps only the latest value`() = runTest { + val file = File(tempDir(), "debounced.json") + val writer = store(file, backgroundScope) + + writer.scheduleWrite(listOf("v1")) + advanceTimeBy(400) + assertFalse(file.exists(), "write must wait for the debounce window") + + // A newer value restarts the window and supersedes v1. + writer.scheduleWrite(listOf("v2")) + advanceTimeBy(400) + assertFalse(file.exists()) + + writer.flush() + assertEquals(listOf("v2"), store(file, backgroundScope).load()) + } + + @Test + fun `flush after the debounced write already landed is a no-op`() = runTest { + val file = File(tempDir(), "settled.json") + val writer = store(file, backgroundScope) + writer.scheduleWrite(listOf("v1")) + writer.flush() + assertEquals(listOf("v1"), store(file, backgroundScope).load()) + file.delete() + writer.flush() // nothing pending → must not resurrect the file + assertFalse(file.exists()) + } + + @Test + fun `write replaces previous content atomically (no tmp residue)`() = runTest { + val file = File(tempDir(), "atomic.json") + val writer = store(file, backgroundScope) + writer.scheduleWrite(listOf("first")) + writer.flush() + writer.scheduleWrite(listOf("second")) + writer.flush() + assertEquals(listOf("second"), store(file, backgroundScope).load()) + assertTrue(file.parentFile.listFiles()!!.none { it.name.endsWith(".tmp") }) + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/LastSeenStoreTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/LastSeenStoreTest.kt new file mode 100644 index 00000000..e9a13f88 --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/LastSeenStoreTest.kt @@ -0,0 +1,66 @@ +package app.hapi.data.store + +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest + +class LastSeenStoreTest { + + @Test + fun `markSeen is monotonic max`() = runTest { + val store = LastSeenStore(backgroundScope) + store.markSeen("s1", 1_000) + assertEquals(1_000, store.lastSeenAt("s1")) + store.markSeen("s1", 500) // stale screen must not rewind + assertEquals(1_000, store.lastSeenAt("s1")) + store.markSeen("s1", 2_000) + assertEquals(2_000, store.lastSeenAt("s1")) + assertEquals(0, store.lastSeenAt("unknown")) + } + + @Test + fun `unread compares updatedAt against the watermark`() = runTest { + val row = summary("s1", updatedAt = 1_000) + assertTrue(LastSeenStore.isUnread(row, lastSeenAt = 0)) + assertTrue(LastSeenStore.isUnread(row, lastSeenAt = 999)) + assertFalse(LastSeenStore.isUnread(row, lastSeenAt = 1_000)) + assertFalse(LastSeenStore.isUnread(row, lastSeenAt = 2_000)) + } + + @Test + fun `baseline seeds missing watermarks only once per scope`() = runTest { + val store = LastSeenStore(backgroundScope) + store.markSeen("seen", 50) + store.initializeBaseline( + "hub-a", + listOf(summary("seen", updatedAt = 900), summary("fresh", updatedAt = 700)), + ) + // Existing watermarks are never overwritten; missing ones seed at updatedAt. + assertEquals(50, store.lastSeenAt("seen")) + assertEquals(700, store.lastSeenAt("fresh")) + assertFalse(LastSeenStore.isUnread(summary("fresh", updatedAt = 700), store.lastSeenAt("fresh"))) + + // Second call for the same scope is a no-op — later sessions stay unread. + store.initializeBaseline("hub-a", listOf(summary("later", updatedAt = 999))) + assertEquals(0, store.lastSeenAt("later")) + assertTrue(LastSeenStore.isUnread(summary("later", updatedAt = 999), store.lastSeenAt("later"))) + } + + @Test + fun `state round-trips through the snapshot`() = runTest { + val dir = Files.createTempDirectory("last-seen").toFile() + val store = LastSeenStore(backgroundScope, dir) + store.markSeen("s1", 1_234) + store.initializeBaseline("hub-a", emptyList()) + store.flushPersistence() + + val cold = LastSeenStore(backgroundScope, dir) + assertEquals(1_234, cold.lastSeenAt("s1")) + // Baseline flag persists too — no re-seeding on cold start. + cold.initializeBaseline("hub-a", listOf(summary("s2", updatedAt = 700))) + assertEquals(0, cold.lastSeenAt("s2")) + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/MachineStoreTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/MachineStoreTest.kt new file mode 100644 index 00000000..b8b39d0c --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/MachineStoreTest.kt @@ -0,0 +1,109 @@ +package app.hapi.data.store + +import app.hapi.protocol.wire.HapiJson +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.MachinesResponse +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.encodeToString +import okhttp3.mockwebserver.MockWebServer + +class MachineStoreTest { + + private fun machinesJson(vararg machines: Machine): String = + HapiJson.encodeToString(MachinesResponse(machines.toList())) + + private fun runMachineTest( + block: suspend kotlinx.coroutines.test.TestScope.(MachineStore, MockWebServer) -> Unit, + ) = runTest { + val server = MockWebServer() + server.start() + try { + block(MachineStore(apiFor(server), backgroundScope), server) + } finally { + server.shutdown() + } + } + + @Test + fun `refresh replaces the list in API order`() = runMachineTest { store, server -> + server.enqueueJson(machinesJson(machine("m2"), machine("m1"))) + store.refresh() + assertEquals(listOf("m2", "m1"), store.machines.value.map { it.id }) + } + + @Test + fun `full machine payload upserts in place and appends new ones`() = runMachineTest { store, server -> + server.enqueueJson(machinesJson(machine("m1"), machine("m2"))) + store.refresh() + + store.applyMachineEvent( + machineUpdatedEvent("m1", HapiJson.encodeToString(machine("m1", host = "renamed"))) + ) + assertEquals("renamed", store.machines.value.first().metadata?.host) + assertEquals(listOf("m1", "m2"), store.machines.value.map { it.id }) + + store.applyMachineEvent(machineUpdatedEvent("m3", HapiJson.encodeToString(machine("m3")))) + assertEquals(listOf("m1", "m2", "m3"), store.machines.value.map { it.id }) + } + + @Test + fun `full machine payload with active false removes the row`() = runMachineTest { store, server -> + server.enqueueJson(machinesJson(machine("m1"), machine("m2"))) + store.refresh() + store.applyMachineEvent( + machineUpdatedEvent("m1", HapiJson.encodeToString(machine("m1", active = false))) + ) + assertEquals(listOf("m2"), store.machines.value.map { it.id }) + } + + @Test + fun `null data removes the machine`() = runMachineTest { store, server -> + server.enqueueJson(machinesJson(machine("m1"), machine("m2"))) + store.refresh() + store.applyMachineEvent(machineUpdatedEvent("m1", "null")) + assertEquals(listOf("m2"), store.machines.value.map { it.id }) + } + + @Test + fun `patch with active false removes, other patches refetch`() = runMachineTest { store, server -> + server.enqueueJson(machinesJson(machine("m1"), machine("m2"))) + store.refresh() + + store.applyMachineEvent(machineUpdatedEvent("m1", """{"active":false}""")) + assertEquals(listOf("m2"), store.machines.value.map { it.id }) + + // activeAt-only patch carries too little to upsert → refetch. + server.enqueueJson(machinesJson(machine("m2"), machine("m3"))) + store.applyMachineEvent(machineUpdatedEvent("m2", """{"activeAt":123}""")) + store.machines.first { list -> list.map { it.id } == listOf("m2", "m3") } + } + + @Test + fun `absent data refetches machines`() = runMachineTest { store, server -> + server.enqueueJson(machinesJson(machine("m1"))) + store.applyMachineEvent(machineUpdatedEvent("m1", dataJson = null)) + store.machines.first { list -> list.map { it.id } == listOf("m1") } + } + + @Test + fun `machines round-trip through the snapshot`() = runTest { + val dir = Files.createTempDirectory("machine-store").toFile() + val server = MockWebServer() + server.start() + try { + val store = MachineStore(apiFor(server), backgroundScope, dir) + server.enqueueJson(machinesJson(machine("m1"))) + store.refresh() + store.flushPersistence() + + val cold = MachineStore(apiFor(server), backgroundScope, dir) + assertEquals(listOf("m1"), cold.machines.value.map { it.id }) + } finally { + server.shutdown() + } + } +} 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 new file mode 100644 index 00000000..55af5761 --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/SessionStoreTest.kt @@ -0,0 +1,313 @@ +package app.hapi.data.store + +import app.hapi.data.sse.SseSubscriptionKey +import java.io.File +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest + +class SessionStoreTest { + + private val globalScope = SseSubscriptionKey.Global + + private fun runStoreTest( + snapshotDir: File? = null, + block: suspend kotlinx.coroutines.test.TestScope.(SessionStore, MockWebServer) -> Unit, + ) = runTest { + val server = MockWebServer() + server.start() + try { + val store = SessionStore(apiFor(server), backgroundScope, snapshotDir) + block(store, server) + } finally { + server.shutdown() + } + } + + // ------------------------------------------------------------ refresh -- + + @Test + fun `refresh replaces the list with the sorted server response`() = runStoreTest { store, server -> + server.enqueueJson( + sessionsResponseJson( + summary("old-inactive", updatedAt = 1_000), + summary("pinned", updatedAt = 500, pinned = true), + summary("active", active = true, updatedAt = 100), + ) + ) + store.refresh() + assertEquals(listOf("pinned", "active", "old-inactive"), store.sessions.value.map { it.id }) + } + + @Test + fun `refresh failure throws and keeps previous state`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1"))) + store.refresh() + server.enqueueJson("""{"error":"boom"}""", code = 500) + assertFailsWith { store.refresh() } + assertEquals(listOf("s1"), store.sessions.value.map { it.id }) + } + + // ----------------------------------------------------- event: full session -- + + @Test + fun `full-session event replaces the detail and upserts the summary`() = runStoreTest { store, server -> + server.enqueueJson( + sessionsResponseJson( + summary("s1", updatedAt = 100, futureScheduledMessageCount = 2, nextScheduledAt = 999) + ) + ) + store.refresh() + + val full = session("s1", updatedAt = 5_000, agentStateVersion = 9) + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(full))) + + assertEquals(full, store.currentDetail("s1")) + val row = store.sessions.value.single() + assertEquals(5_000, row.updatedAt) + assertEquals(9, row.agentStateVersion) + // Hub-computed fields the projection cannot derive are preserved. + assertEquals(2, row.futureScheduledMessageCount) + assertEquals(999L, row.nextScheduledAt) + } + + @Test + fun `full-session event with mismatched id falls back to list refetch`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 100))) + store.refresh() + // The refetch triggered by the mismatching payload: + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 100), summary("s2", updatedAt = 50))) + + store.applySessionEvent( + globalScope, + sessionUpdatedEvent("s2", fullSessionJson(session("other-id"))), + ) + assertNull(store.currentDetail("s2")) + // runTest's real-time timeout guards the await (virtual withTimeout + // would race the real network round-trip). + store.sessions.first { list -> list.any { it.id == "s2" } } + } + + // ----------------------------------------------------------- event: patch -- + + @Test + fun `stale versioned patch leaves detail and summary untouched`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 100, agentStateVersion = 5))) + store.refresh() + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(session("s1", agentStateVersion = 5)))) + + val before = store.sessions.value + store.applySessionEvent( + globalScope, + sessionUpdatedEvent( + "s1", + """{"agentState":{"version":4,"value":{"requests":{"r1":{"tool":"Bash"}}}}}""", + ), + ) + assertEquals(5, store.currentDetail("s1")?.agentStateVersion) + assertNull(store.currentDetail("s1")?.agentState) + assertEquals(0, store.sessions.value.single().pendingRequestsCount) + assertSame(before, store.sessions.value, "stale patch must keep the list identity") + } + + @Test + fun `equal-version patch applies to the summary but not the detail`() = runStoreTest { store, server -> + // The replicated web divergence: summary path >= vs detail path >. + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 100, agentStateVersion = 5))) + store.refresh() + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(session("s1", agentStateVersion = 5)))) + + store.applySessionEvent( + globalScope, + sessionUpdatedEvent( + "s1", + """{"agentState":{"version":5,"value":{"requests":{"r1":{"tool":"Bash"}}}}}""", + ), + ) + assertNull(store.currentDetail("s1")?.agentState, "detail gates strictly greater") + val row = store.sessions.value.single() + assertEquals(1, row.pendingRequestsCount) + assertEquals(listOf("permission"), row.pendingRequestKinds) + } + + @Test + fun `newer versioned patch applies to both caches and re-sorts`() = runStoreTest { store, server -> + server.enqueueJson( + sessionsResponseJson( + summary("s1", active = true, updatedAt = 100, agentStateVersion = 5), + summary("s2", active = true, updatedAt = 200), + ) + ) + store.refresh() + assertEquals(listOf("s2", "s1"), store.sessions.value.map { it.id }) + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(session("s1", agentStateVersion = 5)))) + + store.applySessionEvent( + globalScope, + sessionUpdatedEvent( + "s1", + """{"updatedAt":300,"agentState":{"version":6,"value":{"requests":{"r1":{"tool":"Bash"}}}}}""", + ), + ) + val detail = store.currentDetail("s1") + assertEquals(6, detail?.agentStateVersion) + assertEquals("Bash", detail?.agentState?.requests?.get("r1")?.tool) + // Pending requests push the active session ahead of the newer one. + assertEquals(listOf("s1", "s2"), store.sessions.value.map { it.id }) + assertEquals(1, store.sessions.value.first().pendingRequestsCount) + } + + @Test + fun `keep-alive activeAt-only patch keeps the list identity`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", active = true, updatedAt = 100, activeAt = 1_000))) + store.refresh() + val before = store.sessions.value + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", """{"active":true,"activeAt":11000}""")) + assertSame(before, store.sessions.value) + } + + @Test + fun `patch for an unlisted session falls back to a list refetch`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("brand-new", updatedAt = 10))) + store.applySessionEvent(globalScope, sessionUpdatedEvent("brand-new", """{"updatedAt":10}""")) + store.sessions.first { list -> list.any { it.id == "brand-new" } } + } + + @Test + fun `unparseable data refetches list and cached detail`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 100))) + store.refresh() + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(session("s1", updatedAt = 100)))) + + // Detail + list refetch run concurrently — route by path, not FIFO. + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val body = when { + request.path!!.startsWith("/api/sessions/s1") -> + """{"session":${fullSessionJson(session("s1", updatedAt = 900))}}""" + request.path!!.startsWith("/api/sessions") -> + sessionsResponseJson(summary("s1", updatedAt = 900)) + else -> return MockResponse().setResponseCode(404) + } + return MockResponse().setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(body) + } + } + + // `data` present but neither a Session nor a strict patch. + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", """{"unknownKey":1}""")) + store.sessions.first { list -> list.any { it.updatedAt == 900L } } + store.sessionDetail("s1").first { it?.updatedAt == 900L } + } + + // ------------------------------------------------------ event: removal -- + + @Test + fun `session-removed drops the row and the detail`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1"), summary("s2"))) + store.refresh() + store.applySessionEvent(globalScope, sessionUpdatedEvent("s1", fullSessionJson(session("s1")))) + + store.applySessionEvent(globalScope, sessionRemovedEvent("s1")) + assertEquals(listOf("s2"), store.sessions.value.map { it.id }) + assertNull(store.currentDetail("s1")) + } + + @Test + fun `session-added with a full session inserts a new row`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 500))) + store.refresh() + store.applySessionEvent(globalScope, sessionAddedEvent("s2", fullSessionJson(session("s2", updatedAt = 900)))) + assertEquals(listOf("s2", "s1"), store.sessions.value.map { it.id }) + } + + // --------------------------------------------------------- pin/archive -- + + @Test + fun `setPinMode flips flags optimistically and re-sorts`() = runStoreTest { store, server -> + server.enqueueJson( + sessionsResponseJson( + summary("s1", updatedAt = 900), + summary("s2", updatedAt = 100), + ) + ) + store.refresh() + server.enqueueJson("""{"ok":true}""") // PUT pin + store.setPinMode("s2", "project") + assertEquals(listOf("s2", "s1"), store.sessions.value.map { it.id }) + assertEquals(true, store.sessions.value.first().pinned) + assertEquals(false, store.sessions.value.first().globalPinned) + + server.enqueueJson("""{"ok":true}""") + store.setPinMode("s2", "global") + assertEquals(false, store.sessions.value.first().pinned) + assertEquals(true, store.sessions.value.first().globalPinned) + + server.enqueueJson("""{"ok":true}""") + store.setPinMode("s2", "none") + assertEquals(listOf("s1", "s2"), store.sessions.value.map { it.id }) + } + + @Test + fun `setPinMode failure rolls forward to server truth`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 900), summary("s2", updatedAt = 100))) + store.refresh() + server.enqueueJson("""{"error":"boom"}""", code = 500) // PUT pin fails + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 900), summary("s2", updatedAt = 100))) + + assertFailsWith { store.setPinMode("s2", "project") } + store.sessions.first { list -> list.map { it.id } == listOf("s1", "s2") && list.none { it.pinned == true } } + } + + @Test + fun `archive removes optimistically and restores on failure`() = runStoreTest { store, server -> + server.enqueueJson(sessionsResponseJson(summary("s1", updatedAt = 900), summary("s2", updatedAt = 100))) + store.refresh() + + server.enqueueJson("""{"ok":true}""") + store.archiveSession("s2") + assertEquals(listOf("s1"), store.sessions.value.map { it.id }) + + server.enqueueJson("""{"error":"session_inactive"}""", code = 409) + assertFailsWith { store.archiveSession("s1") } + assertEquals(listOf("s1"), store.sessions.value.map { it.id }, "failed archive restores the row") + } + + // ------------------------------------------------------------ snapshot -- + + @Test + fun `summaries round-trip through the snapshot into a cold store`() = runTest { + val dir = Files.createTempDirectory("session-store").toFile() + val server = MockWebServer() + server.start() + try { + val store = SessionStore(apiFor(server), backgroundScope, dir) + server.enqueueJson( + sessionsResponseJson( + summary("pinned", updatedAt = 100, pinned = true), + summary("recent", updatedAt = 900), + ) + ) + store.refresh() + store.flushPersistence() + + val cold = SessionStore(apiFor(server), backgroundScope, dir) + assertEquals(listOf("pinned", "recent"), cold.sessions.value.map { it.id }) + assertTrue(cold.sessions.value.first().pinned == true) + assertTrue(File(dir, "sessions.json").isFile) + } finally { + server.shutdown() + } + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/StoreSyncTargetsTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/StoreSyncTargetsTest.kt new file mode 100644 index 00000000..a1b203b0 --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/StoreSyncTargetsTest.kt @@ -0,0 +1,164 @@ +package app.hapi.data.store + +import app.hapi.data.sse.EngineEvent +import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.data.sse.SyncEventRouter +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SyncEvent +import app.hapi.protocol.wire.SyncEvents +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest + +class FakeSessionListStore : SessionListStore { + override val sessions: StateFlow> = MutableStateFlow(emptyList()) + val calls = mutableListOf() + + override suspend fun refresh() { + calls += "refresh" + } + + override fun scheduleRefresh() { + calls += "scheduleRefresh" + } + + override suspend fun fullResync() { + calls += "fullResync" + } + + override fun applySessionEvent(scope: SseSubscriptionKey, event: SyncEvent) { + calls += "session:${event::class.simpleName}" + } + + override suspend fun setPinMode(sessionId: String, mode: String) { + calls += "pin:$sessionId:$mode" + } + + override suspend fun archiveSession(sessionId: String) { + calls += "archive:$sessionId" + } +} + +class FakeMachineListStore : MachineListStore { + override val machines: StateFlow> = MutableStateFlow(emptyList()) + val calls = mutableListOf() + + override suspend fun refresh() { + calls += "refresh" + } + + override fun scheduleRefresh() { + calls += "scheduleRefresh" + } + + override fun applyMachineEvent(event: SyncEvent.MachineUpdated) { + calls += "machine:${event.machineId}" + } +} + +/** Routing rules of the M2b `SyncTargets` implementation, with fake stores. */ +class StoreSyncTargetsTest { + + private val global = SseSubscriptionKey.Global + private val sessionScope = SseSubscriptionKey.Session("s1") + + private fun sync(json: String): EngineEvent.Sync = EngineEvent.Sync(SyncEvents.parse(json)) + + @Test + fun `session lifecycle events reach the session store`() = runTest { + val sessions = FakeSessionListStore() + val router = SyncEventRouter(StoreSyncTargets(sessions, FakeMachineListStore(), backgroundScope)) + router.route(global, sync("""{"type":"session-updated","sessionId":"s1","data":{"active":true}}""")) + router.route(global, sync("""{"type":"session-removed","sessionId":"s1"}""")) + router.route(global, sync("""{"type":"session-ended","sessionId":"s1","reason":"completed"}""")) + assertEquals( + listOf("session:SessionUpdated", "session:SessionRemoved", "session:SessionEnded"), + sessions.calls, + ) + } + + @Test + fun `machine-updated reaches the machine store`() = runTest { + val machines = FakeMachineListStore() + val router = SyncEventRouter(StoreSyncTargets(FakeSessionListStore(), machines, backgroundScope)) + router.route(global, sync("""{"type":"machine-updated","machineId":"m1","data":null}""")) + assertEquals(listOf("machine:m1"), machines.calls) + } + + @Test + fun `global message-stream events refresh the session list`() = runTest { + val sessions = FakeSessionListStore() + val router = SyncEventRouter(StoreSyncTargets(sessions, FakeMachineListStore(), backgroundScope)) + router.route(global, sync("""{"type":"messages-invalidated","sessionId":"s1"}""")) + router.route(global, sync("""{"type":"messages-consumed","sessionId":"s1","localIds":["l1"],"invokedAt":1}""")) + router.route(global, sync("""{"type":"message-cancelled","sessionId":"s1","messageId":"m1"}""")) + router.route(global, sync("""{"type":"scheduled-matured","sessionId":"s1"}""")) + assertEquals(List(4) { "scheduleRefresh" }, sessions.calls) + } + + @Test + fun `message-received refreshes the list only when scheduled`() = runTest { + val sessions = FakeSessionListStore() + val router = SyncEventRouter(StoreSyncTargets(sessions, FakeMachineListStore(), backgroundScope)) + router.route( + global, + sync("""{"type":"message-received","sessionId":"s1","message":{"id":"m1","createdAt":1}}"""), + ) + assertEquals(emptyList(), sessions.calls) + router.route( + global, + sync("""{"type":"message-received","sessionId":"s1","message":{"id":"m2","createdAt":1,"scheduledAt":99}}"""), + ) + assertEquals(listOf("scheduleRefresh"), sessions.calls) + } + + @Test + fun `session-scoped message events do not touch the list (window territory)`() = runTest { + val sessions = FakeSessionListStore() + val router = SyncEventRouter(StoreSyncTargets(sessions, FakeMachineListStore(), backgroundScope)) + router.route(sessionScope, sync("""{"type":"messages-invalidated","sessionId":"s1"}""")) + assertEquals(emptyList(), sessions.calls) + } + + @Test + fun `gap handshake triggers the full resync`() = runTest { + val sessions = FakeSessionListStore() + val machines = FakeMachineListStore() + // The launched resync must run on a foreground test scope — + // advanceUntilIdle does not execute background-scope-only tasks. + val router = SyncEventRouter(StoreSyncTargets(sessions, machines, this)) + router.route(global, EngineEvent.Handshake(subscriptionId = "sub-1", resume = EngineEvent.Resume.Gap)) + advanceUntilIdle() + assertEquals(listOf("fullResync"), sessions.calls) + assertEquals(listOf("refresh"), machines.calls) + } + + @Test + fun `ok handshake skips the resync`() = runTest { + val sessions = FakeSessionListStore() + val machines = FakeMachineListStore() + val router = SyncEventRouter(StoreSyncTargets(sessions, machines, this)) + router.route(global, EngineEvent.Handshake(subscriptionId = "sub-1", resume = EngineEvent.Resume.Ok)) + advanceUntilIdle() + assertEquals(emptyList(), sessions.calls) + assertEquals(emptyList(), machines.calls) + } + + @Test + fun `toast events reach the callback`() = runTest { + val toasts = mutableListOf() + val router = SyncEventRouter( + StoreSyncTargets(FakeSessionListStore(), FakeMachineListStore(), backgroundScope) { toasts += it } + ) + router.route( + global, + sync("""{"type":"toast","data":{"title":"t","body":"b","sessionId":"s1","url":"/sessions/s1"}}"""), + ) + assertEquals(1, toasts.size) + assertEquals("t", toasts.single().data.title) + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/store/StoreTestFixtures.kt b/android/core/data/src/test/kotlin/app/hapi/data/store/StoreTestFixtures.kt new file mode 100644 index 00000000..c65dc53d --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/store/StoreTestFixtures.kt @@ -0,0 +1,127 @@ +package app.hapi.data.store + +import app.hapi.data.api.HapiApi +import app.hapi.protocol.wire.HapiJson +import app.hapi.protocol.wire.Machine +import app.hapi.protocol.wire.MachineMetadata +import app.hapi.protocol.wire.Session +import app.hapi.protocol.wire.SessionSummary +import app.hapi.protocol.wire.SessionsResponse +import app.hapi.protocol.wire.SyncEvent +import app.hapi.protocol.wire.SyncEvents +import kotlinx.serialization.encodeToString +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer + +fun summary( + id: String, + active: Boolean = false, + updatedAt: Long = 0, + activeAt: Long = 0, + pinned: Boolean? = null, + globalPinned: Boolean? = null, + pendingRequestsCount: Int = 0, + metadataVersion: Long = 0, + agentStateVersion: Long = 0, + todosUpdatedAt: Long = 0, + futureScheduledMessageCount: Int = 0, + nextScheduledAt: Long? = null, +): SessionSummary = SessionSummary( + id = id, + active = active, + thinking = false, + activeAt = activeAt, + updatedAt = updatedAt, + pinned = pinned, + globalPinned = globalPinned, + metadata = null, + metadataVersion = metadataVersion, + agentStateVersion = agentStateVersion, + todosUpdatedAt = todosUpdatedAt, + todoProgress = null, + pendingRequestsCount = pendingRequestsCount, + pendingRequestKinds = emptyList(), + pendingRequests = emptyList(), + backgroundTaskCount = 0, + futureScheduledMessageCount = futureScheduledMessageCount, + nextScheduledAt = nextScheduledAt, + model = null, + modelReasoningEffort = null, + effort = null, +) + +fun session( + id: String, + updatedAt: Long = 0, + active: Boolean = true, + metadataVersion: Long = 1, + agentStateVersion: Long = 1, + todosUpdatedAt: Long? = 0, +): Session = Session( + id = id, + namespace = "default", + seq = 1, + createdAt = 1, + updatedAt = updatedAt, + active = active, + activeAt = 0, + metadata = null, + metadataVersion = metadataVersion, + agentState = null, + agentStateVersion = agentStateVersion, + thinking = false, + thinkingAt = 0, + todosUpdatedAt = todosUpdatedAt, +) + +fun machine(id: String, active: Boolean = true, host: String = "$id-host"): Machine = Machine( + id = id, + namespace = "default", + seq = 1, + createdAt = 1, + updatedAt = 1, + active = active, + activeAt = 1, + metadata = MachineMetadata(host = host, platform = "linux", happyCliVersion = "1.0.0"), + metadataVersion = 1, + runnerState = null, + runnerStateVersion = 1, +) + +/** Builds a decoded `session-updated` event whose `data` is raw JSON text. */ +fun sessionUpdatedEvent(sessionId: String, dataJson: String?): SyncEvent { + val data = dataJson?.let { ""","data":$it""" } ?: "" + return SyncEvents.parse("""{"type":"session-updated","sessionId":"$sessionId"$data}""") +} + +fun sessionAddedEvent(sessionId: String, dataJson: String?): SyncEvent { + val data = dataJson?.let { ""","data":$it""" } ?: "" + return SyncEvents.parse("""{"type":"session-added","sessionId":"$sessionId"$data}""") +} + +fun sessionRemovedEvent(sessionId: String): SyncEvent = + SyncEvents.parse("""{"type":"session-removed","sessionId":"$sessionId"}""") + +fun machineUpdatedEvent(machineId: String, dataJson: String?): SyncEvent.MachineUpdated { + val data = dataJson?.let { ""","data":$it""" } ?: "" + return SyncEvents.parse("""{"type":"machine-updated","machineId":"$machineId"$data}""") + as SyncEvent.MachineUpdated +} + +fun fullSessionJson(session: Session): String = HapiJson.encodeToString(session) + +fun sessionsResponseJson(vararg sessions: SessionSummary): String = + HapiJson.encodeToString(SessionsResponse(sessions.toList())) + +fun MockWebServer.enqueueJson(body: String, code: Int = 200) { + enqueue( + MockResponse() + .setResponseCode(code) + .setHeader("Content-Type", "application/json") + .setBody(body) + ) +} + +fun apiFor(server: MockWebServer): HapiApi = + HapiApi(server.url("/").toString(), OkHttpClient()) diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionMetadata.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionMetadata.kt index 451cd2b0..3aa787c9 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionMetadata.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionMetadata.kt @@ -32,6 +32,19 @@ data class SessionMetadata( val hapiMcpUrl: String? = null, val slashCommands: List? = null, val tools: List? = null, + // Per-flavor agent session ids (`MetadataSchema`) — the resume handle for + // each CLI. Needed by the `SessionSummary.agentSessionId` projection + // (`getSummaryAgentSessionId`, `shared/src/sessionSummary.ts`). + val claudeSessionId: String? = null, + val codexSessionId: String? = null, + val geminiSessionId: String? = null, + val opencodeSessionId: String? = null, + val grokSessionId: String? = null, + val agySessionId: String? = null, + val cursorSessionId: String? = null, + val kimiSessionId: String? = null, + val copilotSessionId: String? = null, + val piSessionId: String? = null, ) /** `metadata.summary` on the detail session (`{text, updatedAt}`). */ 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 new file mode 100644 index 00000000..47ad56fc --- /dev/null +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SessionSorting.kt @@ -0,0 +1,41 @@ +package app.hapi.protocol.wire + +/** + * The session-list order — exact port of `sortSessionSummaries` + * (`web/src/hooks/useSSE.ts`; also stated in + * `docs/api/client-contract/sse.md#keep-alive-noise`): + * + * 1. `globalPinned` first (null-safe: absent counts as false); + * 2. then `pinned`; + * 3. then `active`; + * 4. among sessions with equal `active` **when both are active**: + * `pendingRequestsCount` descending (the reference's + * `left.active && …` guard — inactive ties skip straight to recency); + * 5. finally `updatedAt` descending. + * + * Ties keep their prior relative order: JS `Array.prototype.sort` and + * Kotlin's `sortedWith` are both stable. + */ +val SessionSummaryComparator: Comparator = Comparator { left, right -> + val leftGlobal = left.globalPinned == true + val rightGlobal = right.globalPinned == true + if (leftGlobal != rightGlobal) { + return@Comparator if (leftGlobal) -1 else 1 + } + val leftPinned = left.pinned == true + val rightPinned = right.pinned == true + if (leftPinned != rightPinned) { + return@Comparator if (leftPinned) -1 else 1 + } + if (left.active != right.active) { + return@Comparator if (left.active) -1 else 1 + } + if (left.active && left.pendingRequestsCount != right.pendingRequestsCount) { + return@Comparator right.pendingRequestsCount - left.pendingRequestsCount + } + right.updatedAt.compareTo(left.updatedAt) +} + +/** Stable sort of a whole list with [SessionSummaryComparator]. */ +fun sortSessionSummaries(sessions: List): List = + sessions.sortedWith(SessionSummaryComparator) 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 new file mode 100644 index 00000000..f9e90cde --- /dev/null +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/SummaryPatching.kt @@ -0,0 +1,351 @@ +package app.hapi.protocol.wire + +import app.hapi.protocol.catalog.AgentFlavor +import kotlin.math.max + +/** + * Summary-side patch path — faithful port of the web reference: + * derivations from `shared/src/sessionSummary.ts` (`computePendingRequests*`, + * `computeTodoProgress`, `toSessionSummary`) and the list-cache patch rules + * from `web/src/hooks/useSSE.ts` (`patchSessionSummary`, + * `isRenderIrrelevantPatch`, `sameSessionSummaryMetadata`, + * `canApplyVersionedSummaryPatch`). + * + * ## `>=` vs the detail path's strict `>` (deliberate, replicated divergence) + * + * The detail path (`app.hapi.protocol.patch.applySessionDetailPatch`) gates + * versioned sub-patches with **strictly greater** versions. The web summary + * path — replicated here — accepts **greater-or-equal**: re-deriving the + * summary fields (`todoProgress`, `pendingRequests*`, projected metadata) + * from an equal-version `value` is idempotent, because the summary stores only + * derivations of the value, never the value itself. Applying the same version + * twice recomputes the same numbers; the strict gate matters only where the + * raw value is cached (a stale equal-version `agentState` replayed into the + * *detail* cache could resurrect resolved permission requests). + * `docs/api/client-contract/sse.md#versioned-patch-algorithm` documents both. + */ +object SummaryPatching { + + /** + * Cap on `pendingRequests` carried in `SessionSummary` + * (`PENDING_REQUEST_SUMMARY_CAP`). `pendingRequestsCount` stays the + * authoritative total; the capped slice is per-row hover/badge copy. + */ + const val PENDING_REQUEST_SUMMARY_CAP: Int = 5 + + const val KIND_PERMISSION: String = "permission" + const val KIND_INPUT: String = "input" + + /** `INPUT_REQUEST_TOOLS` — tools that ask the operator, not for permission. */ + private val INPUT_REQUEST_TOOLS = setOf( + "AskUserQuestion", + "ask_user_question", + "ExitPlanMode", + "exit_plan_mode", + "request_user_input", + ) + + private fun classifyKind(tool: String): String = + if (tool in INPUT_REQUEST_TOOLS) KIND_INPUT else KIND_PERMISSION + + // ------------------------------------------------------- derivations -- + + /** + * `computePendingRequestKinds`: deduplicated kinds; when both are present + * the canonical order is `[permission, input]`, otherwise insertion order + * (which for a single kind is just that kind). + */ + fun computePendingRequestKinds(agentState: AgentState?): List { + val requests = agentState?.requests ?: return emptyList() + val kinds = LinkedHashSet() + for (request in requests.values) { + kinds.add(classifyKind(request.tool)) + } + return if (KIND_PERMISSION in kinds && KIND_INPUT in kinds) { + listOf(KIND_PERMISSION, KIND_INPUT) + } else { + kinds.toList() + } + } + + /** + * `computePendingRequests`: oldest-first (by `since`, then id) capped + * slice. [fallbackSince] (typically the session's `updatedAt`) substitutes + * for requests stored without `createdAt`. + */ + fun computePendingRequests( + agentState: AgentState?, + fallbackSince: Long, + cap: Int = PENDING_REQUEST_SUMMARY_CAP, + ): List { + val requests = agentState?.requests ?: return emptyList() + val items = requests.map { (id, request) -> + PendingRequest( + id = id, + kind = classifyKind(request.tool), + tool = request.tool, + since = request.createdAt ?: fallbackSince, + ) + }.sortedWith(compareBy({ it.since }, { it.id })) + return if (cap >= items.size) items else items.take(max(0, cap)) + } + + /** `computePendingRequestsCount` — the authoritative (uncapped) total. */ + fun computePendingRequestsCount(agentState: AgentState?): Int = + agentState?.requests?.size ?: 0 + + /** `computeTodoProgress`: null for absent/empty todos. */ + fun computeTodoProgress(todos: List?): TodoProgress? { + if (todos.isNullOrEmpty()) return null + return TodoProgress( + completed = todos.count { it.status == "completed" }, + total = todos.size, + ) + } + + /** + * `getSummaryAgentSessionId`: with a known flavor, only that flavor's id + * field counts (trimmed, blank ⇒ null). The legacy fallback chain (raw, + * untrimmed, `pi` excluded — replicated) applies only when the flavor is + * missing or unknown. + */ + private fun summaryAgentSessionId(metadata: SessionMetadata): String? { + val flavor = metadata.flavor + if (AgentFlavor.isKnown(flavor)) { + val flavorSessionId = when (flavor) { + "claude" -> metadata.claudeSessionId + "codex" -> metadata.codexSessionId + "gemini" -> metadata.geminiSessionId + "opencode" -> metadata.opencodeSessionId + "grok" -> metadata.grokSessionId + "agy" -> metadata.agySessionId + "cursor" -> metadata.cursorSessionId + "kimi" -> metadata.kimiSessionId + "copilot" -> metadata.copilotSessionId + "pi" -> metadata.piSessionId + else -> null + } + return flavorSessionId?.trim()?.takeIf { it.isNotEmpty() } + } + return metadata.codexSessionId + ?: metadata.claudeSessionId + ?: metadata.geminiSessionId + ?: metadata.opencodeSessionId + ?: metadata.grokSessionId + ?: metadata.agySessionId + ?: metadata.cursorSessionId + ?: metadata.kimiSessionId + ?: metadata.copilotSessionId + } + + /** `toSessionSummaryMetadata` — list-sized projection of full metadata. */ + fun toSessionSummaryMetadata(metadata: SessionMetadata?): SessionSummaryMetadata? { + if (metadata == null) return null + return SessionSummaryMetadata( + name = metadata.name, + path = metadata.path, + machineId = metadata.machineId, + summary = metadata.summary?.let { SummaryText(it.text) }, + flavor = metadata.flavor, + worktree = metadata.worktree, + agentSessionId = summaryAgentSessionId(metadata), + lifecycleState = metadata.lifecycleState, + hapiMcpUrl = metadata.hapiMcpUrl, + ) + } + + /** + * `toSessionSummary`: project a full [Session] (SSE full-session payload) + * into a list row. `futureScheduledMessageCount`/`nextScheduledAt` are + * hub-computed from the message table and NOT derivable from a `Session` — + * they project to 0/null; the caller preserves the previous row's values + * (`upsertSessionSummary` in the web reference does exactly that). + */ + fun toSessionSummary(session: Session): SessionSummary = SessionSummary( + id = session.id, + active = session.active, + thinking = session.thinking, + activeAt = session.activeAt, + updatedAt = session.updatedAt, + pinned = session.pinned ?: false, + globalPinned = session.globalPinned ?: false, + metadata = toSessionSummaryMetadata(session.metadata), + metadataVersion = session.metadataVersion, + agentStateVersion = session.agentStateVersion, + todosUpdatedAt = session.todosUpdatedAt ?: 0, + todoProgress = computeTodoProgress(session.todos), + pendingRequestsCount = computePendingRequestsCount(session.agentState), + pendingRequestKinds = computePendingRequestKinds(session.agentState), + pendingRequests = computePendingRequests(session.agentState, session.updatedAt), + backgroundTaskCount = session.backgroundTaskCount ?: 0, + futureScheduledMessageCount = 0, + nextScheduledAt = null, + model = session.model, + modelReasoningEffort = session.modelReasoningEffort, + effort = session.effort, + ) + + // ------------------------------------------------------- patch rules -- + + /** + * Apply a [SessionPatch] to a list row — the pure core of the web's + * `patchSessionSummary`. Always returns the patched summary; the caller + * decides whether to keep the old object via [isRenderIrrelevantPatch] + * (the keep-alive suppression) and re-sorts. + * + * - Flat fields: last-write-wins when present; a present-`null` + * `model`/`modelReasoningEffort`/`effort` clears. (The web's + * `patch.backgroundTaskCount ?? 0` fallback guards a present-`undefined` + * that the strict wire schema cannot produce; absent ⇒ keep.) + * - `updatedAt`: max-monotonic — stale versioned-patch replays must not + * move the list clock backward. + * - Versioned fields gate against THIS summary's watermarks with `>=` + * (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. + * - `teamState` is a summary no-op (not rendered on the list). + * - `activeTurnStartedAt` / `scratchlistUpdatedAt` / `serviceTier` / + * `permissionMode` / `collaborationMode` / `copilotAgentMode` have no + * summary counterpart — ignored, like the reference. + */ + fun applySessionSummaryPatch(current: SessionSummary, patch: SessionPatch): SessionSummary { + var next = current.copy( + active = patch.active ?: current.active, + thinking = patch.thinking ?: current.thinking, + activeAt = patch.activeAt ?: current.activeAt, + updatedAt = patch.updatedAt?.let { max(current.updatedAt, it) } ?: current.updatedAt, + backgroundTaskCount = patch.backgroundTaskCount ?: current.backgroundTaskCount, + model = when (val model = patch.model) { + is OptionalField.Present -> model.value + OptionalField.Absent -> current.model + }, + modelReasoningEffort = when (val value = patch.modelReasoningEffort) { + is OptionalField.Present -> value.value + OptionalField.Absent -> current.modelReasoningEffort + }, + effort = when (val effort = patch.effort) { + is OptionalField.Present -> effort.value + OptionalField.Absent -> current.effort + }, + ) + + // Gate versioned fields against THIS summary's watermarks — not the + // detail cache (global SSE covers every session; requiring detail + // would force O(N) list refetches). Compared against `current`, like + // the reference (`next` carries the same watermark values anyway). + patch.todos?.let { todos -> + if (todos.version >= current.todosUpdatedAt) { + next = next.copy( + todoProgress = computeTodoProgress(todos.value), + todosUpdatedAt = todos.version, + ) + } + } + patch.agentState?.let { agentState -> + if (agentState.version >= current.agentStateVersion) { + next = next.copy( + pendingRequestsCount = computePendingRequestsCount(agentState.value), + pendingRequestKinds = computePendingRequestKinds(agentState.value), + pendingRequests = computePendingRequests(agentState.value, next.updatedAt), + agentStateVersion = agentState.version, + ) + } + } + patch.metadata?.let { metadata -> + if (metadata.version >= current.metadataVersion) { + next = next.copy( + metadata = toSessionSummaryMetadata(metadata.value), + metadataVersion = metadata.version, + ) + } + } + return next + } + + /** + * `sameSessionSummaryMetadata`: true when the two projections render the + * same list row. Deliberately partial, like the reference — `hapiMcpUrl` + * is not compared (nothing on the list renders it; a real metadata change + * still surfaces through the `metadataVersion` check in + * [isRenderIrrelevantPatch]). + */ + fun sameSessionSummaryMetadata( + current: SessionSummaryMetadata?, + next: SessionSummaryMetadata?, + ): Boolean { + if (current === next) return true + if (current == null || next == null) return current == null && next == null + return current.name == next.name + && current.path == next.path + && current.machineId == next.machineId + && current.summary?.text == next.summary?.text + && current.flavor == next.flavor + && current.agentSessionId == next.agentSessionId + && current.lifecycleState == next.lifecycleState + && current.worktree?.basePath == next.worktree?.basePath + && current.worktree?.branch == next.worktree?.branch + && current.worktree?.name == next.worktree?.name + && current.worktree?.worktreePath == next.worktree?.worktreePath + && current.worktree?.createdAt == next.worktree?.createdAt + } + + /** + * `isRenderIrrelevantPatch`: true when the only difference between the + * pre- and post-patch summaries is `activeAt` — the CLI keep-alive + * re-broadcasts a full patch ~every 10 s per active session with only + * `activeAt` moving, and nothing on the list renders `activeAt`. The + * store keeps the previous object (and skips the re-sort) in that case. + * + * Port notes: `pendingRequests` compares id/kind/tool but NOT `since` + * (replicated — `since` only affects hover copy through the same + * requests). `pinned`/`globalPinned` are intentionally absent, matching + * the reference (patches never carry them; pin flips arrive as full + * sessions or REST refetches). Kotlin collapses the TS + * `undefined !== null` distinction for `modelReasoningEffort`; the only + * effect is suppressing a re-render that stores an equal-rendering value. + */ + fun isRenderIrrelevantPatch(current: SessionSummary, next: SessionSummary): Boolean { + return current.active == next.active + && current.thinking == next.thinking + && current.updatedAt == next.updatedAt + && current.backgroundTaskCount == next.backgroundTaskCount + && current.model == next.model + && current.modelReasoningEffort == next.modelReasoningEffort + && current.effort == next.effort + && current.pendingRequestsCount == next.pendingRequestsCount + // Structured SSE patches (#897) can move these without touching + // the keep-alive fields above; omit them and a todos/metadata/ + // agentState patch would be dropped as "activeAt-only" churn. + && current.todoProgress == next.todoProgress + && current.pendingRequestKinds == next.pendingRequestKinds + && current.pendingRequests.size == next.pendingRequests.size + && current.pendingRequests.indices.all { i -> + val req = current.pendingRequests[i] + val nextReq = next.pendingRequests[i] + req.id == nextReq.id && req.kind == nextReq.kind && req.tool == nextReq.tool + } + && sameSessionSummaryMetadata(current.metadata, next.metadata) + && current.metadataVersion == next.metadataVersion + && current.agentStateVersion == next.agentStateVersion + && current.todosUpdatedAt == next.todosUpdatedAt + } + + /** + * `canApplyVersionedSummaryPatch` — the old "detail required" gate. + * + * The reference keeps it only for unit tests of the pre-watermark rule; + * the live summary path gates against the summary's own watermarks + * instead ([applySessionSummaryPatch]). `teamState` never blocks: it is + * not rendered on the list. + */ + @Deprecated( + "Gate against SessionSummary watermarks (applySessionSummaryPatch); " + + "kept only to pin the legacy rule, mirroring the web reference." + ) + fun canApplyVersionedSummaryPatch(patch: SessionPatch, detailPresent: Boolean): Boolean { + if (patch.metadata == null && patch.agentState == null && patch.todos == null) { + return true + } + return detailPresent + } +} 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 new file mode 100644 index 00000000..23a8674c --- /dev/null +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SessionSortingTest.kt @@ -0,0 +1,109 @@ +package app.hapi.protocol.wire + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** Pins the exact `sortSessionSummaries` order from `web/src/hooks/useSSE.ts`. */ +class SessionSortingTest { + + private fun summary( + id: String, + active: Boolean = false, + updatedAt: Long = 0, + pinned: Boolean? = null, + globalPinned: Boolean? = null, + pendingRequestsCount: Int = 0, + ): SessionSummary = SessionSummary( + id = id, + active = active, + thinking = false, + activeAt = 0, + updatedAt = updatedAt, + pinned = pinned, + globalPinned = globalPinned, + metadata = null, + metadataVersion = 0, + agentStateVersion = 0, + todosUpdatedAt = 0, + todoProgress = null, + pendingRequestsCount = pendingRequestsCount, + pendingRequestKinds = emptyList(), + pendingRequests = emptyList(), + backgroundTaskCount = 0, + futureScheduledMessageCount = 0, + nextScheduledAt = null, + model = null, + modelReasoningEffort = null, + effort = null, + ) + + @Test + fun `globalPinned beats pinned beats active beats recency`() { + val sorted = sortSessionSummaries( + listOf( + summary("recent-inactive", updatedAt = 9_000), + summary("active", active = true, updatedAt = 1_000), + summary("pinned", pinned = true, updatedAt = 500), + summary("global", globalPinned = true, updatedAt = 100), + ) + ) + assertEquals(listOf("global", "pinned", "active", "recent-inactive"), sorted.map { it.id }) + } + + @Test + fun `among active sessions pendingRequestsCount descends before updatedAt`() { + val sorted = sortSessionSummaries( + listOf( + summary("a", active = true, updatedAt = 9_000, pendingRequestsCount = 0), + summary("b", active = true, updatedAt = 1_000, pendingRequestsCount = 2), + summary("c", active = true, updatedAt = 5_000, pendingRequestsCount = 1), + ) + ) + assertEquals(listOf("b", "c", "a"), sorted.map { it.id }) + } + + @Test + fun `inactive sessions ignore pendingRequestsCount (web left-active guard)`() { + val sorted = sortSessionSummaries( + listOf( + summary("low-pending-recent", updatedAt = 9_000, pendingRequestsCount = 0), + summary("high-pending-old", updatedAt = 1_000, pendingRequestsCount = 5), + ) + ) + assertEquals(listOf("low-pending-recent", "high-pending-old"), sorted.map { it.id }) + } + + @Test + fun `pinned sections sort by recency within themselves`() { + val sorted = sortSessionSummaries( + listOf( + summary("g-old", globalPinned = true, updatedAt = 100), + summary("p-new", pinned = true, updatedAt = 9_000), + summary("g-new", globalPinned = true, updatedAt = 5_000), + summary("p-old", pinned = true, updatedAt = 200), + ) + ) + assertEquals(listOf("g-new", "g-old", "p-new", "p-old"), sorted.map { it.id }) + } + + @Test + fun `null pin flags count as false and ties keep prior order (stable)`() { + val a = summary("a", updatedAt = 1_000, pinned = null) + val b = summary("b", updatedAt = 1_000, pinned = false) + val c = summary("c", updatedAt = 1_000) + assertEquals(listOf("a", "b", "c"), sortSessionSummaries(listOf(a, b, c)).map { it.id }) + assertEquals(listOf("c", "b", "a"), sortSessionSummaries(listOf(c, b, a)).map { it.id }) + } + + @Test + fun `updatedAt comparison survives long deltas`() { + // Long-range timestamps must not overflow an Int subtraction. + val sorted = sortSessionSummaries( + listOf( + summary("old", updatedAt = 1_000L), + summary("new", updatedAt = 1_000L + Int.MAX_VALUE.toLong() * 3), + ) + ) + assertEquals(listOf("new", "old"), sorted.map { it.id }) + } +} diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SummaryPatchingTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SummaryPatchingTest.kt new file mode 100644 index 00000000..ca2b9749 --- /dev/null +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/SummaryPatchingTest.kt @@ -0,0 +1,435 @@ +package app.hapi.protocol.wire + +import kotlinx.serialization.json.JsonNull +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Port of the summary-path cases from `web/src/hooks/useSSE.test.ts` + * (`canApplyVersionedSummaryPatch`, `isRenderIrrelevantPatch`) plus pins for + * the pieces the web only exercises through the hook: the `>=` versioned + * gates of `patchSessionSummary`, the `shared/src/sessionSummary.ts` + * derivations, and the `toSessionSummary` projection. + */ +class SummaryPatchingTest { + + private fun makeSummary( + id: String = "session-1", + active: Boolean = true, + thinking: Boolean = false, + activeAt: Long = 1_000, + updatedAt: Long = 2_000, + pinned: Boolean? = null, + globalPinned: Boolean? = null, + metadata: SessionSummaryMetadata? = null, + metadataVersion: Long = 0, + agentStateVersion: Long = 0, + todosUpdatedAt: Long = 0, + todoProgress: TodoProgress? = null, + pendingRequestsCount: Int = 0, + pendingRequestKinds: List = emptyList(), + pendingRequests: List = emptyList(), + backgroundTaskCount: Int = 0, + model: String? = null, + modelReasoningEffort: String? = null, + effort: String? = null, + ): SessionSummary = SessionSummary( + id = id, + active = active, + thinking = thinking, + activeAt = activeAt, + updatedAt = updatedAt, + pinned = pinned, + globalPinned = globalPinned, + metadata = metadata, + metadataVersion = metadataVersion, + agentStateVersion = agentStateVersion, + todosUpdatedAt = todosUpdatedAt, + todoProgress = todoProgress, + pendingRequestsCount = pendingRequestsCount, + pendingRequestKinds = pendingRequestKinds, + pendingRequests = pendingRequests, + backgroundTaskCount = backgroundTaskCount, + futureScheduledMessageCount = 0, + nextScheduledAt = null, + model = model, + modelReasoningEffort = modelReasoningEffort, + effort = effort, + ) + + private fun request(tool: String, createdAt: Long? = null) = + AgentStateRequest(tool = tool, arguments = JsonNull, createdAt = createdAt) + + // ------------------------------------------------------- derivations -- + + @Test + fun `computePendingRequestKinds dedupes and canonicalizes both-kinds order`() { + assertEquals(emptyList(), SummaryPatching.computePendingRequestKinds(null)) + assertEquals(emptyList(), SummaryPatching.computePendingRequestKinds(AgentState())) + + val permissionOnly = AgentState(requests = mapOf("a" to request("Bash"), "b" to request("Edit"))) + assertEquals(listOf("permission"), SummaryPatching.computePendingRequestKinds(permissionOnly)) + + val inputOnly = AgentState(requests = mapOf("a" to request("AskUserQuestion"))) + assertEquals(listOf("input"), SummaryPatching.computePendingRequestKinds(inputOnly)) + + // Input encountered first — canonical order is still permission,input. + val both = AgentState( + requests = linkedMapOf( + "a" to request("request_user_input"), + "b" to request("Bash"), + ) + ) + assertEquals(listOf("permission", "input"), SummaryPatching.computePendingRequestKinds(both)) + } + + @Test + fun `computePendingRequests sorts oldest-first with id tiebreak and falls back to fallbackSince`() { + val state = AgentState( + requests = linkedMapOf( + "req-c" to request("Bash", createdAt = 300), + "req-a" to request("Edit", createdAt = null), // → fallbackSince = 100 + "req-b" to request("ExitPlanMode", createdAt = 100), + ) + ) + val items = SummaryPatching.computePendingRequests(state, fallbackSince = 100) + assertEquals(listOf("req-a", "req-b", "req-c"), items.map { it.id }) + assertEquals(listOf(100L, 100L, 300L), items.map { it.since }) + assertEquals(listOf("permission", "input", "permission"), items.map { it.kind }) + } + + @Test + fun `computePendingRequests caps at five but count stays authoritative`() { + val requests = (1..7).associate { "req-$it" to request("Bash", createdAt = it.toLong()) } + val state = AgentState(requests = requests) + val items = SummaryPatching.computePendingRequests(state, fallbackSince = 0) + assertEquals(5, items.size) + assertEquals((1..5).map { "req-$it" }, items.map { it.id }) + assertEquals(7, SummaryPatching.computePendingRequestsCount(state)) + } + + @Test + fun `computeTodoProgress is null for absent or empty and counts completed`() { + assertNull(SummaryPatching.computeTodoProgress(null)) + assertNull(SummaryPatching.computeTodoProgress(emptyList())) + val todos = listOf( + TodoItem(content = "a", status = "completed"), + TodoItem(content = "b", status = "in_progress"), + TodoItem(content = "c", status = "completed"), + ) + assertEquals(TodoProgress(completed = 2, total = 3), SummaryPatching.computeTodoProgress(todos)) + } + + // -------------------------------------------------------- projection -- + + private fun makeSession( + metadata: SessionMetadata? = null, + agentState: AgentState? = null, + todos: List? = null, + ): Session = Session( + id = "session-1", + namespace = "default", + seq = 1, + createdAt = 1_000, + updatedAt = 2_000, + active = true, + activeAt = 1_000, + metadata = metadata, + metadataVersion = 3, + agentState = agentState, + agentStateVersion = 4, + thinking = true, + thinkingAt = 0, + todos = todos, + todosUpdatedAt = 5, + backgroundTaskCount = 2, + model = "opus", + effort = "high", + ) + + @Test + fun `toSessionSummary projects derived fields and watermarks`() { + val session = makeSession( + metadata = SessionMetadata( + path = "/repo", + host = "host", + name = "My session", + flavor = "claude", + claudeSessionId = " abc ", + summary = MetadataSummary(text = "doing things", updatedAt = 9), + ), + agentState = AgentState(requests = mapOf("r1" to request("Bash", createdAt = 50))), + todos = listOf(TodoItem(content = "a", status = "completed")), + ) + val summary = SummaryPatching.toSessionSummary(session) + assertEquals("session-1", summary.id) + assertTrue(summary.active) + assertTrue(summary.thinking) + assertEquals(false, summary.pinned) + assertEquals(false, summary.globalPinned) + assertEquals(3, summary.metadataVersion) + assertEquals(4, summary.agentStateVersion) + assertEquals(5, summary.todosUpdatedAt) + assertEquals(TodoProgress(1, 1), summary.todoProgress) + assertEquals(1, summary.pendingRequestsCount) + assertEquals(listOf("permission"), summary.pendingRequestKinds) + assertEquals("abc", summary.metadata?.agentSessionId) // trimmed + assertEquals("doing things", summary.metadata?.summary?.text) + assertEquals(2, summary.backgroundTaskCount) + assertEquals(0, summary.futureScheduledMessageCount) + assertNull(summary.nextScheduledAt) + } + + @Test + fun `agentSessionId uses only the known flavor's field, legacy chain otherwise`() { + // Known flavor: other flavors' ids are ignored, blank collapses to null. + val claude = SummaryPatching.toSessionSummaryMetadata( + SessionMetadata(path = "/p", host = "h", flavor = "claude", claudeSessionId = " ", codexSessionId = "cx") + ) + assertNull(claude?.agentSessionId) + + // Unknown flavor: legacy fallback chain, codex first, untrimmed. + val unknown = SummaryPatching.toSessionSummaryMetadata( + SessionMetadata(path = "/p", host = "h", flavor = "newagent", claudeSessionId = "cl", codexSessionId = "cx") + ) + assertEquals("cx", unknown?.agentSessionId) + + // Legacy chain never reads piSessionId (replicated web quirk). + val piOnly = SummaryPatching.toSessionSummaryMetadata( + SessionMetadata(path = "/p", host = "h", flavor = null, piSessionId = "pi-1") + ) + assertNull(piOnly?.agentSessionId) + } + + // ------------------------------------------------- patch application -- + + @Test + fun `flat fields are last-write-wins and updatedAt is max-monotonic`() { + val current = makeSummary(updatedAt = 2_000, model = "opus", backgroundTaskCount = 1) + val next = SummaryPatching.applySessionSummaryPatch( + current, + SessionPatch( + active = false, + thinking = true, + activeAt = 9_000, + updatedAt = 1_500, // stale — must not rewind + model = OptionalField.Present(null), // present null clears + effort = OptionalField.Present("low"), + backgroundTaskCount = 3, + ), + ) + assertFalse(next.active) + assertTrue(next.thinking) + assertEquals(9_000, next.activeAt) + assertEquals(2_000, next.updatedAt) + assertNull(next.model) + assertEquals("low", next.effort) + assertEquals(3, next.backgroundTaskCount) + } + + @Test + fun `absent optional fields leave the summary untouched`() { + val current = makeSummary(model = "opus", modelReasoningEffort = "high", effort = "medium") + val next = SummaryPatching.applySessionSummaryPatch(current, SessionPatch(activeAt = 5_000)) + assertEquals("opus", next.model) + assertEquals("high", next.modelReasoningEffort) + assertEquals("medium", next.effort) + } + + @Test + fun `agentState patch with equal version reapplies (summary path accepts gte)`() { + // DIVERGENCE FROM DETAIL PATH, replicated from web: the detail cache + // gates with strict `>`; the summary path re-derives from `>=` + // because the derivation is idempotent (sse.md#versioned-patch-algorithm). + val current = makeSummary(agentStateVersion = 5, pendingRequestsCount = 0) + val state = AgentState(requests = mapOf("r1" to request("Bash", createdAt = 10))) + val next = SummaryPatching.applySessionSummaryPatch( + current, + SessionPatch(agentState = VersionedValue(version = 5, value = state)), + ) + assertEquals(1, next.pendingRequestsCount) + assertEquals(listOf("permission"), next.pendingRequestKinds) + assertEquals(5, next.agentStateVersion) + } + + @Test + fun `stale versioned patches are rejected`() { + val current = makeSummary( + metadataVersion = 5, + agentStateVersion = 5, + todosUpdatedAt = 5, + pendingRequestsCount = 2, + todoProgress = TodoProgress(1, 2), + ) + val next = SummaryPatching.applySessionSummaryPatch( + current, + SessionPatch( + metadata = VersionedValue(4, SessionMetadata(path = "/new", host = "h")), + agentState = VersionedValue(4, AgentState()), + todos = VersionedValue(4, emptyList()), + ), + ) + assertEquals(5, next.metadataVersion) + assertEquals(5, next.agentStateVersion) + assertEquals(5, next.todosUpdatedAt) + assertEquals(2, next.pendingRequestsCount) + assertEquals(TodoProgress(1, 2), next.todoProgress) + assertNull(next.metadata) + } + + @Test + fun `newer versioned patches recompute the derived fields`() { + val current = makeSummary(updatedAt = 2_000, agentStateVersion = 1, todosUpdatedAt = 1, metadataVersion = 1) + val next = SummaryPatching.applySessionSummaryPatch( + current, + SessionPatch( + updatedAt = 8_000, + metadata = VersionedValue(2, SessionMetadata(path = "/repo", host = "h", name = "n")), + agentState = VersionedValue(2, AgentState(requests = mapOf("r1" to request("Edit")))), + todos = VersionedValue(2, listOf(TodoItem(content = "a", status = "pending"))), + ), + ) + assertEquals(8_000, next.updatedAt) + assertEquals(2, next.metadataVersion) + assertEquals("/repo", next.metadata?.path) + assertEquals(2, next.agentStateVersion) + assertEquals(1, next.pendingRequestsCount) + // Requests without createdAt use the POST-patch updatedAt as `since`. + assertEquals(8_000, next.pendingRequests.single().since) + assertEquals(2, next.todosUpdatedAt) + assertEquals(TodoProgress(0, 1), next.todoProgress) + } + + @Test + fun `agentState null value clears the pending fields`() { + val current = makeSummary( + agentStateVersion = 1, + pendingRequestsCount = 2, + pendingRequestKinds = listOf("permission"), + pendingRequests = listOf(PendingRequest("r1", "permission", "Bash", 1)), + ) + val next = SummaryPatching.applySessionSummaryPatch( + current, + SessionPatch(agentState = VersionedValue(2, null)), + ) + assertEquals(0, next.pendingRequestsCount) + assertEquals(emptyList(), next.pendingRequestKinds) + assertEquals(emptyList(), next.pendingRequests) + } + + @Test + fun `teamState patch is a summary no-op`() { + val current = makeSummary() + val next = SummaryPatching.applySessionSummaryPatch( + current, + SessionPatch(teamState = VersionedValue(9, null)), + ) + assertEquals(current, next) + } + + // -------------------------------------------- render-irrelevance filter -- + + @Test + fun `keep-alive that only moves activeAt is irrelevant`() { + val current = makeSummary(activeAt = 1_000) + val next = makeSummary(activeAt = 11_000) + assertTrue(SummaryPatching.isRenderIrrelevantPatch(current, next)) + } + + @Test + fun `identical summaries are irrelevant`() { + assertTrue(SummaryPatching.isRenderIrrelevantPatch(makeSummary(), makeSummary())) + } + + @Test + fun `each rendered field change is relevant`() { + val cases = listOf( + makeSummary(active = false), + makeSummary(thinking = true), + makeSummary(updatedAt = 9_999), + makeSummary(backgroundTaskCount = 3), + makeSummary(model = "opus"), + makeSummary(modelReasoningEffort = "high"), + makeSummary(effort = "medium"), + makeSummary(pendingRequestsCount = 2), + makeSummary(metadata = SessionSummaryMetadata(path = "/other")), + makeSummary(metadata = SessionSummaryMetadata(path = "/tmp", flavor = "claude")), + makeSummary(metadata = SessionSummaryMetadata(path = "/tmp", machineId = "Teemo")), + makeSummary( + metadata = SessionSummaryMetadata( + path = "/tmp", + worktree = WorktreeMetadata( + basePath = "/tmp", branch = "feat/x", name = "x", worktreePath = "/tmp/x", + ), + ) + ), + makeSummary(todoProgress = TodoProgress(1, 2)), + makeSummary(pendingRequestKinds = listOf("input")), + makeSummary(metadataVersion = 7), + makeSummary(agentStateVersion = 7), + makeSummary(todosUpdatedAt = 7), + ) + for (changed in cases) { + assertFalse( + SummaryPatching.isRenderIrrelevantPatch(makeSummary(), changed.copy(activeAt = 11_000)), + "expected relevant: $changed", + ) + } + } + + @Test + fun `pendingRequests compare id kind tool but not since`() { + val current = makeSummary( + pendingRequests = listOf(PendingRequest("r1", "permission", "Bash", since = 1)), + ) + val sinceOnly = makeSummary( + pendingRequests = listOf(PendingRequest("r1", "permission", "Bash", since = 2)), + ) + assertTrue(SummaryPatching.isRenderIrrelevantPatch(current, sinceOnly)) + + val toolChanged = makeSummary( + pendingRequests = listOf(PendingRequest("r1", "permission", "Edit", since = 1)), + ) + assertFalse(SummaryPatching.isRenderIrrelevantPatch(current, toolChanged)) + } + + // ---------------------------------------- legacy detail-required gate -- + + @Suppress("DEPRECATION") + @Test + fun `canApplyVersionedSummaryPatch mirrors the legacy rule`() { + // Non-versioned patches never need detail. + assertTrue(SummaryPatching.canApplyVersionedSummaryPatch(SessionPatch(), detailPresent = false)) + // metadata/agentState/todos each require detail. + assertFalse( + SummaryPatching.canApplyVersionedSummaryPatch( + SessionPatch(metadata = VersionedValue(1, null)), detailPresent = false, + ) + ) + assertFalse( + SummaryPatching.canApplyVersionedSummaryPatch( + SessionPatch(agentState = VersionedValue(1, null)), detailPresent = false, + ) + ) + assertFalse( + SummaryPatching.canApplyVersionedSummaryPatch( + SessionPatch(todos = VersionedValue(1, emptyList())), detailPresent = false, + ) + ) + // teamState-only is a summary no-op and never blocks. + assertTrue( + SummaryPatching.canApplyVersionedSummaryPatch( + SessionPatch(teamState = VersionedValue(1, null)), detailPresent = false, + ) + ) + // With detail present everything is allowed. + assertTrue( + SummaryPatching.canApplyVersionedSummaryPatch( + SessionPatch(metadata = VersionedValue(2, null)), detailPresent = true, + ) + ) + } +}