From 23e3c5431a0ab0fd63219765ecaed8192989e7a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Tue, 10 Nov 2026 09:05:41 +0000 Subject: [PATCH] Progress (harness spec 3.4.0): one line for what a reply is doing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `status` frame carries `progress` {phase, since, ...} beside its text from spec 3.4.0 (progress.md). The app draws it as `{{text}} · {{elapsed}}` -- the shared texts as string resources, the elapsed time ticking each second, `retrying`'s `in` counted down, the text alone for stopped and failed -- under the reply and in the assistant's sheet, and falls back to the free `status` text for a server that does not send it, a phase it does not know, or a required field missing. Under inspection the clock stands still (65 s), so screenshots are stable and nothing animates forever. Coded to the spec while the server's frame is being added. ProgressTest runs the spec's own conformance cases (conformance/progress.json, copied from LLeMbas CLI 3.4.0 until the server vendors it) against the English in res/values; fetch-contract.py pins the server's copy as contract/harness_progress.json once it is there. gen-strings.py takes the server's translations of the `{{field}}` texts (its catalogues key them by the spec's English), numbering the fields and doubling a lone %. Screenshots: 04-writing with a rate, 04-waiting-for-model at 360 dp and 1.5x type. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + .../java/eu/llembas/android/api/LiveReply.kt | 6 +- .../java/eu/llembas/android/api/Models.kt | 7 +- .../java/eu/llembas/android/api/Progress.kt | 137 +++++++ .../eu/llembas/android/assist/AssistSheet.kt | 4 +- .../eu/llembas/android/ui/ProgressWords.kt | 89 +++++ .../eu/llembas/android/ui/chat/ChatScreen.kt | 8 +- app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-hu/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-sk/strings.xml | 2 + app/src/main/res/values/strings.xml | 29 ++ .../java/eu/llembas/android/ProgressTest.kt | 98 ++++++ .../java/eu/llembas/android/shots/Fakes.kt | 14 +- .../eu/llembas/android/shots/ScreenShots.kt | 6 +- .../test/resources/progress_conformance.json | 333 ++++++++++++++++++ scripts/fetch-contract.py | 17 +- scripts/gen-strings.py | 18 +- scripts/strings.py | 46 +++ 23 files changed, 821 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/eu/llembas/android/api/Progress.kt create mode 100644 app/src/main/java/eu/llembas/android/ui/ProgressWords.kt create mode 100644 app/src/test/java/eu/llembas/android/ProgressTest.kt create mode 100644 app/src/test/resources/progress_conformance.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e5fa3e..f714482 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,14 @@ is in alpha and releases come off `main`. and the recording goes wherever that recogniser sends it. No Google library is in the app: it uses whichever recogniser the phone has, and says so when it has none. +- **What a reply is doing, in the words every LLeMbas app uses.** Under a reply being written + the app draws the server's progress -- *Queued*, *Waiting for* a model *and why*, *Loading*, + *Reading the prompt: 1999 / 3000 tokens (66%)*, *Thinking*, *Writing: 12.5 tok/s*, + *Running bash: bun test*, *Waiting for you*, *Waiting for subagents*, *Compacting*, + *Retrying in 7 s*, *Stopped*, *Failed* -- with how long it has been at it, ticking each + second (`· 1m 05s`). The same in the assistant's sheet. A server that does not send it yet + is shown as before. + ### Fixed - **A corrected command on an approval runs as corrected.** A linked computer's approval card diff --git a/app/src/main/java/eu/llembas/android/api/LiveReply.kt b/app/src/main/java/eu/llembas/android/api/LiveReply.kt index 0f09be8..0adb690 100644 --- a/app/src/main/java/eu/llembas/android/api/LiveReply.kt +++ b/app/src/main/java/eu/llembas/android/api/LiveReply.kt @@ -15,6 +15,8 @@ data class LiveReply( val tail: Tail = Tail(), val plan: Plan? = null, val status: String = "", + /** The structured progress beside [status] (spec 3.4.0); null from an older server, or idle. */ + val progress: Progress? = null, val cards: List = emptyList(), val jobs: List = emptyList(), val metrics: Metrics? = null, @@ -45,7 +47,7 @@ data class LiveReply( "plan" -> copy(plan = decodePlan(data)) - "status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text) } ?: this + "status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text, progress = it.progress) } ?: this "ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this @@ -54,7 +56,7 @@ data class LiveReply( "metrics" -> decode(Metrics.serializer(), data)?.let { copy(metrics = it) } ?: this "done" -> decode(DoneFrame.serializer(), data)?.let { - copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "") + copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "", progress = null) } ?: this "close" -> copy(closed = true) diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index 696c9f9..8780c30 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -477,8 +477,13 @@ data class StepsFrame(val steps: List = emptyList(), val tail: Tail = Tail @Serializable data class SteeredFrame(val ids: List = emptyList()) +/** + * The `status` frame: the free [text] every server sends, and beside it from harness spec 3.4.0 + * the structured [progress] (`progress.md`) -- null when the session is doing nothing, or from + * an older server. A client that reads [progress] draws it and ignores [text]. + */ @Serializable -data class StatusFrame(val text: String = "") +data class StatusFrame(val text: String = "", val progress: Progress? = null) @Serializable data class AskFrame(val cards: List = emptyList()) diff --git a/app/src/main/java/eu/llembas/android/api/Progress.kt b/app/src/main/java/eu/llembas/android/api/Progress.kt new file mode 100644 index 0000000..2cd661a --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Progress.kt @@ -0,0 +1,137 @@ +package eu.llembas.android.api + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import java.util.Locale + +/** + * What a session is doing (harness spec 3.4.0, `progress.md`): one of a fixed set of [phase]s, + * since [since] (Unix milliseconds), with the phase's data. A field that is not known is left + * out by the sender, so every one is optional here, and the text says less without it. + */ +@Serializable +data class Progress( + val phase: String, + val since: Long = 0, + /** queued: turns before it. */ + val ahead: Int? = null, + /** waiting_for_model, loading_model: the model's display name. */ + val model: String? = null, + /** waiting_for_model: busy | slots | group. stopped: person | steps | budget. retrying, failed: the error. */ + val reason: String? = null, + /** reading_prompt: prompt tokens processed, of [total]. */ + val done: Int? = null, + val total: Int? = null, + /** writing: tokens a second. */ + val rate: Double? = null, + /** running_tool: the tool's name; waiting_for_person (approval): the tool asked about. */ + val tool: String? = null, + /** running_tool: the call's short title. waiting_for_person: approval | question | plan. */ + val what: String? = null, + /** waiting_for_subagents: subagents working or waiting. */ + val running: Int? = null, + /** retrying: seconds until the retry, counted down from [since]. */ + @SerialName("in") val inSeconds: Int? = null, + val attempt: Int? = null, +) { + companion object { + /** `loop.json` `progress.no_elapsed`: drawn as their text alone. */ + val NO_ELAPSED = setOf("stopped", "failed") + } +} + +/** + * The shared texts (`loop.json` `progress.texts`, the i18n keys `progress.` …), as this + * app holds them: [text] returns the template for a key with its arguments filled in, or null for + * a key it does not have. The keys are the spec's with `.` as `_`: `queued_ahead`, + * `reason_busy`, `what_approval_bare`, `stopped_reason_person`, `line`. + */ +fun interface ProgressWords { + fun text(key: String, vararg args: String): String? +} + +/** + * The phase's text, its fields filled (`progress.md` §2): numbers as integers, a rate with one + * decimal in [locale]'s format, `retrying`'s `in` counted down to [now]. Null for a phase this + * app does not know -- a newer server's -- so the caller falls back to the `status` text. + */ +fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Locale = Locale.getDefault()): String? { + val p = progress + return when (p.phase) { + "queued" -> if (p.ahead != null) words.text("queued_ahead", "${p.ahead}") else words.text("queued") + + "waiting_for_model" -> { + val model = p.model ?: return null + val why = p.reason?.let { words.text("reason_$it") ?: it } ?: return null + words.text("waiting_for_model", model, why) + } + + "loading_model" -> p.model?.let { words.text("loading_model", it) } + + "reading_prompt" -> { + val done = p.done + val total = p.total + if (done != null && total != null && total > 0) { + words.text("reading_prompt", "$done", "$total", "${done.toLong() * 100 / total}") + } else { + words.text("reading_prompt_bare") + } + } + + "thinking" -> words.text("thinking") + + "writing" -> p.rate?.let { words.text("writing", String.format(locale, "%.1f", it)) } ?: words.text("writing_bare") + + "running_tool" -> { + val tool = p.tool ?: return null + if (!p.what.isNullOrBlank()) words.text("running_tool", tool, p.what.take(80)) else words.text("running_tool_bare", tool) + } + + "waiting_for_person" -> { + val what = when (p.what) { + "approval" -> if (!p.tool.isNullOrBlank()) words.text("what_approval", p.tool) else words.text("what_approval_bare") + null -> null + else -> words.text("what_${p.what}") + } ?: return null + words.text("waiting_for_person", what) + } + + "waiting_for_subagents" -> words.text("waiting_for_subagents", "${p.running ?: 0}") + + "compacting" -> words.text("compacting") + + "retrying" -> { + val left = ((p.inSeconds ?: 0) - ((now - p.since).coerceAtLeast(0) / 1000)).coerceAtLeast(0) + words.text("retrying", "$left", p.reason.orEmpty()) + } + + "stopped" -> { + val why = p.reason?.let { words.text("stopped_reason_$it") } + if (why != null) words.text("stopped_reason", why) else words.text("stopped") + } + + "failed" -> words.text("failed", p.reason.orEmpty()) + + else -> null + } +} + +/** + * The line a client draws (`progress.md` §3): `{{text}} · {{elapsed}}`, or the text alone for + * `stopped` and `failed`. Null when [progressText] is. + */ +fun progressLine(progress: Progress, words: ProgressWords, now: Long, locale: Locale = Locale.getDefault()): String? { + val text = progressText(progress, words, now, locale) ?: return null + if (progress.phase in Progress.NO_ELAPSED) return text + return words.text("line", text, elapsed(now - progress.since)) ?: text +} + +/** Whole seconds as a ticking clock writes a duration: `5s`, `1m 05s`, `1h 02m`. Never negative. */ +fun elapsed(millis: Long): String { + val seconds = millis.coerceAtLeast(0) / 1000 + return when { + seconds < 60 -> "${seconds}s" + seconds < 3600 -> "${seconds / 60}m ${"%02d".format(Locale.ROOT, seconds % 60)}s" + else -> "${seconds / 3600}h ${"%02d".format(Locale.ROOT, (seconds % 3600) / 60)}m" + } +} diff --git a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt index 4db1d55..1c0e74d 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt @@ -89,6 +89,7 @@ import androidx.compose.ui.unit.dp import eu.llembas.android.R import eu.llembas.android.ui.ModelAvatar import eu.llembas.android.ui.chat.Steps +import eu.llembas.android.ui.progressLineOf import eu.llembas.android.ui.theme.LocalPalette import kotlinx.coroutines.launch @@ -470,10 +471,11 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: } if (turn.steps.isNotEmpty()) Steps(turn.steps) val reply = turn.reply + val statusLine = progressLineOf(reply?.progress) ?: reply?.status.orEmpty() when { reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) } - turn.writing && reply?.status?.isNotBlank() == true -> Text(reply.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint) + turn.writing && statusLine.isNotBlank() -> Text(statusLine, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint) last && !turn.writing && turn.steps.isNotEmpty() -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { if (state.canSpeak) { diff --git a/app/src/main/java/eu/llembas/android/ui/ProgressWords.kt b/app/src/main/java/eu/llembas/android/ui/ProgressWords.kt new file mode 100644 index 0000000..8904b8f --- /dev/null +++ b/app/src/main/java/eu/llembas/android/ui/ProgressWords.kt @@ -0,0 +1,89 @@ +package eu.llembas.android.ui + +import android.content.res.Resources +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalInspectionMode +import eu.llembas.android.R +import eu.llembas.android.api.Progress +import eu.llembas.android.api.ProgressWords +import eu.llembas.android.api.progressLine +import eu.llembas.android.api.progressText +import kotlinx.coroutines.delay + +/** The progress texts' resources, by the spec's key (`progress.` with `.` as `_`). */ +private val PROGRESS_STRINGS = mapOf( + "queued" to R.string.progress_queued, + "queued_ahead" to R.string.progress_queued_ahead, + "waiting_for_model" to R.string.progress_waiting_for_model, + "loading_model" to R.string.progress_loading_model, + "reading_prompt" to R.string.progress_reading_prompt, + "reading_prompt_bare" to R.string.progress_reading_prompt_bare, + "thinking" to R.string.progress_thinking, + "writing" to R.string.progress_writing, + "writing_bare" to R.string.progress_writing_bare, + "running_tool" to R.string.progress_running_tool, + "running_tool_bare" to R.string.progress_running_tool_bare, + "waiting_for_person" to R.string.progress_waiting_for_person, + "waiting_for_subagents" to R.string.progress_waiting_for_subagents, + "compacting" to R.string.progress_compacting, + "retrying" to R.string.progress_retrying, + "stopped" to R.string.progress_stopped, + "stopped_reason" to R.string.progress_stopped_reason, + "failed" to R.string.progress_failed, + "reason_busy" to R.string.progress_reason_busy, + "reason_slots" to R.string.progress_reason_slots, + "reason_group" to R.string.progress_reason_group, + "what_approval" to R.string.progress_what_approval, + "what_approval_bare" to R.string.progress_what_approval_bare, + "what_question" to R.string.progress_what_question, + "what_plan" to R.string.progress_what_plan, + "stopped_reason_person" to R.string.progress_stopped_person, + "stopped_reason_steps" to R.string.progress_stopped_steps, + "stopped_reason_budget" to R.string.progress_stopped_budget, + "line" to R.string.progress_line, +) + +/** [ProgressWords] from the app's string resources, in the app's language. */ +fun progressWords(resources: Resources): ProgressWords = ProgressWords { key, args -> + PROGRESS_STRINGS[key]?.let { id -> if (args.isEmpty()) resources.getString(id) else resources.getString(id, *args) } +} + +/** The clock a progress line ticks by: now, again on every whole second. */ +@Composable +fun rememberTick(): Long { + var now by remember { mutableLongStateOf(System.currentTimeMillis()) } + LaunchedEffect(Unit) { + while (true) { + now = System.currentTimeMillis() + delay(1000L - now % 1000L) + } + } + return now +} + +/** In a preview or a screenshot the clock stands still, this long after the phase began. */ +private const val STILL_ELAPSED = 65_000L + +/** + * The progress line to draw for [progress] (`{{text}} · {{elapsed}}`), ticking once a second; + * or the text alone with [withElapsed] false, where a line has no room (a list's row). Null + * when there is no progress, or it is a phase this app does not know: draw `status` then. + */ +@Composable +fun progressLineOf(progress: Progress?, withElapsed: Boolean = true): String? { + progress ?: return null + val resources = LocalContext.current.resources + val locale = LocalConfiguration.current.locales[0] + val words = remember(resources, locale) { progressWords(resources) } + // Under inspection (previews, screenshots) nothing may animate forever, and a shot must be + // the same every time. + val now = if (LocalInspectionMode.current) progress.since + STILL_ELAPSED else rememberTick() + return if (withElapsed) progressLine(progress, words, now, locale) else progressText(progress, words, now, locale) +} diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt index fd14a9b..2ecd338 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt @@ -92,6 +92,7 @@ import eu.llembas.android.R import eu.llembas.android.api.Message import eu.llembas.android.api.ShowCard import eu.llembas.android.ui.ModelAvatar +import eu.llembas.android.ui.progressLineOf import eu.llembas.android.ui.theme.LocalPalette import eu.llembas.android.ui.viewer.FileViewer import kotlinx.coroutines.launch @@ -286,9 +287,12 @@ fun ChatContent( } } } - if (live != null && live.status.isNotBlank()) { + // The 3.4.0 progress line, ticking; the free status text from an older server. + val progressLine = progressLineOf(live?.progress) + val statusLine = progressLine ?: live?.status.orEmpty() + if (live != null && statusLine.isNotBlank()) { Text( - live.status, + statusLine, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 88146d5..0c73ac2 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -222,6 +222,8 @@ Vaše odpověď Něco jiného Odeslat + Přemýšlí + Zastaveno %1$s se ptá: Model uvádí: %1$s Upravit to před spuštěním diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 7dc1ac8..ef2591a 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -222,6 +222,8 @@ Ihre Antwort Etwas anderes Senden + Denkt nach + Angehalten %1$s fragt: Es sagt: %1$s Vor dem Ausführen ändern diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 62f22b6..31bad42 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -222,6 +222,8 @@ Su respuesta Otra cosa Enviar + Pensando + Detenido %1$s pregunta: Dice: %1$s Cambiar esto antes de que se ejecute diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 646f8f8..42e6ed0 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -222,6 +222,8 @@ Votre réponse Autre chose Envoyer + Réflexion + Arrêté %1$s demande : Il dit : %1$s Modifier ceci avant l\'exécution diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 0276c85..54940b6 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -222,6 +222,8 @@ Az Ön válasza Valami más Küldés + Gondolkodás + Leállítva %1$s kérdezi: Ezt mondja: %1$s Módosítás futtatás előtt diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index eda7e26..f161051 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -222,6 +222,8 @@ La tua risposta Altro Invia + Ragionamento + Fermato %1$s chiede: Dice: %1$s Modificalo prima che venga eseguito diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a445636..81f8288 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -222,6 +222,8 @@ Twoja odpowiedź Coś innego Wyślij + Rozumowanie + Zatrzymano %1$s pyta: Mówi: %1$s Zmień to przed uruchomieniem diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index f356eec..41439c3 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -222,6 +222,8 @@ Vaša odpoveď Niečo iné Poslať + Premýšľa + Zastavené %1$s sa pýta: Model uvádza: %1$s Upraviť to pred spustením diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b37e8e5..b90d454 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -223,6 +223,35 @@ Your answer Something else Send + Queued + Queued: %1$s ahead + Waiting for %1$s: %2$s + Loading %1$s + Reading the prompt: %1$s / %2$s tokens (%3$s%%) + Reading the prompt + Thinking + Writing: %1$s tok/s + Writing + Running %1$s: %2$s + Running %1$s + Waiting for you: %1$s + Waiting for subagents: %1$s running + Compacting the conversation + Retrying in %1$s s: %2$s + Stopped + Stopped: %1$s + Failed: %1$s + it serves one request at a time and is answering another + all its slots are in use + its server holds another model now + allow %1$s? + an approval + a question + the plan + by you + step limit + budget + %1$s · %2$s %1$s asks: It says: %1$s Change this before it runs diff --git a/app/src/test/java/eu/llembas/android/ProgressTest.kt b/app/src/test/java/eu/llembas/android/ProgressTest.kt new file mode 100644 index 0000000..c41c53b --- /dev/null +++ b/app/src/test/java/eu/llembas/android/ProgressTest.kt @@ -0,0 +1,98 @@ +package eu.llembas.android + +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.Progress +import eu.llembas.android.api.ProgressWords +import eu.llembas.android.api.elapsed +import eu.llembas.android.api.progressLine +import eu.llembas.android.api.progressText +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.long +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import java.io.File +import java.util.Locale + +/** + * The progress line (harness spec 3.4.0, `progress.md`): the spec's own conformance cases + * (`conformance/progress.json`, the file every client and the server test against), drawn with + * the app's English strings as `res/values/strings.xml` has them -- so a string that drifted + * from `loop.json`'s `progress.texts` fails here too. + */ +class ProgressTest { + /** The app's English, read from the generated resources, formatted as Android formats it. */ + private val english: ProgressWords by lazy { + val xml = File("src/main/res/values/strings.xml").readText() + val strings = Regex("""(.*?)""").findAll(xml) + .associate { it.groupValues[1] to it.groupValues[2].replace("\\'", "'").replace("&", "&") } + val keys = mapOf("stopped_reason_person" to "stopped_person", "stopped_reason_steps" to "stopped_steps", "stopped_reason_budget" to "stopped_budget") + ProgressWords { key, args -> strings[keys[key] ?: key]?.let { String.format(Locale.ROOT, it, *args) } } + } + + private val cases: List by lazy { + // The server's pinned copy (`contract/harness_progress.json`) once it vendors spec 3.4.0; + // until then the spec's own file, copied from LLeMbas CLI 3.4.0 into the test resources. + val loader = javaClass.classLoader!! + val text = requireNotNull(loader.getResource("harness_progress.json") ?: loader.getResource("progress_conformance.json")).readText() + LembasJson.parseToJsonElement(text).jsonObject.getValue("cases").jsonArray.map { it.jsonObject } + } + + @Test + fun everyConformanceCase() { + assertEquals(25, cases.size) + for (case in cases) { + val progress = LembasJson.decodeFromJsonElement(Progress.serializer(), case.getValue("progress")) + val now = case.getValue("now").jsonPrimitive.long + val expect = case.getValue("expect").jsonObject + val about = case["about"]?.jsonPrimitive?.content + assertEquals(about, expect.getValue("text").jsonPrimitive.content, progressText(progress, english, now, Locale.ROOT)) + assertEquals(about, expect.getValue("line").jsonPrimitive.content, progressLine(progress, english, now, Locale.ROOT)) + } + } + + @Test + fun aClockWritesDurations() { + assertEquals("0s", elapsed(-1500)) + assertEquals("59s", elapsed(59_999)) + assertEquals("1m 00s", elapsed(60_000)) + assertEquals("59m 59s", elapsed(3_599_000)) + assertEquals("1h 00m", elapsed(3_600_000)) + assertEquals("26h 03m", elapsed(93_780_000)) + } + + @Test + fun aRateInThePersonsNumberFormat() { + val writing = Progress(phase = "writing", since = 0, rate = 12.46) + assertEquals("Writing: 12,5 tok/s", progressText(writing, english, 0, Locale.forLanguageTag("sk"))) + } + + @Test + fun aPhaseThisAppDoesNotKnowFallsBackToStatus() { + assertNull(progressLine(Progress(phase = "dreaming", since = 0), english, 0)) + // A required field missing: no half sentence, the status text instead. + assertNull(progressLine(Progress(phase = "running_tool", since = 0), english, 0)) + assertNull(progressLine(Progress(phase = "waiting_for_model", since = 0, model = "coder"), english, 0)) + } + + @Test + fun theStatusFrameCarriesProgress() { + val frame = """{"text": "Running bake --slow", "progress": {"phase": "running_tool", "since": 1762790400000, "tool": "bash", "what": "bake --slow"}}""" + val live = LiveReply("m").apply("status", frame) + assertEquals("Running bake --slow", live.status) + assertEquals("bake --slow", live.progress?.what) + // An older server's frame: the text alone, no progress. + val old = live.apply("status", """{"text": "Thinking"}""") + assertEquals("Thinking", old.status) + assertNull(old.progress) + // Idle: progress null. + assertNull(live.apply("status", """{"text": "", "progress": null}""").progress) + // The reply ends: neither is kept. + val done = LembasJson.parseToJsonElement(File("../contract/event_done.json").readText()).toString() + assertNull(live.apply("done", done).progress) + } +} diff --git a/app/src/test/java/eu/llembas/android/shots/Fakes.kt b/app/src/test/java/eu/llembas/android/shots/Fakes.kt index 43f4cfc..c692668 100644 --- a/app/src/test/java/eu/llembas/android/shots/Fakes.kt +++ b/app/src/test/java/eu/llembas/android/shots/Fakes.kt @@ -14,6 +14,7 @@ import eu.llembas.android.api.LiveReply import eu.llembas.android.api.Message import eu.llembas.android.api.Metrics import eu.llembas.android.api.ModelList +import eu.llembas.android.api.Progress import eu.llembas.android.api.RunError import eu.llembas.android.api.RunModel import eu.llembas.android.api.RunResult @@ -183,10 +184,21 @@ object Fakes { /** The last reply while it is being written: its tools done, its words coming in. */ val writing = transcript.copy( messages = listOf(question, answer, packing, packingAnswer.copy(steps = emptyList(), complete = false)), - live = LiveReply(messageId = "m4", steps = packingSteps.take(2), tail = Tail(text = "Here is a list for **three days**, light enough")), + live = LiveReply( + messageId = "m4", + steps = packingSteps.take(2), + tail = Tail(text = "Here is a list for **three days**, light enough"), + status = "Writing", + progress = Progress(phase = "writing", since = 1762790400000, rate = 12.46), + ), summary = null, ) + /** Waiting for a model, the long reason: the progress line at its widest. */ + val waitingForModel = writing.copy( + live = writing.live!!.copy(progress = Progress(phase = "waiting_for_model", since = 1762790400000, model = "Qwen 27B", reason = "busy")), + ) + /** A chat on a model with effort levels, a team and a plan: the tune sheet with everything. */ val tuned = transcript.copy( chat = chat.copy(model = "gpt-oss", effort = "high", mode = "plan", agents = AgentsSetting(1, 4)), diff --git a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt index 3d4afa7..4626d4b 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -88,7 +88,11 @@ class ScreenShots { } @Test - fun writing() = shoot("04-writing") { ChatContent(Fakes.writing, NoChatActions, agent = false) } + fun writing() { + // The 3.4.0 progress line under the reply: `{{text}} · {{elapsed}}`, the clock still. + shoot("04-writing") { ChatContent(Fakes.writing, NoChatActions, agent = false) } + shoot("04-waiting-for-model", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.waitingForModel, NoChatActions, agent = false) } + } @Test fun drawer() { diff --git a/app/src/test/resources/progress_conformance.json b/app/src/test/resources/progress_conformance.json new file mode 100644 index 0000000..6096060 --- /dev/null +++ b/app/src/test/resources/progress_conformance.json @@ -0,0 +1,333 @@ +{ + "about": "Progress (progress.md, spec 3.4.0): the text and the line every client draws for a progress object. `progress`: the object; `now`: the client's clock (Unix ms). Expect `text` — the phase's text from loop.json progress.texts, its fields filled (numbers written plainly: integers as they are, a rate with one decimal) — and `line` — `{{text}} · {{elapsed}}` with elapsed = now − since in whole seconds (5s, 1m 05s, 1h 02m), or the text alone for stopped and failed. retrying's `in` is counted down: in − floor((now − since) / 1000), never below 0. LLeMbas: services/progress.py; CLI: session/progress.ts.", + "cases": [ + { + "about": "Queued, nothing more known.", + "progress": { + "phase": "queued", + "since": 1762790400000 + }, + "now": 1762790405000, + "expect": { + "text": "Queued", + "line": "Queued · 5s" + } + }, + { + "about": "Queued behind two turns.", + "progress": { + "phase": "queued", + "since": 1762790400000, + "ahead": 2 + }, + "now": 1762790465000, + "expect": { + "text": "Queued: 2 ahead", + "line": "Queued: 2 ahead · 1m 05s" + } + }, + { + "about": "A one-request server answering another request.", + "progress": { + "phase": "waiting_for_model", + "since": 1762790400000, + "model": "Qwen 27B", + "reason": "busy" + }, + "now": 1762790412400, + "expect": { + "text": "Waiting for Qwen 27B: it serves one request at a time and is answering another", + "line": "Waiting for Qwen 27B: it serves one request at a time and is answering another · 12s" + } + }, + { + "about": "Every slot taken.", + "progress": { + "phase": "waiting_for_model", + "since": 1762790400000, + "model": "coder", + "reason": "slots" + }, + "now": 1762790401000, + "expect": { + "text": "Waiting for coder: all its slots are in use", + "line": "Waiting for coder: all its slots are in use · 1s" + } + }, + { + "about": "Another model on the one-model server.", + "progress": { + "phase": "waiting_for_model", + "since": 1762790400000, + "model": "coder", + "reason": "group" + }, + "now": 1762790400000, + "expect": { + "text": "Waiting for coder: its server holds another model now", + "line": "Waiting for coder: its server holds another model now · 0s" + } + }, + { + "about": "Loading.", + "progress": { + "phase": "loading_model", + "since": 1762790400000, + "model": "Gemma 12B" + }, + "now": 1762794125000, + "expect": { + "text": "Loading Gemma 12B", + "line": "Loading Gemma 12B · 1h 02m" + } + }, + { + "about": "Reading the prompt: the percentage is floored.", + "progress": { + "phase": "reading_prompt", + "since": 1762790400000, + "done": 1999, + "total": 3000 + }, + "now": 1762790402000, + "expect": { + "text": "Reading the prompt: 1999 / 3000 tokens (66%)", + "line": "Reading the prompt: 1999 / 3000 tokens (66%) · 2s" + } + }, + { + "about": "Reading the prompt with no counts from the server.", + "progress": { + "phase": "reading_prompt", + "since": 1762790400000 + }, + "now": 1762790402000, + "expect": { + "text": "Reading the prompt", + "line": "Reading the prompt · 2s" + } + }, + { + "about": "Thinking.", + "progress": { + "phase": "thinking", + "since": 1762790400000 + }, + "now": 1762790459999, + "expect": { + "text": "Thinking", + "line": "Thinking · 59s" + } + }, + { + "about": "Writing, the rate with one decimal.", + "progress": { + "phase": "writing", + "since": 1762790400000, + "rate": 12.46 + }, + "now": 1762790404000, + "expect": { + "text": "Writing: 12.5 tok/s", + "line": "Writing: 12.5 tok/s · 4s" + } + }, + { + "about": "Writing before a rate is measured.", + "progress": { + "phase": "writing", + "since": 1762790400000 + }, + "now": 1762790400400, + "expect": { + "text": "Writing", + "line": "Writing · 0s" + } + }, + { + "about": "A tool with what it does.", + "progress": { + "phase": "running_tool", + "since": 1762790400000, + "tool": "bash", + "what": "bun test" + }, + "now": 1762790461000, + "expect": { + "text": "Running bash: bun test", + "line": "Running bash: bun test · 1m 01s" + } + }, + { + "about": "A tool without a title.", + "progress": { + "phase": "running_tool", + "since": 1762790400000, + "tool": "recall" + }, + "now": 1762790401000, + "expect": { + "text": "Running recall", + "line": "Running recall · 1s" + } + }, + { + "about": "An approval, naming the tool.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "approval", + "tool": "bash" + }, + "now": 1762790430000, + "expect": { + "text": "Waiting for you: allow bash?", + "line": "Waiting for you: allow bash? · 30s" + } + }, + { + "about": "An approval with no tool named.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "approval" + }, + "now": 1762790400000, + "expect": { + "text": "Waiting for you: an approval", + "line": "Waiting for you: an approval · 0s" + } + }, + { + "about": "A question.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "question" + }, + "now": 1762790403000, + "expect": { + "text": "Waiting for you: a question", + "line": "Waiting for you: a question · 3s" + } + }, + { + "about": "The plan.", + "progress": { + "phase": "waiting_for_person", + "since": 1762790400000, + "what": "plan" + }, + "now": 1762790403000, + "expect": { + "text": "Waiting for you: the plan", + "line": "Waiting for you: the plan · 3s" + } + }, + { + "about": "Subagents.", + "progress": { + "phase": "waiting_for_subagents", + "since": 1762790400000, + "running": 3 + }, + "now": 1762790490000, + "expect": { + "text": "Waiting for subagents: 3 running", + "line": "Waiting for subagents: 3 running · 1m 30s" + } + }, + { + "about": "Compacting.", + "progress": { + "phase": "compacting", + "since": 1762790400000 + }, + "now": 1762790407000, + "expect": { + "text": "Compacting the conversation", + "line": "Compacting the conversation · 7s" + } + }, + { + "about": "Retrying: `in` counts down from since.", + "progress": { + "phase": "retrying", + "since": 1762790400000, + "reason": "502 Bad Gateway", + "in": 10, + "attempt": 2 + }, + "now": 1762790403000, + "expect": { + "text": "Retrying in 7 s: 502 Bad Gateway", + "line": "Retrying in 7 s: 502 Bad Gateway · 3s" + } + }, + { + "about": "Retrying: never below 0.", + "progress": { + "phase": "retrying", + "since": 1762790400000, + "reason": "overloaded", + "in": 2 + }, + "now": 1762790405000, + "expect": { + "text": "Retrying in 0 s: overloaded", + "line": "Retrying in 0 s: overloaded · 5s" + } + }, + { + "about": "Stopped draws no elapsed time.", + "progress": { + "phase": "stopped", + "since": 1762790400000 + }, + "now": 1762790405000, + "expect": { + "text": "Stopped", + "line": "Stopped" + } + }, + { + "about": "Stopped by the person.", + "progress": { + "phase": "stopped", + "since": 1762790400000, + "reason": "person" + }, + "now": 1762790405000, + "expect": { + "text": "Stopped: by you", + "line": "Stopped: by you" + } + }, + { + "about": "Stopped at the step limit.", + "progress": { + "phase": "stopped", + "since": 1762790400000, + "reason": "steps" + }, + "now": 1762790400000, + "expect": { + "text": "Stopped: step limit", + "line": "Stopped: step limit" + } + }, + { + "about": "Failed.", + "progress": { + "phase": "failed", + "since": 1762790400000, + "reason": "connection refused" + }, + "now": 1762790405000, + "expect": { + "text": "Failed: connection refused", + "line": "Failed: connection refused" + } + } + ] +} diff --git a/scripts/fetch-contract.py b/scripts/fetch-contract.py index 6c4231a..db5d3f6 100755 --- a/scripts/fetch-contract.py +++ b/scripts/fetch-contract.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""The server's contract, pinned: `contract/*.json` from `tests/fixtures/api_v2/` at a ref. +"""The server's contract, pinned: `contract/*.json` from `tests/fixtures/api_v2/` at a ref, and +the harness spec's conformance cases the app draws by (`harness_*.json`) from the server's copy. scripts/fetch-contract.py copy the fixtures at that ref, write contract/lock.json scripts/fetch-contract.py verify: contract/ matches contract/lock.json @@ -22,6 +23,10 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent.parent SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas")) SOURCE = "tests/fixtures/api_v2" +# The harness spec's conformance cases a client draws by, from the server's vendored copy of the +# spec at the same ref: `harness_.json` beside the fixtures, once the server has them. +HARNESS = "src/lembas/harness_spec/conformance" +HARNESS_CASES = ("progress.json",) OUT = ROOT / "contract" LOCK = OUT / "lock.json" @@ -56,9 +61,19 @@ def main() -> None: old.unlink() for name in names: (OUT / name).write_text(git("show", f"{commit}:{SOURCE}/{name}"), encoding="utf-8") + have = set(git("ls-tree", "--name-only", f"{commit}:{HARNESS}").split()) if harness_at(commit) else set() + for name in HARNESS_CASES: + if name in have: + (OUT / f"harness_{name}").write_text(git("show", f"{commit}:{HARNESS}/{name}"), encoding="utf-8") + names.append(f"harness_{name}") LOCK.write_text(json.dumps({"ref": ref, "commit": commit, "sha256": digest()}, indent=2) + "\n") print(f"fetch-contract: {len(names)} files from {ref} ({commit[:12]})") +def harness_at(commit: str) -> bool: + found = subprocess.run(["git", "-C", str(SERVER), "cat-file", "-e", f"{commit}:{HARNESS}"], capture_output=True) + return found.returncode == 0 + + if __name__ == "__main__": main() diff --git a/scripts/gen-strings.py b/scripts/gen-strings.py index 070d31b..4c3c408 100755 --- a/scripts/gen-strings.py +++ b/scripts/gen-strings.py @@ -61,15 +61,21 @@ def server_catalogue(code: str, ref: str | None = None) -> dict[str, str]: def numbered(server_english: str, translation: str) -> str: - """A server translation with its named placeholders (`%(n)s`) numbered as Android's - (`%1$s`), in the order the server's English names them. `%%` stays as it is: both write a - percent sign that way.""" + """A server translation with its named placeholders numbered as Android's (`%1$s`), in the + order the server's English names them. Two kinds: `%(n)s`, where `%%` stays as it is (both + write a percent sign that way); and the harness's shared texts' `{{n}}` (the progress + keys, `loop.json` `progress.texts`), which are not %-formatted on the server, so a lone `%` + there becomes Android's `%%`.""" names: list[str] = [] - for name in re.findall(r"%\((\w+)\)s", server_english): + braces = "{{" in server_english + pattern = r"\{\{(\w+)\}\}" if braces else r"%\((\w+)\)s" + for name in re.findall(pattern, server_english): if name not in names: names.append(name) + if braces: + translation = translation.replace("%", "%%") for i, name in enumerate(names, start=1): - translation = translation.replace(f"%({name})s", f"%{i}$s") + translation = translation.replace("{{" + name + "}}" if braces else f"%({name})s", f"%{i}$s") return translation @@ -81,7 +87,7 @@ def server_text(catalogue: dict[str, str], key: str, english: str) -> str | None source = SERVER_ENGLISH.get(key) if source and source in catalogue: text = numbered(source, catalogue[source]) - return None if "%(" in text else text + return None if "%(" in text or "{{" in text else text return None diff --git a/scripts/strings.py b/scripts/strings.py index 91be6ca..86c8bf6 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -240,6 +240,37 @@ STRINGS: dict[str, str] = { "card_answer": "Your answer", "card_something_else": "Something else", "card_send": "Send", + # Progress (harness spec 3.4.0, progress.md; loop.json progress.texts, word for word, with + # Android's placeholders in the order the spec's {{fields}} come) + "progress_queued": "Queued", + "progress_queued_ahead": "Queued: %1$s ahead", + "progress_waiting_for_model": "Waiting for %1$s: %2$s", + "progress_loading_model": "Loading %1$s", + "progress_reading_prompt": "Reading the prompt: %1$s / %2$s tokens (%3$s%%)", + "progress_reading_prompt_bare": "Reading the prompt", + "progress_thinking": "Thinking", + "progress_writing": "Writing: %1$s tok/s", + "progress_writing_bare": "Writing", + "progress_running_tool": "Running %1$s: %2$s", + "progress_running_tool_bare": "Running %1$s", + "progress_waiting_for_person": "Waiting for you: %1$s", + "progress_waiting_for_subagents": "Waiting for subagents: %1$s running", + "progress_compacting": "Compacting the conversation", + "progress_retrying": "Retrying in %1$s s: %2$s", + "progress_stopped": "Stopped", + "progress_stopped_reason": "Stopped: %1$s", + "progress_failed": "Failed: %1$s", + "progress_reason_busy": "it serves one request at a time and is answering another", + "progress_reason_slots": "all its slots are in use", + "progress_reason_group": "its server holds another model now", + "progress_what_approval": "allow %1$s?", + "progress_what_approval_bare": "an approval", + "progress_what_question": "a question", + "progress_what_plan": "the plan", + "progress_stopped_person": "by you", + "progress_stopped_steps": "step limit", + "progress_stopped_budget": "budget", + "progress_line": "%1$s · %2$s", "card_asker": "%1$s asks:", "card_it_says": "It says: %1$s", "card_change_before": "Change this before it runs", @@ -351,6 +382,21 @@ STRINGS: dict[str, str] = { # taken from the server's catalogue and its named placeholders numbered in the order the # English names them -- so "%(steps)s steps, %(tools)s tools" becomes `%1$s`, `%2$s`. SERVER_ENGLISH: dict[str, str] = { + # The progress texts: the server's catalogues key them by the spec's English, {{fields}} and all. + "progress_queued_ahead": "Queued: {{ahead}} ahead", + "progress_waiting_for_model": "Waiting for {{model}}: {{reason}}", + "progress_loading_model": "Loading {{model}}", + "progress_reading_prompt": "Reading the prompt: {{done}} / {{total}} tokens ({{percent}}%)", + "progress_writing": "Writing: {{rate}} tok/s", + "progress_running_tool": "Running {{tool}}: {{what}}", + "progress_running_tool_bare": "Running {{tool}}", + "progress_waiting_for_person": "Waiting for you: {{what}}", + "progress_waiting_for_subagents": "Waiting for subagents: {{running}} running", + "progress_retrying": "Retrying in {{in}} s: {{reason}}", + "progress_stopped_reason": "Stopped: {{reason}}", + "progress_failed": "Failed: {{reason}}", + "progress_what_approval": "allow {{tool}}?", + "progress_line": "{{text}} · {{elapsed}}", "card_asker": "%(job)s asks:", "card_it_says": "It says: %(purpose)s", "activity_used": "%(percent)s%% used",