Display per harness spec 3.7.0: the end line, durations, locale numbers, the cards' actions
CI / check (push) Canceled after 0s

- A reply that was stopped or failed keeps the progress text at its end
  (display.md section 4): "Stopped: by you", "Failed: ...". message.stopped
  was never drawn, and a failure showed the raw error. The reason comes from
  the stream's last status frame and stays with the finished row; a stored
  row gives "Stopped" or "Failed: <first line of its error>".
- A finished tool call shows its duration (0.4s, 1m 05s, 2h 03m) from the
  call's `ms`, where the server sends it; none while running or when denied.
- Counts in the progress line are in the phone's locale format (Locale.ROOT
  is the spec's plain format, which the conformance cases use); a cut `what`
  ends in an ellipsis, counted in code points; the clock is joined with the
  shared progress_line separator.
- Approval card: Allow once / Always allow / Deny / Deny, and say why. Plan
  card: Approve, continue in Edit / in Manual, and Revise.
- fetch-contract.py pins the spec's display.json as harness_display.json
  once the server's copy of the spec has it; DisplayTest then runs its
  duration and end cases.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 10:03:04 +00:00
1 parent f2a2acf996
commit a30075c8f3
22 files changed
+428 -41

No files matched your search

@@ -0,0 +1,88 @@
package eu.llembas.android.api
import java.text.NumberFormat
import java.util.Locale
/*
* One display in every client (harness spec 3.7.0, `display.md`): what this app says about a tool
* call, the end of a reply and a number -- the same things, from the same data, as the web UI,
* Desktop and the CLI.
*/
/** The states that end a turn without finishing it; their line stays on the reply (`display.end`). */
val END_PHASES = setOf("stopped", "failed")
/**
* A call's short title as a line may show it (`display.md` §1, step 4): trimmed, its first line
* only, and cut to [max] code points -- one fewer and `…` -- so a cut title says it was cut.
* Null when nothing is left.
*/
fun shortTitle(text: String?, max: Int = TITLE_MAX): String? {
val line = text?.trim()?.lineSequence()?.firstOrNull()?.trim().orEmpty()
if (line.isEmpty()) return null
if (line.codePointCount(0, line.length) <= max) return line
return line.substring(0, line.offsetByCodePoints(0, max - 1)) + "…"
}
/** `loop.json` `progress.what_max`. */
const val TITLE_MAX = 80
/**
* The state a drawn call is in (`display.md` §2): `running`, `done`, `failed` or `denied`, from
* what `/api/v2` says of it.
*/
fun ToolCall.state(): String = when {
status == "denied" -> "denied"
status == "error" || !error.isNullOrEmpty() -> "failed"
status == "running" || status == "pending" -> "running"
else -> "done"
}
/**
* How long a finished call took (`display.md` §2): tenths under a minute (`0.4s`), then
* `1m 05s`, then `2h 03m`. None for a call that is running or was denied, or whose time was not
* kept. Not a locale number: written with `.` everywhere.
*/
fun callDuration(state: String, ms: Long?): String? {
if (ms == null || state == "running" || state == "denied") return null
val seconds = ms.coerceAtLeast(0) / 1000.0
if (seconds < 60) return String.format(Locale.ROOT, "%.1fs", seconds)
val minutes = (seconds / 60).toLong()
return if (minutes < 60) {
String.format(Locale.ROOT, "%dm %02ds", minutes, (seconds % 60).toLong())
} else {
String.format(Locale.ROOT, "%dh %02dm", minutes / 60, minutes % 60)
}
}
/**
* How a reply ended, when it did not finish (`display.md` §4): the `stopped` or `failed` progress
* whose line stays on it. From the end the stream said (kept on the message as its `progress`,
* with the reason: by you, step limit, budget), else from what the stored row knows -- that it
* was stopped, or its error, of which the first line is the reason. Null for a reply that
* finished, a user's message, or one still queued.
*/
fun Message.end(): Progress? = when {
role != "assistant" -> null
progress?.phase in END_PHASES -> progress
!error.isNullOrBlank() -> Progress(phase = "failed", reason = error.lineSequence().firstOrNull { it.isNotBlank() }?.trim())
stopped -> Progress(phase = "stopped")
else -> null
}
/**
* A count a person reads, in [locale]'s own format -- its grouping and its decimal mark
* (`display.md` §6): `12,480`, `12 480`, `12.480`. [Locale.ROOT] is the spec's plain format, no
* grouping and `.`, which is what its conformance texts are written in.
*/
fun localeNumber(n: Long, locale: Locale): String = if (locale == Locale.ROOT) n.toString() else NumberFormat.getIntegerInstance(locale).format(n)
/** A measure with [decimals] places, in [locale]'s format; plain for [Locale.ROOT]. */
fun localeNumber(n: Double, decimals: Int, locale: Locale): String {
if (locale == Locale.ROOT) return String.format(Locale.ROOT, "%.${decimals}f", n)
val format = NumberFormat.getNumberInstance(locale)
format.minimumFractionDigits = decimals
format.maximumFractionDigits = decimals
format.roundingMode = java.math.RoundingMode.HALF_UP
return format.format(n)
}
@@ -17,6 +17,8 @@ data class LiveReply(
val status: String = "",
/** The structured progress beside [status] (spec 3.4.0); null from an older server, or idle. */
val progress: Progress? = null,
/** How the turn ended when it did not finish: the last `stopped` or `failed` progress, with its reason. */
val end: Progress? = null,
val cards: List<Card> = emptyList(),
val jobs: List<Job> = emptyList(),
/** The subagent tree (spec 3.4.0), from the `tree` frame; null until there is one. */
@@ -49,7 +51,9 @@ data class LiveReply(
"plan" -> copy(plan = decodePlan(data))
"status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text, progress = it.progress) } ?: this
"status" -> decode(StatusFrame.serializer(), data)?.let { frame ->
copy(status = frame.text, progress = frame.progress, end = frame.progress?.takeIf { it.phase in END_PHASES })
} ?: this
"ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this
@@ -59,8 +63,20 @@ 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 = "", progress = null)
"done" -> decode(DoneFrame.serializer(), data)?.let { done ->
// The finished row says that it was stopped or failed; the stream said why (by you,
// the step limit, the budget). The reason goes with the row, where its line stays
// (display.md §4).
val row = done.message
val ended = row.stopped || !row.error.isNullOrBlank()
copy(
finished = if (ended && row.progress == null && end != null) row.copy(progress = end) else row,
title = done.chat.title.ifEmpty { null },
next = done.next,
cards = emptyList(),
status = "",
progress = null,
)
} ?: this
"close" -> copy(closed = true)
@@ -376,6 +376,8 @@ data class ToolCall(
val diff: String? = null,
val exit: Int? = null,
val hits: Int? = null,
/** How long the call took, in milliseconds (spec 3.7.0: `tool_end`'s `ms`); null where it was not kept. */
val ms: Long? = null,
val path: String? = null,
val truncated: Boolean = false,
val job: JsonElement? = null,
@@ -36,7 +36,7 @@ data class Progress(
) {
companion object {
/** `loop.json` `progress.no_elapsed`: drawn as their text alone. */
val NO_ELAPSED = setOf("stopped", "failed")
val NO_ELAPSED = END_PHASES
}
}
@@ -51,14 +51,16 @@ fun interface ProgressWords {
}
/**
* 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.
* The phase's text, its fields filled (`progress.md` §2): every count and measure in [locale]'s
* own number format (`display.md` §6: the phone's grouping and decimal mark; [Locale.ROOT] is the
* spec's plain format), a title that had to be cut ending in `…`, `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")
"queued" -> if (p.ahead != null) words.text("queued_ahead", localeNumber(p.ahead.toLong(), locale)) else words.text("queued")
"waiting_for_model" -> {
val model = p.model ?: return null
@@ -72,7 +74,8 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
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}")
val percent = localeNumber(done.toLong() * 100 / total, locale)
words.text("reading_prompt", localeNumber(done.toLong(), locale), localeNumber(total.toLong(), locale), percent)
} else {
words.text("reading_prompt_bare")
}
@@ -80,11 +83,13 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
"thinking" -> words.text("thinking")
"writing" -> p.rate?.let { words.text("writing", String.format(locale, "%.1f", it)) } ?: words.text("writing_bare")
"writing" -> p.rate?.let { words.text("writing", localeNumber(it, 1, locale)) } ?: 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)
// The call's short title (display.md §1): one line, and `…` where it had to be cut.
val what = shortTitle(p.what)
if (what != null) words.text("running_tool", tool, what) else words.text("running_tool_bare", tool)
}
"waiting_for_person" -> {
@@ -96,7 +101,7 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
words.text("waiting_for_person", what)
}
"waiting_for_subagents" -> words.text("waiting_for_subagents", "${p.running ?: 0}")
"waiting_for_subagents" -> words.text("waiting_for_subagents", localeNumber((p.running ?: 0).toLong(), locale))
"compacting" -> words.text("compacting")
@@ -63,6 +63,9 @@ fun progressWords(resources: Resources): ProgressWords = ProgressWords { key, ar
PROGRESS_STRINGS[key]?.let { id -> if (args.isEmpty()) resources.getString(id) else resources.getString(id, *args) }
}
/** The end of a progress line: the shared `progress.line` separator and [clock], without the text before it. */
fun progressClock(resources: Resources, clock: String): String = resources.getString(R.string.progress_line, "", clock)
/** The clock a progress line ticks by: now, again on every whole second. */
@Composable
fun rememberTick(): Long {
@@ -115,7 +118,8 @@ fun ProgressStatus(progress: Progress?, status: String, style: TextStyle, color:
}
Row(modifier, verticalAlignment = Alignment.Top) {
Text(text, style = style, color = color, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
// The spec's separator, `progress.line`'s " · ", before the clock.
if (clock != null) Text(" · $clock", style = style, color = color, maxLines = 1, softWrap = false)
// The clock after the shared separator: `progress.line` (`{{text}} · {{elapsed}}`) with
// the text left out, so the separator is the spec's and not a copy of it.
if (clock != null) Text(progressClock(LocalContext.current.resources, clock), style = style, color = color, maxLines = 1, softWrap = false)
}
}
@@ -51,6 +51,8 @@ import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.callDuration
import eu.llembas.android.api.state
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.theme.LocalPalette
@@ -107,6 +109,10 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
call.block.chips.forEach { chip ->
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
}
// How long a finished call took (display.md §2); a running or a denied one shows none.
callDuration(call.state(), call.ms)?.let { took ->
Text(took, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, modifier = Modifier.padding(start = 6.dp))
}
}
call.purpose?.takeIf { it.isNotBlank() }?.let {
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
@@ -124,7 +124,9 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
Text(stringResource(R.string.card_allow_always))
}
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny)) }
// The spec's four actions (display.md §5): Deny at once, or with the person's words to the model.
TextButton(onClick = { onAnswer(CardAnswer(verdict = "deny")) }) { Text(stringResource(R.string.card_deny)) }
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny_reason)) }
}
}
}
@@ -204,20 +206,11 @@ private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String
@Composable
private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
val item = card.items.firstOrNull() ?: return
var mode by remember { mutableStateOf("edit") }
var revising by remember { mutableStateOf(false) }
var feedback by remember { mutableStateOf("") }
val plan = item.plan?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
Text(plan?.title?.ifBlank { null } ?: item.title, style = MaterialTheme.typography.titleMedium)
plan?.let { PlanBody(it) }
if (item.modeChoice) {
Row(verticalAlignment = Alignment.CenterVertically) {
RadioButton(selected = mode == "edit", onClick = { mode = "edit" })
Text(stringResource(R.string.mode_edit))
RadioButton(selected = mode == "manual", onClick = { mode = "manual" })
Text(stringResource(R.string.mode_manual))
}
}
if (revising) {
OutlinedTextField(
value = feedback,
@@ -227,15 +220,24 @@ private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
)
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
} else {
// Approve together with the mode the work continues in (display.md §5), where the
// session may choose one; otherwise Approve alone. And Revise.
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = {
onAnswer(CardAnswer(verdict = "allow", choices = if (item.modeChoice) mapOf(item.key to listOf(mode)) else emptyMap()))
}) { Text(stringResource(R.string.plan_approve)) }
OutlinedButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
if (item.modeChoice) {
Button(onClick = { onAnswer(planApproval(item, "edit")) }) { Text(stringResource(R.string.plan_approve_edit)) }
OutlinedButton(onClick = { onAnswer(planApproval(item, "manual")) }) { Text(stringResource(R.string.plan_approve_manual)) }
} else {
Button(onClick = { onAnswer(planApproval(item, null)) }) { Text(stringResource(R.string.plan_approve)) }
}
TextButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
}
}
}
/** A plan's approval as the server reads it: allow, and the mode to continue in where one was chosen. */
internal fun planApproval(item: CardItem, mode: String?): CardAnswer =
CardAnswer(verdict = "allow", choices = if (item.modeChoice && mode != null) mapOf(item.key to listOf(mode)) else emptyMap())
/** A plan's phases and tasks, ticked as the reply works through them. */
@Composable
fun PlanBody(plan: Plan) {
@@ -85,6 +85,7 @@ import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.end
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.Segment
@@ -224,8 +225,16 @@ fun AssistantMessage(
if (writing) {
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
} else {
message.error?.let {
Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 8.dp))
// How a reply that did not finish ended (display.md §4): the progress text alone --
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
// the error colour, a stop muted. Nothing else says it a second time.
message.end()?.let { end ->
Text(
progressLineOf(end, withElapsed = false) ?: message.error.orEmpty(),
color = if (end.phase == "failed") palette.danger else palette.inkMuted,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 8.dp),
)
}
// The actions and the foot share one row: the icons keep their 48 dp, the foot gives.
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Spustit znovu</string>
<string name="card_approval">Povolit to?</string>
<string name="card_allow_once">Povolit jednou</string>
<string name="card_allow_always">Toto vždy povolit</string>
<string name="card_allow_always">Vždy povolit</string>
<string name="card_deny">Zamítnout</string>
<string name="card_deny_reason">Zamítnout a říct proč</string>
<string name="plan_approve_edit">Schválit, pokračovat v režimu Upravit</string>
<string name="plan_approve_manual">Schválit, pokračovat v režimu Ručně</string>
<string name="card_reason">Proč ne? (nepovinné)</string>
<string name="card_recommended">doporučeno</string>
<string name="card_answer">Vaše odpověď</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Erneut ausführen</string>
<string name="card_approval">Das erlauben?</string>
<string name="card_allow_once">Einmal erlauben</string>
<string name="card_allow_always">Dies immer erlauben</string>
<string name="card_allow_always">Immer erlauben</string>
<string name="card_deny">Ablehnen</string>
<string name="card_deny_reason">Ablehnen und begründen</string>
<string name="plan_approve_edit">Bestätigen, weiter im Modus Bearbeiten</string>
<string name="plan_approve_manual">Bestätigen, weiter im Modus Manuell</string>
<string name="card_reason">Warum nicht? (optional)</string>
<string name="card_recommended">empfohlen</string>
<string name="card_answer">Ihre Antwort</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Ejecutar de nuevo</string>
<string name="card_approval">¿Permitir esto?</string>
<string name="card_allow_once">Permitir una vez</string>
<string name="card_allow_always">Permitir siempre esto</string>
<string name="card_allow_always">Permitir siempre</string>
<string name="card_deny">Denegar</string>
<string name="card_deny_reason">Denegar y decir por qué</string>
<string name="plan_approve_edit">Aprobar y continuar en Editar</string>
<string name="plan_approve_manual">Aprobar y continuar en Manual</string>
<string name="card_reason">¿Por qué no? (opcional)</string>
<string name="card_recommended">recomendado</string>
<string name="card_answer">Su respuesta</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Relancer</string>
<string name="card_approval">Autoriser ceci ?</string>
<string name="card_allow_once">Autoriser une fois</string>
<string name="card_allow_always">Toujours autoriser ceci</string>
<string name="card_allow_always">Toujours autoriser</string>
<string name="card_deny">Refuser</string>
<string name="card_deny_reason">Refuser, et dire pourquoi</string>
<string name="plan_approve_edit">Approuver, continuer en mode Modifier</string>
<string name="plan_approve_manual">Approuver, continuer en mode Manuel</string>
<string name="card_reason">Pourquoi pas ? (facultatif)</string>
<string name="card_recommended">recommandé</string>
<string name="card_answer">Votre réponse</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Futtatás újra</string>
<string name="card_approval">Engedélyezzük ezt?</string>
<string name="card_allow_once">Engedélyezés egyszer</string>
<string name="card_allow_always">Ennek mindig engedélyezése</string>
<string name="card_allow_always">Engedélyezés mindig</string>
<string name="card_deny">Elutasítás</string>
<string name="card_deny_reason">Elutasítás indoklással</string>
<string name="plan_approve_edit">Jóváhagyás, folytatás Szerkesztés módban</string>
<string name="plan_approve_manual">Jóváhagyás, folytatás Kézi módban</string>
<string name="card_reason">Miért nem? (opcionális)</string>
<string name="card_recommended">ajánlott</string>
<string name="card_answer">Az Ön válasza</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Esegui di nuovo</string>
<string name="card_approval">Consentire questo?</string>
<string name="card_allow_once">Consenti una volta</string>
<string name="card_allow_always">Consenti sempre questo</string>
<string name="card_allow_always">Consenti sempre</string>
<string name="card_deny">Nega</string>
<string name="card_deny_reason">Nega e spiega perché</string>
<string name="plan_approve_edit">Approva, continua in Modifica</string>
<string name="plan_approve_manual">Approva, continua in Manuale</string>
<string name="card_reason">Perché no? (facoltativo)</string>
<string name="card_recommended">consigliato</string>
<string name="card_answer">La tua risposta</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Uruchom ponownie</string>
<string name="card_approval">Zezwolić na to?</string>
<string name="card_allow_once">Zezwól raz</string>
<string name="card_allow_always">Zawsze na to zezwalaj</string>
<string name="card_allow_always">Zawsze zezwalaj</string>
<string name="card_deny">Odrzuć</string>
<string name="card_deny_reason">Odrzuć i powiedz dlaczego</string>
<string name="plan_approve_edit">Zatwierdź, kontynuuj w trybie Edytuj</string>
<string name="plan_approve_manual">Zatwierdź, kontynuuj w trybie Ręcznie</string>
<string name="card_reason">Czemu nie? (opcjonalnie)</string>
<string name="card_recommended">zalecane</string>
<string name="card_answer">Twoja odpowiedź</string>
+4 -1
View File
@@ -247,8 +247,11 @@
<string name="schedule_run_again">Spustiť znova</string>
<string name="card_approval">Povoliť to?</string>
<string name="card_allow_once">Povoliť raz</string>
<string name="card_allow_always">Toto vždy povoliť</string>
<string name="card_allow_always">Vždy povoliť</string>
<string name="card_deny">Odmietnuť</string>
<string name="card_deny_reason">Odmietnuť a povedať prečo</string>
<string name="plan_approve_edit">Schváliť, pokračovať v režime Upraviť</string>
<string name="plan_approve_manual">Schváliť, pokračovať v režime Ručne</string>
<string name="card_reason">Prečo nie? (nepovinné)</string>
<string name="card_recommended">odporúčané</string>
<string name="card_answer">Vaša odpoveď</string>
+4 -1
View File
@@ -248,8 +248,11 @@
<string name="schedule_run_again">Run again</string>
<string name="card_approval">Allow this?</string>
<string name="card_allow_once">Allow once</string>
<string name="card_allow_always">Always allow this</string>
<string name="card_allow_always">Always allow</string>
<string name="card_deny">Deny</string>
<string name="card_deny_reason">Deny, and say why</string>
<string name="plan_approve_edit">Approve, continue in Edit</string>
<string name="plan_approve_manual">Approve, continue in Manual</string>
<string name="card_reason">Why not? (optional)</string>
<string name="card_recommended">recommended</string>
<string name="card_answer">Your answer</string>
@@ -0,0 +1,181 @@
package eu.llembas.android
import eu.llembas.android.api.CardItem
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.Message
import eu.llembas.android.api.Progress
import eu.llembas.android.api.ProgressWords
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.callDuration
import eu.llembas.android.api.end
import eu.llembas.android.api.localeNumber
import eu.llembas.android.api.progressLine
import eu.llembas.android.api.progressText
import eu.llembas.android.api.shortTitle
import eu.llembas.android.api.state
import eu.llembas.android.ui.chat.planApproval
import kotlinx.serialization.json.JsonNull
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.Assert.assertTrue
import org.junit.Test
import java.io.File
import java.util.Locale
/**
* One display in every client (harness spec 3.7.0, `display.md`), as far as the phone draws it:
* a finished call's duration, the line that stays on a reply that was stopped or failed, a title
* that was cut, and numbers in the phone's format. The values are the spec's own examples; once
* the server's copy of the spec carries `conformance/display.json` it is pinned as
* `contract/harness_display.json` and its `duration` and `end` cases run here too.
*/
class DisplayTest {
private val english: ProgressWords by lazy {
val xml = File("src/main/res/values/strings.xml").readText()
val strings = Regex("""<string name="progress_([a-z_]+)"[^>]*>(.*?)</string>""").findAll(xml)
.associate { it.groupValues[1] to it.groupValues[2].replace("\\'", "'").replace("&amp;", "&") }
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) } }
}
@Test
fun aFinishedCallSaysHowLongItTook() {
assertEquals("0.4s", callDuration("done", 412))
assertEquals("8.4s", callDuration("done", 8_449))
assertEquals("59.9s", callDuration("failed", 59_940))
assertEquals("1m 05s", callDuration("done", 65_000))
assertEquals("2h 03m", callDuration("done", 7_380_000))
assertEquals("1.2s", callDuration("failed", 1_200))
// Never a running call, never a denied one, and none where the time was not kept.
assertNull(callDuration("denied", 3))
assertNull(callDuration("running", 5_000))
assertNull(callDuration("done", null))
// A duration is not a locale number: a decimal point on every phone.
val phone = Locale.getDefault()
try {
Locale.setDefault(Locale.forLanguageTag("sk-SK"))
assertEquals("8.4s", callDuration("done", 8_449))
} finally {
Locale.setDefault(phone)
}
}
@Test
fun aCallIsInOneOfFourStates() {
assertEquals("done", ToolCall(name = "bash", status = "ok").state())
assertEquals("running", ToolCall(name = "bash", status = "running").state())
assertEquals("failed", ToolCall(name = "bash", status = "error").state())
assertEquals("failed", ToolCall(name = "bash", status = "ok", error = "exit 2").state())
assertEquals("denied", ToolCall(name = "bash", status = "denied").state())
// The call's time comes with the call (the link's `ms`), and an older server sends none.
assertEquals(8_449L, LembasJson.decodeFromString(ToolCall.serializer(), """{"name":"bash","status":"ok","ms":8449}""").ms)
assertNull(LembasJson.decodeFromString(ToolCall.serializer(), """{"name":"bash","status":"ok"}""").ms)
}
private fun reply(stopped: Boolean = false, error: String? = null, progress: Progress? = null) =
Message(id = "m", role = "assistant", stopped = stopped, error = error, progress = progress)
private fun line(message: Message): String? = message.end()?.let { progressText(it, english, 0, Locale.ROOT) }
@Test
fun aReplyThatDidNotFinishKeepsItsLine() {
assertEquals("Stopped: by you", line(reply(stopped = true, progress = Progress(phase = "stopped", reason = "person"))))
assertEquals("Stopped: step limit", line(reply(stopped = true, progress = Progress(phase = "stopped", reason = "steps"))))
assertEquals("Stopped: budget", line(reply(stopped = true, progress = Progress(phase = "stopped", reason = "budget"))))
// A stored row knows that it was stopped, not why: the line without a reason.
assertEquals("Stopped", line(reply(stopped = true)))
// An error: its first line is the reason, and the line is the spec's, not the raw text.
assertEquals("Failed: 502 Bad Gateway", line(reply(error = "502 Bad Gateway\n at upstream")))
// A reply that finished shows nothing; nor does a user's message, or one that is only queued.
assertNull(reply().end())
assertNull(Message(id = "u", role = "user", stopped = true).end())
assertNull(reply(progress = Progress(phase = "queued", ahead = 1)).end())
}
@Test
fun theStreamsReasonStaysWithTheFinishedReply() {
val stopped = """{"text": "", "progress": {"phase": "stopped", "since": 1767323045000, "reason": "person"}}"""
val done = LembasJson.parseToJsonElement(File("../contract/event_done.json").readText()).jsonObject
fun doneWith(change: (MutableMap<String, kotlinx.serialization.json.JsonElement>) -> Unit): String {
val message = done.getValue("message").jsonObject.toMutableMap().also(change)
return JsonObject(done + ("message" to JsonObject(message))).toString()
}
// Stopped by the person: the stream said why, the row only that it was stopped.
val live = LiveReply("msg2").apply("status", stopped)
val ended = live.apply("done", doneWith { it["stopped"] = kotlinx.serialization.json.JsonPrimitive(true) })
assertNull(ended.progress)
assertEquals("Stopped: by you", line(ended.finished!!))
// A reply that finished after all keeps nothing of an earlier stop.
assertNull(live.apply("done", doneWith { }).finished!!.end())
// The phase moved on before the end (a retry that then worked): no end is remembered.
val moved = live.apply("status", """{"text": "Writing", "progress": {"phase": "writing", "since": 1}}""")
assertNull(moved.end)
assertTrue(done.getValue("message").jsonObject["error"] is JsonNull)
}
@Test
fun aTitleThatWasCutSaysSo() {
assertEquals("bake --slow", shortTitle(" bake --slow\n--and more "))
assertNull(shortTitle(" "))
assertNull(shortTitle(null))
val long = "x".repeat(81)
assertEquals("x".repeat(79) + "…", shortTitle(long))
assertEquals("x".repeat(80), shortTitle("x".repeat(80)))
// Counted in code points: a character outside the basic plane is one, and is never split.
val leaves = "\uD83C\uDF43".repeat(81)
assertEquals("\uD83C\uDF43".repeat(79) + "…", shortTitle(leaves))
val running = Progress(phase = "running_tool", since = 0, tool = "bash", what = long)
assertEquals("Running bash: ${"x".repeat(79)}… · 0s", progressLine(running, english, 0, Locale.ROOT))
}
@Test
fun numbersAreInThePhonesFormat() {
val reading = Progress(phase = "reading_prompt", since = 0, done = 12_480, total = 32_000)
assertEquals("Reading the prompt: 12480 / 32000 tokens (39%)", progressText(reading, english, 0, Locale.ROOT))
assertEquals("Reading the prompt: 12,480 / 32,000 tokens (39%)", progressText(reading, english, 0, Locale.US))
assertEquals("Reading the prompt: 12.480 / 32.000 tokens (39%)", progressText(reading, english, 0, Locale.GERMANY))
assertEquals("Writing: 1.234,5 tok/s", progressText(Progress(phase = "writing", since = 0, rate = 1234.46), english, 0, Locale.GERMANY))
assertEquals("Queued: 1,200 ahead", progressText(Progress(phase = "queued", since = 0, ahead = 1200), english, 0, Locale.US))
assertEquals("12480", localeNumber(12_480, Locale.ROOT))
assertEquals("12.5", localeNumber(12.46, 1, Locale.ROOT))
}
@Test
fun aPlanIsApprovedWithTheModeToContinueIn() {
val choose = CardItem(key = "p0", kind = "plan", modeChoice = true)
assertEquals(mapOf("p0" to listOf("edit")), planApproval(choose, "edit").choices)
assertEquals(mapOf("p0" to listOf("manual")), planApproval(choose, "manual").choices)
assertEquals("allow", planApproval(choose, "manual").verdict)
// A session that may not choose a mode approves the plan alone.
assertTrue(planApproval(CardItem(key = "p0", kind = "plan", modeChoice = false), null).choices.isEmpty())
}
@Test
fun theSpecsOwnCasesOnceTheyArePinned() {
val file = javaClass.classLoader!!.getResource("harness_display.json") ?: return
val cases = LembasJson.parseToJsonElement(file.readText()).jsonObject.getValue("cases").jsonArray.map { it.jsonObject }
for (case in cases) {
val about = case["about"]?.jsonPrimitive?.content
val expect = case.getValue("expect").jsonObject
when (case.getValue("show").jsonPrimitive.content) {
"duration" -> {
val want = expect.getValue("duration").let { if (it is JsonNull) null else it.jsonPrimitive.content }
assertEquals(about, want, callDuration(case.getValue("state").jsonPrimitive.content, case["ms"]?.jsonPrimitive?.long))
}
"end" -> {
val progress = case.getValue("progress").let { if (it is JsonNull) null else LembasJson.decodeFromJsonElement(Progress.serializer(), it) }
val want = expect.getValue("line").let { if (it is JsonNull) null else it.jsonPrimitive.content }
val message = Message(id = "m", role = "assistant", progress = progress)
assertEquals(about, want, message.end()?.let { progressLine(it, english, case.getValue("now").jsonPrimitive.long, Locale.ROOT) })
}
}
}
}
}