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
@@ -32,6 +32,19 @@ data class SessionMetadata(
val hapiMcpUrl: String? = null,
val slashCommands: List<String>? = null,
val tools: List<String>? = 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}`). */
@@ -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<SessionSummary> = 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<SessionSummary>): List<SessionSummary> =
sessions.sortedWith(SessionSummaryComparator)
@@ -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<String> {
val requests = agentState?.requests ?: return emptyList()
val kinds = LinkedHashSet<String>()
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<PendingRequest> {
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<TodoItem>?): 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
}
}
@@ -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 })
}
}
@@ -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<String> = emptyList(),
pendingRequests: List<PendingRequest> = 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<TodoItem>? = 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<SessionSummary>(
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,
)
)
}
}