API: model levels and pictures, team size, the activity panel's routes
ModelInfo reads levels, the start level, the control, thinking_switch,
parallel and the picture (fetched with the token, only from the instance's
own /api/v2/models/images/). Chat reads agents {min, max} and
device_session_id. The activity, agent, team and stop routes, the events
route followed by StreamClient.watch, and ActivityLogic for the panel's
numbers. ActivityTest parses the new fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
5 files changed
+588
-4
No files matched your search
@@ -0,0 +1,73 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The activity panel's arithmetic, apart from the screen so the tests can hold it: the numbers
|
||||
* are written as the server writes them (`compact_tokens`, `jobs.duration`), and the strip's
|
||||
* line counts what the web's strip counts.
|
||||
*/
|
||||
object ActivityLogic {
|
||||
/** A token count at a glance: 950, 14.2k, 180k, 1.54M (the server's `compact_tokens`). */
|
||||
fun compactTokens(value: Int): String {
|
||||
val n = value.coerceAtLeast(0)
|
||||
return when {
|
||||
n < 1000 -> n.toString()
|
||||
n < 100_000 -> trim(String.format(Locale.ROOT, "%.1f", n / 1000.0)) + "k"
|
||||
n < 1_000_000 -> "${Math.round(n / 1000.0)}k"
|
||||
else -> trim(String.format(Locale.ROOT, "%.2f", n / 1_000_000.0)) + "M"
|
||||
}
|
||||
}
|
||||
|
||||
private fun trim(number: String): String = if ('.' in number) number.trimEnd('0').trimEnd('.') else number
|
||||
|
||||
/** A duration as both the server and the CLI write it: `5s`, `1m 05s`, `2h 03m`. */
|
||||
fun duration(seconds: Long): String {
|
||||
val total = seconds.coerceAtLeast(0)
|
||||
if (total < 60) return "${total}s"
|
||||
val minutes = total / 60
|
||||
val rest = total % 60
|
||||
if (minutes < 60) return String.format(Locale.ROOT, "%dm %02ds", minutes, rest)
|
||||
return String.format(Locale.ROOT, "%dh %02dm", minutes / 60, minutes % 60)
|
||||
}
|
||||
|
||||
/**
|
||||
* How long an agent has run now: the server's count when it was read, plus the time since
|
||||
* for one that is still going. A queued one has not started, and an ended one has stopped
|
||||
* counting.
|
||||
*/
|
||||
fun elapsed(agent: ActivityAgent, readAtMillis: Long, nowMillis: Long): Long {
|
||||
val going = agent.state == "working" || agent.state == "waiting"
|
||||
val since = if (going) ((nowMillis - readAtMillis) / 1000).coerceAtLeast(0) else 0
|
||||
return agent.seconds + since
|
||||
}
|
||||
|
||||
/**
|
||||
* What the strip above the composer says, as counts in order: agents working, queued,
|
||||
* waiting. Empty when nothing is going -- then there is no strip.
|
||||
*/
|
||||
fun stripCounts(summary: ActivitySummary): List<Pair<String, Int>> =
|
||||
listOf("working" to summary.working, "queued" to summary.queued, "waiting" to summary.waiting).filter { it.second > 0 }
|
||||
|
||||
/** The top level split as the panel shows it: those still going, then the ended ones. */
|
||||
fun split(agents: List<ActivityAgent>): Pair<List<ActivityAgent>, List<ActivityAgent>> = agents.partition { it.isActive }
|
||||
|
||||
/** Every agent of a forest with its helpers under it, in tree order, for drawing as rows. */
|
||||
fun flatten(agents: List<ActivityAgent>): List<ActivityAgent> = agents.flatMap { listOf(it) + flatten(it.children) }
|
||||
|
||||
/**
|
||||
* The context's bar: one segment per category with tokens, `free` left out (it is the
|
||||
* empty end of the bar). Nothing at all when the window is unknown.
|
||||
*/
|
||||
fun barParts(context: ContextUse): List<ContextPart> {
|
||||
if (context.limit <= 0) return emptyList()
|
||||
return context.categories.filter { it.key != "free" && it.tokens > 0 }
|
||||
}
|
||||
|
||||
/** The plan the panel shows, read leniently: a plan that does not parse is no plan. */
|
||||
fun plan(json: JsonObject?): Plan? = json?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
|
||||
|
||||
/** A percentage as the server writes it: one decimal, none when it is whole. */
|
||||
fun percent(value: Double): String = trim(String.format(Locale.ROOT, "%.1f", value))
|
||||
}
|
||||
@@ -100,6 +100,11 @@ class Doorstep(private val http: OkHttpClient = SharedHttp) {
|
||||
private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build()
|
||||
}
|
||||
|
||||
private fun agentsJson(agents: AgentsSetting) = buildJsonObject {
|
||||
put("min", agents.min)
|
||||
put("max", agents.max)
|
||||
}
|
||||
|
||||
internal fun detail(response: Response): String {
|
||||
val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
val said = runCatching {
|
||||
@@ -172,6 +177,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
effort: String? = null,
|
||||
mode: String? = null,
|
||||
agent: AgentTarget? = null,
|
||||
agents: AgentsSetting? = null,
|
||||
): NewChat = send(
|
||||
"POST",
|
||||
"/chats",
|
||||
@@ -181,6 +187,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
model?.let { put("model", it) }
|
||||
effort?.let { put("effort", it) }
|
||||
mode?.let { put("mode", it) }
|
||||
agents?.let { put("agents", agentsJson(it)) }
|
||||
put("temporary", temporary)
|
||||
// An agent chat runs on a linked device; an empty directory is the device's first
|
||||
// allowed one. A device that is no longer linked makes it an ordinary chat on the
|
||||
@@ -204,6 +211,9 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun updateChat(chatId: String, changes: JsonObject): Chat = send<ChatEnvelope>("PATCH", "/chats/$chatId", changes).chat
|
||||
|
||||
/** The team's size, both ends at once: the server checks the pair (422 outside its bounds). */
|
||||
suspend fun setAgents(chatId: String, agents: AgentsSetting): Chat = updateChat(chatId, buildJsonObject { put("agents", agentsJson(agents)) })
|
||||
|
||||
suspend fun deleteChat(chatId: String) = empty(authed("$v2/chats/$chatId").delete().build())
|
||||
|
||||
suspend fun stop(chatId: String, messageId: String) =
|
||||
@@ -223,6 +233,46 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
empty(authed("$v2/chats/$chatId/interactions/$cardId").post(body).build())
|
||||
}
|
||||
|
||||
// --- The activity panel, background agents and the team -----------------------------------
|
||||
|
||||
/** Everything the panel shows; `context = false` leaves out the costly context count. */
|
||||
suspend fun activity(chatId: String, context: Boolean = true): Activity = get<ActivityEnvelope>("/chats/$chatId/activity?context=$context").activity
|
||||
|
||||
/** The events route: an `activity` frame whenever the panel's facts change. */
|
||||
fun activityEvents(chatId: String): Request = authed("$v2/chats/$chatId/activity/events").header("Accept", "text/event-stream").build()
|
||||
|
||||
/** One background agent and its whole conversation, read-only. `kind` is `member` or `job`. */
|
||||
suspend fun agent(chatId: String, kind: String, id: String): AgentDetail = get("/chats/$chatId/agents/${segment(kind)}/${segment(id)}")
|
||||
|
||||
/** Stop a background agent (a member leaves the team with those under it). */
|
||||
suspend fun stopAgent(chatId: String, kind: String, id: String): List<String> =
|
||||
send<Stopped>("POST", "/chats/$chatId/agents/${segment(kind)}/${segment(id)}/stop", null).stopped
|
||||
|
||||
suspend fun team(chatId: String, since: Int = 0): TeamView = get<TeamEnvelope>("/chats/$chatId/team?since=$since").team
|
||||
|
||||
suspend fun stopMember(chatId: String, name: String): List<String> = send<Stopped>("POST", "/chats/$chatId/team/${segment(name)}/stop", null).stopped
|
||||
|
||||
// --- Model pictures --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A model's picture, with the token: only a path under the instance's own
|
||||
* `/api/v2/models/images/` is fetched -- a list that named anything else, another host
|
||||
* included, gets the initial instead. At most [IMAGE_MAX_BYTES]; null when there is none.
|
||||
*/
|
||||
suspend fun modelImage(path: String): ByteArray? = withContext(Dispatchers.IO) {
|
||||
val url = modelImageUrl(base, path) ?: return@withContext null
|
||||
http.newCall(authed(url).header("Accept", "image/*").get().build()).await().use {
|
||||
if (!it.isSuccessful) return@use null
|
||||
val body = it.body ?: return@use null
|
||||
if (body.contentLength() > IMAGE_MAX_BYTES) return@use null
|
||||
val bytes = body.source().use { source ->
|
||||
source.request(IMAGE_MAX_BYTES + 1)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, IMAGE_MAX_BYTES + 1))
|
||||
}
|
||||
bytes.takeIf { b -> b.size <= IMAGE_MAX_BYTES }
|
||||
}
|
||||
}
|
||||
|
||||
// --- Attachments -------------------------------------------------------------------------
|
||||
suspend fun upload(name: String, mime: String, bytes: ByteArray, chatId: String? = null): Attachment {
|
||||
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||
@@ -337,5 +387,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
const val SHOWN_MAX_BYTES = 1_100_000L
|
||||
|
||||
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
|
||||
|
||||
/** A model's picture is small; anything larger is not one. */
|
||||
const val IMAGE_MAX_BYTES = 2_000_000L
|
||||
|
||||
private const val IMAGE_PATH = "/api/v2/models/images/"
|
||||
|
||||
/** The picture's URL on [base], or null for a path that is not one of the instance's pictures. */
|
||||
fun modelImageUrl(base: String, path: String?): String? {
|
||||
if (path.isNullOrBlank() || !path.startsWith(IMAGE_PATH)) return null
|
||||
val name = path.removePrefix(IMAGE_PATH)
|
||||
if (name.isEmpty() || !name.all { it.isLetterOrDigit() || it == '.' || it == '_' || it == '-' } || name.startsWith(".")) return null
|
||||
return "$base$IMAGE_PATH$name"
|
||||
}
|
||||
|
||||
/** One path segment, escaped: an agent's name or a job's id is a model's choice. */
|
||||
fun segment(value: String): String = java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||
}
|
||||
}
|
||||
@@ -81,9 +81,54 @@ data class ModelInfo(
|
||||
val vision: Boolean = false,
|
||||
val tools: Boolean = false,
|
||||
val efforts: List<String> = emptyList(),
|
||||
/** Whether the model's server stops thinking when asked: only then is `off` a level. */
|
||||
@SerialName("thinking_switch") val thinkingSwitch: Boolean = false,
|
||||
/** The levels a chat offers, in order (harness spec 3.2.0): `off` first when switchable. */
|
||||
val levels: List<String> = emptyList(),
|
||||
/** The level a chat starts at when none was chosen. */
|
||||
val effort: String = "",
|
||||
/** How the level is chosen: `none`, `switch` (Thinking on or off) or `slider`. */
|
||||
val control: String = "",
|
||||
/** How many requests the model's server answers at once; null for no stated limit. */
|
||||
val parallel: Int? = null,
|
||||
val context: Int = 0,
|
||||
/** The picture's path on the instance (`/api/v2/models/images/…`), read with the token. */
|
||||
val image: String? = null,
|
||||
val default: Boolean = false,
|
||||
)
|
||||
) {
|
||||
/**
|
||||
* The levels, for a server that says them; an older one said only `efforts`, offered after
|
||||
* an `off` that meant "the model's default" -- as the app showed it before.
|
||||
*/
|
||||
val offered: List<String> get() = levels.ifEmpty { if (efforts.isEmpty()) emptyList() else listOf("off") + efforts }
|
||||
|
||||
/** Which control the composer draws, by the server's word or, from an older one, by the count. */
|
||||
val levelControl: String
|
||||
get() = control.takeIf { it in CONTROLS } ?: when {
|
||||
offered.size <= 1 -> "none"
|
||||
offered.size == 2 && "off" in offered -> "switch"
|
||||
else -> "slider"
|
||||
}
|
||||
|
||||
/** The level in force: [chosen] when this model offers it, else its start level. */
|
||||
fun level(chosen: String?): String =
|
||||
chosen?.takeIf { it in offered } ?: effort.takeIf { it in offered } ?: offered.firstOrNull { it != "off" } ?: offered.firstOrNull().orEmpty()
|
||||
|
||||
/** For the Thinking switch: the level that is "on" (the one that is not `off`). */
|
||||
val onLevel: String get() = offered.firstOrNull { it != "off" } ?: effort
|
||||
|
||||
/**
|
||||
* Whether a new chat on this model may have a team, as far as the app can tell: the model
|
||||
* serves two requests at once (`parallel` ≥ 2, or no stated limit) and takes tools. The
|
||||
* server also needs subagents on, which only an existing chat's activity says
|
||||
* (`team_offered`); a setting it does not use is kept and does nothing.
|
||||
*/
|
||||
val mayHaveTeam: Boolean get() = tools && (parallel == null || parallel >= 2)
|
||||
|
||||
companion object {
|
||||
val CONTROLS = setOf("none", "switch", "slider")
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ModelList(val models: List<ModelInfo> = emptyList())
|
||||
@@ -118,15 +163,28 @@ data class Chat(
|
||||
val mode: String = "",
|
||||
val effort: String? = null,
|
||||
val device: Device? = null,
|
||||
/** An agent chat's session on its device (`lembas -s <id>` continues it); null until opened. */
|
||||
@SerialName("device_session_id") val deviceSessionId: String? = null,
|
||||
@SerialName("parent_chat_id") val parentChatId: String? = null,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@SerialName("system_prompt") val systemPrompt: String? = null,
|
||||
val plan: JsonObject? = null,
|
||||
/** The team's size: how many agents, its own included, the chat may have. */
|
||||
val agents: AgentsSetting? = null,
|
||||
) {
|
||||
val isAgent: Boolean get() = kind == "agent"
|
||||
}
|
||||
|
||||
/** A chat's `agents {min, max}` (harness spec 3.2.0): `1 ≤ min ≤ max ≤` the instance's cap. */
|
||||
@Serializable
|
||||
data class AgentsSetting(val min: Int = 1, val max: Int = 4) {
|
||||
companion object {
|
||||
/** The spec's default cap; an instance may set it lower, and then refuses past it (422). */
|
||||
const val CAP = 32
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@@ -429,3 +487,179 @@ data class PushPayload(
|
||||
@SerialName("interaction_id") val interactionId: String? = null,
|
||||
val ask: String? = null,
|
||||
)
|
||||
|
||||
// --- The activity panel (`GET /chats/{chat}/activity`) -------------------------------------
|
||||
|
||||
/** How many background agents are in each state, and the three sums the strip shows. */
|
||||
@Serializable
|
||||
data class ActivitySummary(
|
||||
val queued: Int = 0,
|
||||
val working: Int = 0,
|
||||
val waiting: Int = 0,
|
||||
val done: Int = 0,
|
||||
val stopped: Int = 0,
|
||||
val error: Int = 0,
|
||||
val active: Int = 0,
|
||||
val finished: Int = 0,
|
||||
val total: Int = 0,
|
||||
)
|
||||
|
||||
/** An agent's latest step: the tool it called and on what. */
|
||||
@Serializable
|
||||
data class AgentStep(val tool: String = "", val label: String = "", val title: String = "", val error: Boolean = false, val running: Boolean = false)
|
||||
|
||||
/**
|
||||
* One background agent: a team's member (`kind` member, [id] its name) or a job (`kind` job;
|
||||
* [type] `subagent` or `command`), with its own helpers in [children]. [role], [brief] and
|
||||
* [text] are a model's words: shown as text, never as anything richer.
|
||||
*/
|
||||
@Serializable
|
||||
data class ActivityAgent(
|
||||
val kind: String = "",
|
||||
val id: String = "",
|
||||
val type: String = "",
|
||||
val name: String = "",
|
||||
val role: String = "",
|
||||
val brief: String = "",
|
||||
val state: String = "",
|
||||
val seconds: Int = 0,
|
||||
val started: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val manager: String? = null,
|
||||
val depth: Int = 0,
|
||||
val lead: Boolean = false,
|
||||
val step: AgentStep? = null,
|
||||
val text: String = "",
|
||||
val steps: Int = 0,
|
||||
val tools: Int = 0,
|
||||
val stoppable: Boolean = false,
|
||||
val transcript: Boolean = false,
|
||||
val children: List<ActivityAgent> = emptyList(),
|
||||
) {
|
||||
/** Still to come back: queued, working or waiting. */
|
||||
val isActive: Boolean get() = state in ACTIVE
|
||||
|
||||
companion object {
|
||||
val ACTIVE = setOf("queued", "working", "waiting")
|
||||
}
|
||||
}
|
||||
|
||||
/** One message in a team's room. [text] is a model's: rendered as untrusted markdown. */
|
||||
@Serializable
|
||||
data class RoomMessage(
|
||||
val n: Int = 0,
|
||||
val from: String = "",
|
||||
val to: List<String> = emptyList(),
|
||||
val text: String = "",
|
||||
val report: Boolean = false,
|
||||
val created: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ActivityTeam(
|
||||
val min: Int = 1,
|
||||
val max: Int = 1,
|
||||
val size: Int = 0,
|
||||
val goal: String = "",
|
||||
val room: List<RoomMessage> = emptyList(),
|
||||
val cursor: Int = 0,
|
||||
)
|
||||
|
||||
/** One category of the context: `messages`, `system`, `memory`, … and `free`. */
|
||||
@Serializable
|
||||
data class ContextPart(val key: String = "", val tokens: Int = 0, val percent: Double? = null)
|
||||
|
||||
@Serializable
|
||||
data class ContextUse(
|
||||
val used: Int = 0,
|
||||
val limit: Int = 0,
|
||||
val percent: Double? = null,
|
||||
val measured: Boolean = false,
|
||||
val threshold: Int = 0,
|
||||
@SerialName("tools_count") val toolsCount: Int = 0,
|
||||
@SerialName("mcp_count") val mcpCount: Int = 0,
|
||||
val categories: List<ContextPart> = emptyList(),
|
||||
)
|
||||
|
||||
/** A file the chat or its agents wrote: lines added and removed when known. */
|
||||
@Serializable
|
||||
data class Output(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val writes: Int = 0,
|
||||
val created: Boolean = false,
|
||||
val added: Int? = null,
|
||||
val removed: Int? = null,
|
||||
val at: String = "",
|
||||
)
|
||||
|
||||
/** Everything the activity panel shows. [version] changes whenever any of it but the elapsed time does. */
|
||||
@Serializable
|
||||
data class Activity(
|
||||
val version: String = "",
|
||||
val summary: ActivitySummary = ActivitySummary(),
|
||||
val agents: List<ActivityAgent> = emptyList(),
|
||||
val team: ActivityTeam? = null,
|
||||
@SerialName("team_offered") val teamOffered: Boolean = false,
|
||||
val context: ContextUse? = null,
|
||||
val outputs: List<Output> = emptyList(),
|
||||
val plan: JsonObject? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ActivityEnvelope(val activity: Activity)
|
||||
|
||||
/** The events route's frame: what changed is fetched with `GET /activity`. */
|
||||
@Serializable
|
||||
data class ActivityFrame(val version: String = "", val summary: ActivitySummary = ActivitySummary())
|
||||
|
||||
/** A tool call in an agent's conversation: its name and what it was on. */
|
||||
@Serializable
|
||||
data class TurnTool(val name: String = "", val title: String = "", val isError: Boolean = false)
|
||||
|
||||
/** One turn of a background agent's conversation. `machine`: a message the system gave it. */
|
||||
@Serializable
|
||||
data class AgentTurn(
|
||||
val role: String = "",
|
||||
val text: String = "",
|
||||
val machine: Boolean = false,
|
||||
val tools: List<TurnTool> = emptyList(),
|
||||
val error: String = "",
|
||||
val running: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class AgentDetail(val agent: ActivityAgent, val transcript: List<AgentTurn> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Stopped(val stopped: List<String> = emptyList())
|
||||
|
||||
/** One agent of a team's tree (`GET /chats/{chat}/team`). */
|
||||
@Serializable
|
||||
data class TeamAgent(
|
||||
val name: String = "",
|
||||
val manager: String? = null,
|
||||
val role: String = "",
|
||||
val state: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val lead: Boolean = false,
|
||||
val depth: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TeamView(
|
||||
val offered: Boolean = false,
|
||||
val min: Int = 1,
|
||||
val max: Int = 1,
|
||||
val size: Int = 0,
|
||||
val parallel: Int? = null,
|
||||
val goal: String = "",
|
||||
val agents: List<TeamAgent> = emptyList(),
|
||||
val room: List<RoomMessage> = emptyList(),
|
||||
val cursor: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TeamEnvelope(val team: TeamView)
|
||||
@@ -5,6 +5,7 @@ import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.sse.EventSource
|
||||
import okhttp3.sse.EventSourceListener
|
||||
@@ -31,7 +32,7 @@ class StreamClient(private val api: ApiClient) {
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(chatId, messageId).collect { result ->
|
||||
once(api.streamRequest(chatId, messageId)).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
@@ -51,15 +52,45 @@ class StreamClient(private val api: ApiClient) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow an events route that ends itself now and then (`close` after a while, as the
|
||||
* activity panel's does): opened again at once after a `close`, and after a pause that
|
||||
* grows to 30 seconds when the connection drops. It runs until its collector stops; a
|
||||
* refusal (4xx) ends it with the error.
|
||||
*/
|
||||
fun watch(request: () -> Request): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(request()).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
if (result.frame.event == "close") closed = true else emit(result.frame)
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) continue
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
private fun once(chatId: String, messageId: String): Flow<Outcome> = callbackFlow {
|
||||
private fun once(request: Request): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
api.streamRequest(chatId, messageId),
|
||||
request,
|
||||
object : EventSourceListener() {
|
||||
override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
|
||||
trySend(Outcome.Event(Frame(type ?: "message", data)))
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ActivityEnvelope
|
||||
import eu.llembas.android.api.ActivityFrame
|
||||
import eu.llembas.android.api.ActivityLogic
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentDetail
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ContextUse
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.TeamEnvelope
|
||||
import kotlinx.serialization.KSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The beta.5 `/api/v2` (server dev, pinned in `contract/`): the models' levels and pictures, a
|
||||
* chat's team size, and the activity panel -- parsed with the app's models, then the panel's
|
||||
* arithmetic on what they said.
|
||||
*/
|
||||
class ActivityTest {
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T {
|
||||
val text = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
return LembasJson.decodeFromString(serializer, text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theModelsSayTheirLevelsAndControl() {
|
||||
val (qwen, gptOss, vision) = read("models", ModelList.serializer()).models
|
||||
assertEquals(listOf("off", "medium"), qwen.offered)
|
||||
assertEquals("switch", qwen.levelControl)
|
||||
assertTrue(qwen.thinkingSwitch)
|
||||
assertEquals("medium", qwen.onLevel)
|
||||
assertEquals(2, qwen.parallel)
|
||||
assertEquals("/api/v2/models/images/0a1b2c3d4e5f.png", qwen.image)
|
||||
assertTrue(qwen.mayHaveTeam)
|
||||
|
||||
assertEquals("slider", gptOss.levelControl)
|
||||
assertEquals("high", gptOss.level(null))
|
||||
assertEquals("low", gptOss.level("low"))
|
||||
// A level the model does not offer (an `off` from before) reads as its start level.
|
||||
assertEquals("high", gptOss.level("off"))
|
||||
assertFalse(gptOss.mayHaveTeam)
|
||||
assertNull(gptOss.image)
|
||||
|
||||
assertEquals("none", vision.levelControl)
|
||||
assertEquals("default", vision.level(null))
|
||||
// No stated limit, but no tools: no team.
|
||||
assertNull(vision.parallel)
|
||||
assertFalse(vision.mayHaveTeam)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOlderServersModelStillGetsAControl() {
|
||||
// Before beta.5: `efforts` only. The app offered "off" before them, as it did then.
|
||||
val old = ModelInfo(id = "m", efforts = listOf("low", "high"))
|
||||
assertEquals(listOf("off", "low", "high"), old.offered)
|
||||
assertEquals("slider", old.levelControl)
|
||||
assertEquals("none", ModelInfo(id = "n").levelControl)
|
||||
assertEquals("switch", ModelInfo(id = "s", efforts = listOf("medium")).levelControl)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPictureIsOnlyTheInstancesOwn() {
|
||||
val base = "https://example.org"
|
||||
assertEquals("https://example.org/api/v2/models/images/0a1b.png", ApiClient.modelImageUrl(base, "/api/v2/models/images/0a1b.png"))
|
||||
assertNull(ApiClient.modelImageUrl(base, null))
|
||||
assertNull(ApiClient.modelImageUrl(base, "https://elsewhere.example/x.png"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/api/v2/models/images/../../me"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/api/v2/models/images/a/b.png"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/api/v2/models/images/.hidden"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/uploads/models/x.png"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatSaysItsTeamSizeAndDeviceSession() {
|
||||
val chat = read("chat", Chat.serializer())
|
||||
assertEquals(AgentsSetting(1, 4), chat.agents)
|
||||
assertNull(chat.deviceSessionId)
|
||||
assertEquals("ses_01waybread", read("chat_agent", Chat.serializer()).deviceSessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theActivityPanel() {
|
||||
val activity = read("activity", ActivityEnvelope.serializer()).activity
|
||||
assertEquals("0123456789abcdef", activity.version)
|
||||
assertEquals(3, activity.summary.active)
|
||||
assertTrue(activity.teamOffered)
|
||||
|
||||
val (baker, job) = activity.agents
|
||||
assertEquals("member", baker.kind)
|
||||
assertEquals("read", baker.step?.tool)
|
||||
assertTrue(baker.step!!.running)
|
||||
assertEquals(listOf("wrapper", "baker:job1"), baker.children.map { it.id })
|
||||
assertEquals("command", job.type)
|
||||
assertFalse(job.transcript)
|
||||
|
||||
// The tree, flattened in order for drawing; the split is by the top level's state.
|
||||
assertEquals(listOf("baker", "wrapper", "baker:job1", "job1"), ActivityLogic.flatten(activity.agents).map { it.id })
|
||||
val (live, ended) = ActivityLogic.split(activity.agents)
|
||||
assertEquals(2, live.size)
|
||||
assertTrue(ended.isEmpty())
|
||||
|
||||
val team = activity.team!!
|
||||
assertEquals(3, team.size)
|
||||
assertEquals(2, team.cursor)
|
||||
assertTrue(team.room[1].report)
|
||||
assertEquals(listOf("baker"), team.room[1].to)
|
||||
|
||||
val context = activity.context!!
|
||||
assertEquals(128000, context.limit)
|
||||
assertEquals(listOf("messages", "system"), ActivityLogic.barParts(context).map { it.key })
|
||||
assertEquals("/home/frodo/recipe.md", activity.outputs.single().path)
|
||||
assertEquals(42, activity.outputs.single().added)
|
||||
assertNull(ActivityLogic.plan(activity.plan))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAgentsConversationAndTheTeamAndTheEvent() {
|
||||
val detail = read("agent", AgentDetail.serializer())
|
||||
assertEquals("baker", detail.agent.name)
|
||||
assertEquals(listOf("user", "assistant"), detail.transcript.map { it.role })
|
||||
assertEquals("recipe.md", detail.transcript[1].tools.single().title)
|
||||
assertTrue(detail.transcript[1].running)
|
||||
|
||||
val team = read("team", TeamEnvelope.serializer()).team
|
||||
assertTrue(team.offered)
|
||||
assertEquals(listOf(0, 1, 2), team.agents.map { it.depth })
|
||||
assertNull(team.agents[0].manager)
|
||||
|
||||
val frame = read("event_activity", ActivityFrame.serializer())
|
||||
assertEquals("0123456789abcdef", frame.version)
|
||||
assertEquals(2, frame.summary.working)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theStripCountsWhatIsGoing() {
|
||||
val summary = ActivitySummary(queued = 1, working = 3, waiting = 0, done = 4, finished = 4, active = 4, total = 8)
|
||||
assertEquals(listOf("working" to 3, "queued" to 1), ActivityLogic.stripCounts(summary))
|
||||
assertTrue(ActivityLogic.stripCounts(ActivitySummary(done = 2, finished = 2)).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun numbersAsTheServerWritesThem() {
|
||||
assertEquals("950", ActivityLogic.compactTokens(950))
|
||||
assertEquals("14.2k", ActivityLogic.compactTokens(14_200))
|
||||
assertEquals("41k", ActivityLogic.compactTokens(41_000))
|
||||
assertEquals("180k", ActivityLogic.compactTokens(180_400))
|
||||
assertEquals("1.54M", ActivityLogic.compactTokens(1_540_000))
|
||||
assertEquals("1M", ActivityLogic.compactTokens(1_000_000))
|
||||
assertEquals("5s", ActivityLogic.duration(5))
|
||||
assertEquals("1m 05s", ActivityLogic.duration(65))
|
||||
assertEquals("2h 03m", ActivityLogic.duration(7_380))
|
||||
assertEquals("32", ActivityLogic.percent(32.0))
|
||||
assertEquals("23.4", ActivityLogic.percent(23.4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun elapsedTimeRunsOnOnlyForOneThatIsGoing() {
|
||||
val activity = read("activity", ActivityEnvelope.serializer()).activity
|
||||
val (baker, _) = activity.agents
|
||||
val wrapper = baker.children[0]
|
||||
val helper = baker.children[1]
|
||||
assertEquals(105L, ActivityLogic.elapsed(baker, readAtMillis = 1_000, nowMillis = 11_000))
|
||||
assertEquals(0L, ActivityLogic.elapsed(wrapper, readAtMillis = 1_000, nowMillis = 11_000))
|
||||
assertEquals(12L, ActivityLogic.elapsed(helper, readAtMillis = 1_000, nowMillis = 11_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noWindowNoBar() {
|
||||
assertTrue(ActivityLogic.barParts(ContextUse(used = 10, limit = 0)).isEmpty())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user