mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
feat(android): web-parity presence badges, sort/filter and attached jobs
The home list showed presence only for connected sessions, offered no sort or status choices, and ignored session-attached jobs. Its strict SessionPatch parser also rejected every `attachedJob` SSE patch, so each job heartbeat fell back to a REST list refetch. - Presence badge follows web #2296: solid green pulsing while working, solid blue pulsing for background tasks only, a green ring when connected and waiting, and a power mark when stopped or archived. - The Sort & filter sheet adds Show (all / active only / archived only) and Unread only next to machines and dates, then Sort by (last message or date created) and Active first (on by default; manual pins still lead). Sort and Active first persist app-wide in hapi_prefs; filters stay transient, keep the open session listed, and Reset leaves the order alone. Search keeps relevance with the base tie-break. The share picker keeps the base order. - Decode AttachedJob on summaries and the versioned `attachedJob` patch, applied only when strictly newer, as on web. Full-session events keep the row's job. A running job counts as working on the badge and as active for the Show filter (web #1404), and adds a row line with label, remaining or percent, elapsed time and a thin bar, amber with "no heartbeat" after 15 minutes. - HomeFilterWindowTest's click helper now scrolls back once it reaches the end; the taller sheet otherwise stranded targets above the viewport. - Docs describe the Android sheet, row and job display.
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package app.hapi.protocol.wire
|
||||
|
||||
import kotlin.math.roundToInt
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* Session-attached long-running work (tiann/hapi#1404): the primary job on a
|
||||
* [SessionSummary], independent of agent `active` / `thinking` — work that
|
||||
* outlives the agent. Mirrors `AttachedJobSchema` (`shared/src/schemas.ts`);
|
||||
* supervisor-only fields (`runId`, wake options) are ignored on decode.
|
||||
* [status] stays a string so a status this client does not know cannot fail
|
||||
* the whole list; only [STATUS_RUNNING] is live work.
|
||||
*/
|
||||
@Serializable
|
||||
data class AttachedJob(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val status: String = STATUS_RUNNING,
|
||||
val done: Double? = null,
|
||||
val total: Double? = null,
|
||||
val remaining: Double? = null,
|
||||
val unit: String? = null,
|
||||
val detail: String? = null,
|
||||
val heartbeatAt: Long,
|
||||
val startedAt: Long,
|
||||
val updatedAt: Long,
|
||||
) {
|
||||
val isRunning: Boolean get() = status == STATUS_RUNNING
|
||||
|
||||
/** No heartbeat for [STALE_AFTER_MS]: the row turns amber but keeps its progress. */
|
||||
fun isStale(nowMs: Long): Boolean = nowMs - heartbeatAt > STALE_AFTER_MS
|
||||
|
||||
/**
|
||||
* Whole percent from `done`/`total`, capped at 100; null without a positive
|
||||
* total. `remaining` takes precedence in labels (web
|
||||
* `formatAttachedJobProgress`), so callers check it first.
|
||||
*/
|
||||
val percent: Int?
|
||||
get() {
|
||||
val done = done ?: return null
|
||||
val total = total?.takeIf { it > 0 } ?: return null
|
||||
return minOf(100, (done / total * 100).roundToInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Determinate bar fill in 0..1, or null for an indeterminate bar (web
|
||||
* `attachedJobFraction`: `remaining` wins over `done`/`total`).
|
||||
*/
|
||||
val fraction: Float?
|
||||
get() {
|
||||
val total = total?.takeIf { it > 0 } ?: return null
|
||||
val done = remaining?.let { maxOf(0.0, total - it) } ?: done ?: return null
|
||||
return (done / total).coerceIn(0.0, 1.0).toFloat()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val STATUS_RUNNING: String = "running"
|
||||
|
||||
/** Web `ATTACHED_JOB_STALE_MS`. */
|
||||
const val STALE_AFTER_MS: Long = 15 * 60 * 1000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lettered elapsed time for list chrome, at most two units (web
|
||||
* `formatCompactElapsed`), never an ETA. Rows tick per minute, so anything
|
||||
* under a minute reads `<1m` rather than a seconds count that would freeze.
|
||||
*/
|
||||
fun formatCompactElapsed(elapsedMs: Long): String {
|
||||
if (elapsedMs < 60_000) return "<1m"
|
||||
val totalMinutes = elapsedMs / 60_000
|
||||
if (totalMinutes < 60) return "${totalMinutes}m"
|
||||
val hours = totalMinutes / 60
|
||||
val minutes = totalMinutes % 60
|
||||
if (hours < 24) return if (minutes > 0) "${hours}h ${minutes}m" else "${hours}h"
|
||||
val days = hours / 24
|
||||
val remainingHours = hours % 24
|
||||
return if (remainingHours > 0) "${days}d ${remainingHours}h" else "${days}d"
|
||||
}
|
||||
|
||||
/** Progress counts as the hub sent them: integers without a decimal point. */
|
||||
fun formatJobQuantity(value: Double): String =
|
||||
if (value % 1.0 == 0.0 && kotlin.math.abs(value) < 1e15) value.toLong().toString() else value.toString()
|
||||
@@ -59,6 +59,11 @@ data class SessionPatch(
|
||||
val backgroundTaskCount: Int? = null,
|
||||
/** Bare refetch trigger for `GET /sessions/:id/scratchlist`; carries no data. */
|
||||
val scratchlistUpdatedAt: Long? = null,
|
||||
/**
|
||||
* tiann/hapi#1404: the list row's primary attached job; a null value
|
||||
* clears it. Summary-only — the detail [Session] has no such field.
|
||||
*/
|
||||
val attachedJob: VersionedValue<AttachedJob>? = null,
|
||||
val contentRevision: Long? = null,
|
||||
val readState: SessionReadState? = null,
|
||||
)
|
||||
@@ -70,7 +75,7 @@ object SessionPatches {
|
||||
"metadata", "agentState", "todos", "teamState",
|
||||
"model", "modelReasoningEffort", "effort", "serviceTier",
|
||||
"permissionMode", "collaborationMode", "copilotAgentMode",
|
||||
"backgroundTaskCount", "scratchlistUpdatedAt",
|
||||
"backgroundTaskCount", "scratchlistUpdatedAt", "attachedJob",
|
||||
// Web-only status-panel list; accepted so the patch is not refetched.
|
||||
"backgroundTasks",
|
||||
)
|
||||
@@ -144,6 +149,12 @@ object SessionPatches {
|
||||
},
|
||||
backgroundTaskCount = obj["backgroundTaskCount"]?.let { it.intOrNull ?: return null },
|
||||
scratchlistUpdatedAt = obj["scratchlistUpdatedAt"]?.let { it.longOrNull ?: return null },
|
||||
attachedJob = obj["attachedJob"]?.let { wrapper ->
|
||||
versioned(wrapper) { value ->
|
||||
if (value is JsonNull) null
|
||||
else HapiJson.decodeFromJsonElement(AttachedJob.serializer(), value)
|
||||
} ?: return null
|
||||
},
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
|
||||
@@ -1,15 +1,69 @@
|
||||
package app.hapi.protocol.wire
|
||||
|
||||
/** Mirrors shared/src/sessionOrder.ts. Output and liveness do not affect order. */
|
||||
val SessionOrderComparator: Comparator<SessionSummary> =
|
||||
compareByDescending<SessionSummary> { it.lastUserMessageAt ?: it.createdAt ?: 0L }
|
||||
/** Session-list sort key (web `SessionListSort`, `web/src/hooks/useSessionListView.ts`). */
|
||||
enum class SessionListSort(val storageKey: String) {
|
||||
/** The user's latest prompt, falling back to creation. Agent output never moves it. */
|
||||
LastMessage("last-message"),
|
||||
|
||||
/** Newest sessions first. */
|
||||
Created("created");
|
||||
|
||||
companion object {
|
||||
/** Unknown/corrupt stored values (e.g. web's dropped "activity") degrade to [LastMessage]. */
|
||||
fun fromStorageKey(raw: String?): SessionListSort = entries.firstOrNull { it.storageKey == raw } ?: LastMessage
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Session-list ordering choices: a sort key and whether connected sessions
|
||||
* lead each pin tier (web `SessionListView.sort` / `.activeFirst`).
|
||||
*/
|
||||
data class SessionListOrder(
|
||||
val sort: SessionListSort = SessionListSort.LastMessage,
|
||||
val activeFirst: Boolean = true,
|
||||
) {
|
||||
val isDefault: Boolean get() = this == Default
|
||||
|
||||
companion object {
|
||||
/** The list default (web `DEFAULT_SESSION_LIST_VIEW`). */
|
||||
val Default = SessionListOrder()
|
||||
|
||||
/** The base order every store keeps: user input only, no liveness. */
|
||||
val Base = SessionListOrder(SessionListSort.LastMessage, activeFirst = false)
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirrors web `getSessionSortKey` (`web/src/lib/sessionListOrder.ts`). */
|
||||
fun sessionSortKey(session: SessionSummary, sort: SessionListSort): Long = when (sort) {
|
||||
SessionListSort.Created -> session.createdAt ?: 0L
|
||||
SessionListSort.LastMessage -> session.lastUserMessageAt ?: session.createdAt ?: 0L
|
||||
}
|
||||
|
||||
/** The chosen key descending, then creation descending, then id. */
|
||||
fun sessionOrderComparator(sort: SessionListSort): Comparator<SessionSummary> =
|
||||
compareByDescending<SessionSummary> { sessionSortKey(it, sort) }
|
||||
.thenByDescending { it.createdAt ?: 0L }
|
||||
.thenBy { it.id }
|
||||
|
||||
val SessionSummaryComparator: Comparator<SessionSummary> =
|
||||
compareByDescending<SessionSummary> { it.globalPinned == true }
|
||||
/**
|
||||
* Global pins, project pins, then (with `activeFirst`) connected sessions,
|
||||
* then the sort key. Web `createSessionComparator` under the flat native
|
||||
* list's pin tiers: manual pins still come first.
|
||||
*/
|
||||
fun sessionSummaryComparator(order: SessionListOrder): Comparator<SessionSummary> {
|
||||
val pins = compareByDescending<SessionSummary> { it.globalPinned == true }
|
||||
.thenByDescending { it.pinned == true }
|
||||
.then(SessionOrderComparator)
|
||||
val live = if (order.activeFirst) pins.thenByDescending { it.active } else pins
|
||||
return live.then(sessionOrderComparator(order.sort))
|
||||
}
|
||||
|
||||
/** Mirrors shared/src/sessionOrder.ts. Output and liveness do not affect order. */
|
||||
val SessionOrderComparator: Comparator<SessionSummary> = sessionOrderComparator(SessionListSort.LastMessage)
|
||||
|
||||
val SessionSummaryComparator: Comparator<SessionSummary> = sessionSummaryComparator(SessionListOrder.Base)
|
||||
|
||||
fun sortSessionSummaries(sessions: List<SessionSummary>): List<SessionSummary> =
|
||||
sessions.sortedWith(SessionSummaryComparator)
|
||||
|
||||
fun sortSessionSummaries(sessions: List<SessionSummary>, order: SessionListOrder): List<SessionSummary> =
|
||||
sessions.sortedWith(sessionSummaryComparator(order))
|
||||
|
||||
@@ -36,6 +36,10 @@ data class SessionSummary(
|
||||
val futureScheduledMessageCount: Int = 0,
|
||||
/** Epoch ms of the soonest uninvoked future scheduled message, or null. */
|
||||
val nextScheduledAt: Long? = null,
|
||||
/** Primary session-attached job (tiann/hapi#1404), or null. */
|
||||
val attachedJob: AttachedJob? = null,
|
||||
/** Watermark for versioned `attachedJob` patches; absent (older hub) gates as 0. */
|
||||
val attachedJobUpdatedAt: Long = 0,
|
||||
val model: String? = null,
|
||||
val modelReasoningEffort: String? = null,
|
||||
val effort: String? = null,
|
||||
|
||||
@@ -210,6 +210,8 @@ object SummaryPatching {
|
||||
* (see the class doc for why equality is safe here and only here), then
|
||||
* recompute the derived fields. `pendingRequests`' fallback `since` is
|
||||
* the summary's post-patch `updatedAt`, matching the reference.
|
||||
* - `attachedJob` gates strictly (`>`) on `attachedJobUpdatedAt`, like
|
||||
* the reference: a lagged heartbeat must not resurrect a clear.
|
||||
* - `teamState` is a summary no-op (not rendered on the list).
|
||||
* - `activeTurnStartedAt` / `scratchlistUpdatedAt` / `serviceTier` /
|
||||
* `permissionMode` / `collaborationMode` / `copilotAgentMode` have no
|
||||
@@ -269,6 +271,11 @@ object SummaryPatching {
|
||||
)
|
||||
}
|
||||
}
|
||||
patch.attachedJob?.let { job ->
|
||||
if (job.version > current.attachedJobUpdatedAt) {
|
||||
next = next.copy(attachedJob = job.value, attachedJobUpdatedAt = job.version)
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
@@ -340,6 +347,9 @@ object SummaryPatching {
|
||||
&& current.metadataVersion == next.metadataVersion
|
||||
&& current.agentStateVersion == next.agentStateVersion
|
||||
&& current.todosUpdatedAt == next.todosUpdatedAt
|
||||
// Heartbeats move only `heartbeatAt`, which drives the stale state.
|
||||
&& current.attachedJob == next.attachedJob
|
||||
&& current.attachedJobUpdatedAt == next.attachedJobUpdatedAt
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package app.hapi.protocol.wire
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
|
||||
/**
|
||||
* tiann/hapi#1404 on the list row: wire decoding, the strict `>` version gate
|
||||
* of web `patchSessionSummary`, render relevance and the row helpers.
|
||||
*/
|
||||
class AttachedJobTest {
|
||||
private val jobJson = """{"key":"import","label":"Import","status":"running","done":12,"total":30,""" +
|
||||
""""unit":"files","runId":"r1","wakeOnTerminal":true,"heartbeatAt":5000,"startedAt":1000,"updatedAt":5000}"""
|
||||
|
||||
private fun element(json: String): JsonElement = Json.parseToJsonElement(json)
|
||||
|
||||
private fun patch(json: String): SessionPatch = assertNotNull(SessionPatches.parse(element(json)))
|
||||
|
||||
@Test
|
||||
fun `list rows decode jobs leniently`() {
|
||||
val row = """{"id":"s1","active":false,"attachedJob":$jobJson,"attachedJobUpdatedAt":7}"""
|
||||
val decoded = HapiJson.decodeFromString(SessionSummary.serializer(), row)
|
||||
assertEquals("Import", decoded.attachedJob?.label)
|
||||
assertEquals(true, decoded.attachedJob?.isRunning)
|
||||
assertEquals(7L, decoded.attachedJobUpdatedAt)
|
||||
|
||||
val paused = HapiJson.decodeFromString(SessionSummary.serializer(), row.replace("\"running\"", "\"paused\""))
|
||||
assertEquals(false, paused.attachedJob?.isRunning, "A new status must not fail the list")
|
||||
|
||||
val legacy = HapiJson.decodeFromString(SessionSummary.serializer(), """{"id":"s1","active":false}""")
|
||||
assertNull(legacy.attachedJob)
|
||||
assertEquals(0L, legacy.attachedJobUpdatedAt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `job patches parse instead of forcing a refetch`() {
|
||||
val parsed = patch("""{"attachedJob":{"version":5,"value":$jobJson}}""")
|
||||
assertEquals(5L, parsed.attachedJob?.version)
|
||||
assertEquals(12.0, parsed.attachedJob?.value?.done)
|
||||
assertNull(patch("""{"attachedJob":{"version":6,"value":null}}""").attachedJob?.value)
|
||||
assertNull(SessionPatches.parse(element("""{"attachedJob":{"version":6}}""")), "value key is required")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `patches apply only when strictly newer`() {
|
||||
val empty = SessionSummary(id = "s1", active = false)
|
||||
val start = patch("""{"attachedJob":{"version":5,"value":$jobJson}}""")
|
||||
val running = SummaryPatching.applySessionSummaryPatch(empty, start)
|
||||
assertEquals(12.0, running.attachedJob?.done)
|
||||
assertEquals(5L, running.attachedJobUpdatedAt)
|
||||
assertFalse(SummaryPatching.isRenderIrrelevantPatch(empty, running))
|
||||
|
||||
val cleared = SummaryPatching.applySessionSummaryPatch(running, patch("""{"attachedJob":{"version":6,"value":null}}"""))
|
||||
assertNull(cleared.attachedJob)
|
||||
assertEquals(6L, cleared.attachedJobUpdatedAt)
|
||||
|
||||
// Dual SSE: a lagged heartbeat cannot resurrect the clear; an equal
|
||||
// version is a replay.
|
||||
assertNull(SummaryPatching.applySessionSummaryPatch(cleared, start).attachedJob)
|
||||
val heartbeat = running.attachedJob!!.copy(heartbeatAt = 9_000)
|
||||
val replay = SummaryPatching.applySessionSummaryPatch(running, SessionPatch(attachedJob = VersionedValue(5, heartbeat)))
|
||||
assertEquals(running, replay)
|
||||
val beat = SummaryPatching.applySessionSummaryPatch(running, SessionPatch(attachedJob = VersionedValue(7, heartbeat)))
|
||||
assertFalse(SummaryPatching.isRenderIrrelevantPatch(running, beat), "Heartbeats drive staleness")
|
||||
assertTrue(SummaryPatching.isRenderIrrelevantPatch(running, running.copy(activeAt = 99)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `row helpers match the web labels`() {
|
||||
val job = AttachedJob(key = "k", label = "Import", done = 12.0, total = 30.0, heartbeatAt = 0, startedAt = 0, updatedAt = 0)
|
||||
assertEquals(40, job.percent)
|
||||
assertEquals(0.4f, job.fraction)
|
||||
assertEquals(100, job.copy(done = 45.0).percent, "Capped")
|
||||
assertEquals(0.6f, job.copy(remaining = 12.0).fraction, "Remaining wins, as on web")
|
||||
assertNull(job.copy(total = null).percent)
|
||||
assertNull(job.copy(total = null).fraction, "No honest fraction: indeterminate bar")
|
||||
assertFalse(job.isStale(AttachedJob.STALE_AFTER_MS))
|
||||
assertTrue(job.isStale(AttachedJob.STALE_AFTER_MS + 1))
|
||||
|
||||
assertEquals("<1m", formatCompactElapsed(59_999))
|
||||
assertEquals("5m", formatCompactElapsed(5 * 60_000L))
|
||||
assertEquals("3h 5m", formatCompactElapsed(3 * 3_600_000L + 5 * 60_000L))
|
||||
assertEquals("2h", formatCompactElapsed(2 * 3_600_000L))
|
||||
assertEquals("1d 2h", formatCompactElapsed(26 * 3_600_000L))
|
||||
assertEquals("12", formatJobQuantity(12.0))
|
||||
assertEquals("1.5", formatJobQuantity(1.5))
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,37 @@ class SessionSortingTest {
|
||||
assertEquals(listOf("old", "new"), sortSessionSummaries(listOf(old.copy(lastUserMessageAt = 300), newer)).map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active first leads each pin tier without beating pins`() {
|
||||
val rows = listOf(
|
||||
summary("new-stopped", 2, 200),
|
||||
summary("old-live", 1, 100).copy(active = true),
|
||||
summary("pinned-stopped", at = 1).copy(pinned = true),
|
||||
summary("global", at = 0).copy(globalPinned = true),
|
||||
summary("pinned-live", at = 0).copy(pinned = true, active = true),
|
||||
)
|
||||
assertEquals(
|
||||
listOf("global", "pinned-live", "pinned-stopped", "old-live", "new-stopped"),
|
||||
sortSessionSummaries(rows, SessionListOrder.Default).map { it.id },
|
||||
)
|
||||
assertEquals(
|
||||
listOf("global", "pinned-stopped", "pinned-live", "new-stopped", "old-live"),
|
||||
sortSessionSummaries(rows, SessionListOrder.Base).map { it.id },
|
||||
)
|
||||
assertEquals(sortSessionSummaries(rows), sortSessionSummaries(rows, SessionListOrder.Base))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `created sort ignores input and stored keys match web`() {
|
||||
val rows = listOf(summary("early", 1, 900), summary("unknown", at = 999), summary("late", 5, 10))
|
||||
val created = SessionListOrder(SessionListSort.Created, activeFirst = false)
|
||||
assertEquals(listOf("late", "early", "unknown"), sortSessionSummaries(rows, created).map { it.id })
|
||||
assertEquals(listOf("unknown", "early", "late"), sortSessionSummaries(rows, SessionListOrder.Base).map { it.id })
|
||||
assertEquals("last-message", SessionListSort.LastMessage.storageKey)
|
||||
assertEquals(SessionListSort.LastMessage, SessionListSort.fromStorageKey("activity"))
|
||||
assertEquals(SessionListOrder(SessionListSort.LastMessage, activeFirst = true), SessionListOrder.Default)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `manual pins still come first`() {
|
||||
val rows = listOf(summary("new", at = 99), summary("project", at = 2).copy(pinned = true), summary("global", at = 1).copy(globalPinned = true))
|
||||
|
||||
Reference in New Issue
Block a user