feat(android): session/machine stores + session list (B-M2b)

: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.
This commit is contained in:
weishu
2026-08-17 15:47:05 +08:00
parent f275bae4cb
commit f702cbf844
21 changed files with 3816 additions and 0 deletions
@@ -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<T : Any>(
private val file: File,
private val serializer: KSerializer<T>,
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
}
}
@@ -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<String, Long> = emptyMap(),
val baselines: Set<String> = 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<LastSeenState>? = 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<LastSeenState> = _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<SessionSummary>) {
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
}
}
@@ -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<List<Machine>>
/** `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<List<Machine>>? = 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<List<Machine>> = _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<Machine>) -> List<Machine>) {
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
}
}
@@ -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<List<SessionSummary>>
/** `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<List<SessionSummary>>? = 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<List<SessionSummary>> = _sessions.asStateFlow()
private val _details = MutableStateFlow<Map<String, Session>>(emptyMap())
/** All cached details; per-id observation via [sessionDetail]. */
val details: StateFlow<Map<String, Session>> = _details.asStateFlow()
private val refreshMutex = Mutex()
private val refreshQueued = AtomicBoolean(false)
fun sessionDetail(sessionId: String): Flow<Session?> =
_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<SessionSummary>) -> List<SessionSummary>) {
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 <K, V> MutableStateFlow<Map<K, V>>.update(transform: (Map<K, V>) -> Map<K, V>) {
while (true) {
val previous = value
val next = transform(previous)
if (next === previous || compareAndSet(previous, next)) return
}
}
@@ -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) {
}
}
}
}
@@ -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") })
}
}
@@ -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"))
}
}
@@ -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()
}
}
}
@@ -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<Exception> { 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<Exception> { 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<Exception> { 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()
}
}
}
@@ -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<List<SessionSummary>> = MutableStateFlow(emptyList())
val calls = mutableListOf<String>()
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<List<Machine>> = MutableStateFlow(emptyList())
val calls = mutableListOf<String>()
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<SyncEvent.Toast>()
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)
}
}
@@ -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())