diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt index 66a79c6..7be40c0 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -155,15 +155,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli suspend fun models(chatId: String? = null): List = modelList(chatId).models - /** The models with the instance's subagent cap; with [chatId], whether each is offered subagents on that chat. */ - suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models") + /** + * The models with the instance's subagent cap; with [chatId], whether each is offered subagents + * on that chat. Only models a chat can be on (`capability` `chat`): this list is what every + * picker and the assistant's model setting are filled from. + */ + suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models").forChat() /** The models for a new agent chat on [deviceId], with whether it may have subagents (`agent_subagents`). */ - suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get( + suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get( "/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() + // With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on. directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(), - ) + ).forChat() suspend fun folders(): List = get("/folders").folders @@ -659,26 +663,35 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli * Save a text file. [base] is the `sha` the file had when it was opened: when it holds * something else by now the server writes nothing and this throws [SaveConflict] with its * sentence, unless [force]. Without a [base] nothing is compared, and a path with no file - * makes one. + * makes one. With [create] the file must be new: where something is already at the path the + * server writes nothing (409, `exists`) and this throws [FileExists] with its sentence -- an + * older server knows no `create` and writes as before. */ - suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false): FileContent = withContext(Dispatchers.IO) { + suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false, create: Boolean = false): FileContent { val body = buildJsonObject { put("path", path) put("text", text) base?.takeIf { it.isNotBlank() }?.let { put("base", it) } if (force) put("force", true) + if (create) put("create", true) } - http.newCall(authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()).await().use { response -> - val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("") - if (response.code == 409) { - val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap()) - if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") { - throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty()) - } + val request = authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build() + return withContext(Dispatchers.IO) { http.newCall(request).await().use { response -> saved(response) } } + } + + /** A save's answer: the file as it is now, or what refused it. */ + private fun saved(response: Response): FileContent { + val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("") + if (response.code == 409) { + val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap()) + if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") { + throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty()) } - if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.") - LembasJson.decodeFromString(FileContent.serializer(), said) + // A new file whose name is taken: nothing was written, and the sentence says what is there. + if ((conflict["exists"] as? JsonPrimitive)?.content == "true") throw FileExists(refusal(said).orEmpty()) } + if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.") + return LembasJson.decodeFromString(FileContent.serializer(), said) } suspend fun trash(): TrashList = get("/files/trash") @@ -714,12 +727,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli * The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in * the Authorization header, as on every call: the address names the path and nothing else. */ - fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = authed( - filesUrl( - "/raw", - "path" to path, - "inline" to if (inline) "1" else null, - ), + fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = raw(Raw.Path(path), range, inline) + + /** + * The request for [what]'s bytes, or for [range] of them: a file of the tree by its path (one + * [Raw.Path.version] of it, where named), a file by its node id wherever it is now, or a chat's + * attachment. Always with the token in the header and never in the address. + */ + fun raw(what: Raw, range: LongRange? = null, inline: Boolean = false): Request = authed( + when (what) { + is Raw.Path -> filesUrl("/raw", "path" to what.path, "version" to what.version?.ifBlank { null }, "inline" to if (inline) "1" else null) + is Raw.Node -> filesUrl("/raw", "node" to what.id, "inline" to if (inline) "1" else null) + is Raw.Attached -> "$v2/attachments/${segment(what.id)}" + }, ) .header("Accept", "*/*") .apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } } @@ -767,7 +787,10 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli * blocking, on whatever thread asks (never the main one). A server that answers the whole * file to a range that does not start at 0 is refused rather than read from the wrong place. */ - fun rawBytes(path: String, from: Long, to: Long): ByteArray = http.newCall(rawFile(path, from..to)).execute().use { response -> + fun rawBytes(path: String, from: Long, to: Long): ByteArray = rawBytes(Raw.Path(path), from, to) + + /** The same for any [Raw]: a file by its node id is read a piece at a time as one by its path is. */ + fun rawBytes(what: Raw, from: Long, to: Long): ByteArray = http.newCall(raw(what, from..to)).execute().use { response -> if (!response.isSuccessful) throw ApiException(response.code, detail(response)) if (response.code != 206 && from > 0) throw ApiException(416, "") val want = to - from + 1 @@ -787,6 +810,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli .build() .toString() + // --- Generated media's jobs, and the MCP servers ---------------------------------------------- + + /** A chat's long generations, newest first (at most 50); with [active] only those under way. */ + suspend fun mediaJobs(chatId: String, active: Boolean = false): List = + get("/media/jobs?chat_id=${segment(chatId)}" + if (active) "&active=true" else "").jobs + + /** One job as it stands; somebody else's, or one that is gone, is a 404 in the server's words. */ + suspend fun mediaJob(id: String): MediaJob = get("/media/jobs/${segment(id)}") + + /** Stop a job: the job as it is after. One that has ended stays what it was, so this is safe to repeat. */ + suspend fun cancelMediaJob(id: String): MediaJob = call(authed("$v2/media/jobs/${segment(id)}").delete().build(), MediaJob.serializer()) + + /** The MCP servers whose tools this person's chats may be offered, and how each is signed in to. */ + suspend fun mcpServers(): List = get("/mcp").servers + // --- Push -------------------------------------------------------------------------------- suspend fun pushKey(): PushKey = get("/push") diff --git a/app/src/main/java/eu/llembas/android/api/Media.kt b/app/src/main/java/eu/llembas/android/api/Media.kt new file mode 100644 index 0000000..eb5ed0e --- /dev/null +++ b/app/src/main/java/eu/llembas/android/api/Media.kt @@ -0,0 +1,167 @@ +package eu.llembas.android.api + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +// What a model made, as the app is told of it (`contract/tool_media.json`, `media_job*.json`, +// `mcp_servers.json`): a tool call's typed result, a long generation's job, and -- because they +// arrived with the same server -- the instance's MCP servers and how each is signed in to. + +/** + * A file a tool call made: [kind] is what was asked for (`image`, `image_edit`, `video`, `music`, + * `model3d`), and the file is in the person's Files at [path] -- a moment's truth, since they may + * move it; [nodeId] names it wherever it is. Its bytes are `GET /files/raw?node=`. [width], + * [height] and [seconds] are 0 where the server did not know them. + */ +@Serializable +data class GeneratedMedia( + val kind: String = "", + val path: String = "", + @SerialName("node_id") val nodeId: String = "", + @SerialName("version_id") val versionId: String = "", + val name: String = "", + val mime: String = "", + val size: Long = 0, + val width: Int = 0, + val height: Int = 0, + val seconds: Double = 0.0, +) { + /** How the card shows it, by what was asked for: an unknown kind is its details, never a player. */ + val view: MediaView + get() = when (kind) { + "image", "image_edit" -> MediaView.Picture + "video" -> MediaView.Video + "music" -> MediaView.Sound + else -> MediaView.Details + } + + /** What to call it: its name, else the last name of its path. */ + val title: String get() = name.ifBlank { FileKinds.name(path) } +} + +/** What a generated file's card is: a picture drawn, a player, or (a 3D model, anything unknown) the file's details. */ +enum class MediaView { Picture, Video, Sound, Details } + +/** The job a tool call started (`media_job`): [state] as it was when the call returned. */ +@Serializable +data class MediaJobRef(val id: String = "", val kind: String = "", val state: String = "") + +/** What a finished job was counted as; an empty [currency] is the instance's own. */ +@Serializable +data class MediaCost(val amount: Double = 0.0, val currency: String = "") + +/** + * A long generation (`GET /media/jobs/{id}`): `queued` and `running` are under way, `done` has + * its [result], `failed`, `cancelled` and `expired` say why in [error] -- the server's sentence, + * for the person. [seconds] is how long it has taken so far, or took. [told]: the chat was woken + * with a reply about it. + */ +@Serializable +data class MediaJob( + val id: String = "", + val kind: String = "", + val state: String = "", + val active: Boolean = false, + @SerialName("chat_id") val chatId: String? = null, + @SerialName("message_id") val messageId: String? = null, + val source: String = "", + val prompt: String = "", + val started: String? = null, + val ended: String? = null, + val deadline: String? = null, + val seconds: Double = 0.0, + val error: String = "", + val result: GeneratedMedia? = null, + val cost: MediaCost? = null, + val told: Boolean = false, +) { + /** Still to end: by the server's word, or by a state that is one of the two that are under way. */ + val underWay: Boolean get() = active || state in ACTIVE + + /** Ended some way other than with a file. */ + val unsuccessful: Boolean get() = !underWay && state != DONE + + companion object { + val ACTIVE = setOf("queued", "running") + const val DONE = "done" + const val CANCELLED = "cancelled" + + /** A job known only by the call that started it. */ + fun of(ref: MediaJobRef): MediaJob = MediaJob(id = ref.id, kind = ref.kind, state = ref.state, active = ref.state in ACTIVE) + } +} + +@Serializable +data class MediaJobList(val jobs: List = emptyList()) + +/** + * A new file that was not made because something is already called that (409, `exists: true`): + * the server's sentence. Nothing was written. + */ +class FileExists(message: String) : java.io.IOException(message) + +/** + * How an MCP server is signed in to: [kind] `none`, `secret` or `oauth`; [state] `ready`, + * `signed_in`, `signed_out` or `needs_signin`. [account] is who the provider says signed in -- a + * stranger's text, drawn as plain text. [signinUrl] is a page of the instance to open in a + * browser, where the person signs in to the instance itself with its cookie: the app's token is + * never part of it. + */ +@Serializable +data class McpAuth( + val kind: String = "none", + val state: String = "ready", + val shared: Boolean = false, + val account: String = "", + @SerialName("expires_at") val expiresAt: String? = null, + val renews: Boolean = false, + @SerialName("signin_url") val signinUrl: String? = null, +) { + /** The server's tools are not offered until somebody signs in. */ + val needsSignIn: Boolean get() = state == "signed_out" || state == "needs_signin" +} + +@Serializable +data class McpServer(val id: String = "", val slug: String = "", val name: String = "", val tools: Int = 0, val auth: McpAuth = McpAuth()) { + val label: String get() = name.ifBlank { slug.ifBlank { id } } +} + +@Serializable +data class McpServerList(val servers: List = emptyList()) + +/** + * The address the browser is sent to for a sign-in: always a page of the instance the app is + * signed in to ([base]). An address on that origin is taken as it is; a path alone, or an + * address the instance wrote with another name for itself, is that path on [base] -- so nothing + * the list says can send the person to another host. Null for no address, or one that is no + * http(s) page. + */ +fun signInAddress(base: String, url: String?): String? { + val said = url?.trim().orEmpty() + if (said.isEmpty()) return null + val want = runCatching { java.net.URI(said) }.getOrNull() ?: return null + val home = runCatching { java.net.URI(base) }.getOrNull() ?: return null + if (want.scheme != null && want.scheme.lowercase() !in setOf("http", "https")) return null + val path = want.rawPath.orEmpty() + if (!path.startsWith("/") || path.startsWith("//")) return null + + fun port(u: java.net.URI) = when { + u.port >= 0 -> u.port + u.scheme.equals("https", true) -> 443 + else -> 80 + } + val same = want.scheme != null && want.scheme.equals(home.scheme, true) && want.host != null && want.host.equals(home.host, true) && + port(want) == port(home) && want.userInfo == null + return if (same) said else base.trimEnd('/') + path + want.rawQuery?.let { "?$it" }.orEmpty() +} + +/** Which bytes of the instance are asked for: a file of the tree (or one version of it), a file by its id, or a chat's attachment. */ +sealed interface Raw { + data class Path(val path: String, val version: String? = null) : Raw + + /** A file by its node id, wherever it is now: what a generated file's result carries. */ + data class Node(val id: String) : Raw + + /** A chat's attachment. Answered whole: a player gets a copy, not a stream. */ + data class Attached(val id: String) : Raw +} 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 77586f4..dd77975 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -127,7 +127,16 @@ data class ModelInfo( val provider: String = "", /** The connection's name, for telling two models with one [id] apart. */ val connection: String = "", + /** + * What the model is for (server 2.0.0-beta.17): `chat`, or a word for something a chat cannot + * start on (`embedding`, and later `image`, `video`, …). A server that does not say it offers + * only models to chat with. + */ + val capability: String = CHAT, ) { + /** Whether a chat can be on it: the one capability this app's pickers offer. An unknown word is not one. */ + val forChat: Boolean get() = capability == CHAT + /** What this model is chosen, kept and sent by: its [ref], or its [id] from a server without refs. */ val key: String get() = ref.ifBlank { id } @@ -162,9 +171,13 @@ data class ModelInfo( companion object { val CONTROLS = setOf("none", "switch", "slider") + const val CHAT = "chat" } } +/** The models a chat can be on, of a list: what every model picker and the assistant's model setting offer. */ +fun List.forChat(): List = filter { it.forChat } + /** * The model a name means, in a list: by its `ref`, else the first with that `id` -- which is * what a bare id names on the server too. So a name kept from before refs (a setting, a chat's @@ -212,7 +225,10 @@ data class ModelList( @SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null, /** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */ val start: StartModel? = null, -) +) { + /** The same answer with only the models a chat can be on. */ + fun forChat(): ModelList = if (models.all { it.forChat }) this else copy(models = models.forChat()) +} /** * A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance @@ -510,6 +526,10 @@ data class ToolCall( val show: ShowCard? = null, /** `image_generate`'s picture: the server's own attachment, by id, and its size. */ val image: GeneratedImage? = null, + /** The file the call made (a picture, video, music, a 3D model), which is in the person's Files. */ + val media: GeneratedMedia? = null, + /** A generation that takes minutes: the job the call started, as it was when the call returned. */ + @SerialName("media_job") val mediaJob: MediaJobRef? = null, val block: ToolBlock = ToolBlock(), ) diff --git a/app/src/test/java/eu/llembas/android/MediaContractTest.kt b/app/src/test/java/eu/llembas/android/MediaContractTest.kt new file mode 100644 index 0000000..e41e0d1 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/MediaContractTest.kt @@ -0,0 +1,256 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.ApiException +import eu.llembas.android.api.FileExists +import eu.llembas.android.api.LembasJson +import eu.llembas.android.api.McpServerList +import eu.llembas.android.api.MediaJob +import eu.llembas.android.api.MediaJobList +import eu.llembas.android.api.MediaView +import eu.llembas.android.api.ModelInfo +import eu.llembas.android.api.ModelList +import eu.llembas.android.api.Raw +import eu.llembas.android.api.ToolCall +import eu.llembas.android.api.forChat +import eu.llembas.android.api.signInAddress +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.jsonObject +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test + +/** + * Generated media, its jobs, a new file that must be new, what a model is for and the MCP + * servers, as the pinned contract has them and as the client asks for them. + */ +class MediaContractTest { + private lateinit var server: MockWebServer + + @Before + fun up() { + server = MockWebServer().apply { start() } + } + + @After + fun down() = server.shutdown() + + private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + + private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { + "contract/$name.json is missing" + }.readText() + + @Test + fun aCallCarriesItsFileOrItsJob() { + val calls = LembasJson.parseToJsonElement(contract("tool_media")).jsonObject.getValue("calls") + val (picture, video) = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls) + // A picture is an attachment as before, and a file of the tree as well. + assertEquals("att1", picture.image!!.id) + val media = picture.media!! + assertEquals(MediaView.Picture, media.view) + assertEquals("node8", media.nodeId) + assertEquals("/home/frodo/Generated/image-20260102-030405.png", media.path) + assertEquals("image-20260102-030405.png", media.title) + assertEquals(180_000L, media.size) + assertEquals(1024, media.width) + assertEquals(0.0, media.seconds, 0.0) + assertNull(picture.mediaJob) + // A video is a job: the call says which, and that it was running when it returned. + assertNull(video.media) + assertNull(video.image) + val job = MediaJob.of(video.mediaJob!!) + assertEquals("mjob1", job.id) + assertEquals("video", job.kind) + assertTrue(job.underWay) + } + + @Test + fun theCardIsChosenByWhatWasAskedFor() { + fun view(kind: String) = LembasJson.decodeFromString(eu.llembas.android.api.GeneratedMedia.serializer(), """{"kind":"$kind"}""").view + assertEquals(MediaView.Picture, view("image")) + assertEquals(MediaView.Picture, view("image_edit")) + assertEquals(MediaView.Video, view("video")) + assertEquals(MediaView.Sound, view("music")) + assertEquals(MediaView.Details, view("model3d")) + // A kind this app does not know is a file with details, never something played or drawn. + assertEquals(MediaView.Details, view("hologram")) + } + + @Test + fun aJobUnderWayDoneAndFailed() { + val running = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job")) + assertTrue(running.underWay) + assertFalse(running.unsuccessful) + assertEquals(42.0, running.seconds, 0.0) + assertNull(running.result) + assertFalse(running.told) + + val done = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job_done")) + assertFalse(done.underWay) + assertFalse(done.unsuccessful) + assertEquals(MediaView.Video, done.result!!.view) + assertEquals("node7", done.result!!.nodeId) + assertEquals(5.0, done.result!!.seconds, 0.0) + assertEquals(0.1, done.cost!!.amount, 1e-9) + assertTrue(done.told) + + val failed = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job_failed")) + assertTrue(failed.unsuccessful) + assertEquals("ComfyUI ran out of video memory in KSampler.", failed.error) + + assertEquals(listOf("running", "done", "failed"), LembasJson.decodeFromString(MediaJobList.serializer(), contract("media_jobs")).jobs.map { it.state }) + // A state this app does not know ends the following unless the server says it is still active. + assertFalse(MediaJob(id = "j", state = "paused").underWay) + assertTrue(MediaJob(id = "j", state = "paused", active = true).underWay) + } + + @Test + fun theJobsAreAskedForReadAndCancelled() = runTest { + val api = client() + server.enqueue(MockResponse().setBody(contract("media_jobs"))) + assertEquals(3, api.mediaJobs("chat1").size) + assertEquals("/api/v2/media/jobs?chat_id=chat1", server.takeRequest().path) + server.enqueue(MockResponse().setBody(contract("media_jobs"))) + api.mediaJobs("chat1", active = true) + assertEquals("/api/v2/media/jobs?chat_id=chat1&active=true", server.takeRequest().path) + + server.enqueue(MockResponse().setBody(contract("media_job"))) + assertEquals("mjob1", api.mediaJob("mjob1").id) + val read = server.takeRequest() + assertEquals("GET", read.method) + assertEquals("/api/v2/media/jobs/mjob1", read.path) + assertEquals("Bearer lmb_test", read.getHeader("Authorization")) + + server.enqueue(MockResponse().setBody(contract("media_job_failed"))) + assertEquals("failed", api.cancelMediaJob("mjob3").state) + val cancel = server.takeRequest() + assertEquals("DELETE", cancel.method) + assertEquals("/api/v2/media/jobs/mjob3", cancel.path) + + // Somebody else's job, or one that is gone: the server's sentence. + server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"That job no longer exists."}""")) + try { + api.mediaJob("mjob9") + fail("a 404 is no job") + } catch (e: ApiException) { + assertEquals("That job no longer exists.", e.message) + } + } + + @Test + fun bytesAreAskedForByPathByVersionByNodeAndByAttachment() { + val api = client() + fun path(what: Raw, inline: Boolean = false) = api.raw(what, inline = inline).url.let { it.encodedPath + "?" + it.encodedQuery } + assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fa.mp4", path(Raw.Path("/home/frodo/a.mp4"))) + assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fa.md&version=ver3", path(Raw.Path("/home/frodo/a.md", "ver3"))) + assertEquals("/api/v2/files/raw?node=node7&inline=1", path(Raw.Node("node7"), inline = true)) + assertEquals("/api/v2/attachments/att1", api.raw(Raw.Attached("att1")).url.encodedPath) + // The token is in the header of each, and in the address of none. + for (what in listOf(Raw.Path("/a"), Raw.Node("node7"), Raw.Attached("att1"))) { + val request = api.raw(what, range = 0L..9L) + assertEquals("Bearer lmb_test", request.header("Authorization")) + assertEquals("bytes=0-9", request.header("Range")) + assertFalse(request.url.toString().contains("lmb_test")) + } + // A piece of a file by its id is the same Range request a piece by its path is. + server.enqueue(MockResponse().setResponseCode(206).setBody("0123456789")) + assertEquals("0123456789", api.rawBytes(Raw.Node("node7"), 10, 19).toString(Charsets.UTF_8)) + val piece = server.takeRequest() + assertEquals("/api/v2/files/raw?node=node7", piece.path) + assertEquals("bytes=10-19", piece.getHeader("Range")) + } + + @Test + fun aNewFileIsNeverWrittenOverAnother() = runTest { + val api = client() + server.enqueue(MockResponse().setResponseCode(201).setBody(contract("file_content"))) + api.saveFile("/home/frodo/new.md", "", create = true) + val said = server.takeRequest().body.readUtf8() + assertTrue(said, said.contains("\"create\":true")) + assertFalse(said, said.contains("base")) + + server.enqueue(MockResponse().setResponseCode(409).setBody(contract("file_create_exists"))) + try { + api.saveFile("/home/frodo/lembas.md", "", create = true) + fail("a name that is taken makes no file") + } catch (e: FileExists) { + assertEquals("There is already something called lembas.md here.", e.message) + } + server.takeRequest() + // A save that is not a new file does not say `create`. + server.enqueue(MockResponse().setBody(contract("file_content"))) + api.saveFile("/home/frodo/lembas.md", "x", base = "abab") + assertFalse(server.takeRequest().body.readUtf8().contains("create")) + } + + @Test + fun onlyAModelToChatWithIsOffered() = runTest { + // The pinned lists say `chat` for every model; a list that named another kind loses it here. + assertTrue(LembasJson.decodeFromString(ModelList.serializer(), contract("models")).models.all { it.capability == "chat" && it.forChat }) + val mixed = """{"models": [ + {"id": "qwen", "capability": "chat"}, + {"id": "embedder", "capability": "embedding"}, + {"id": "painter", "capability": "image"}, + {"id": "old"}, + {"id": "novel", "capability": "something-new"}], "subagents_cap": 4}""" + val list = LembasJson.decodeFromString(ModelList.serializer(), mixed) + assertEquals(listOf("qwen", "old"), list.models.forChat().map { it.id }) + assertEquals(listOf("qwen", "old"), list.forChat().models.map { it.id }) + assertEquals(4, list.forChat().subagentsCap) + // What the pickers and the assistant's setting are filled from is already narrowed. + val api = client() + server.enqueue(MockResponse().setBody(mixed)) + assertEquals(listOf("qwen", "old"), api.models().map(ModelInfo::id)) + server.enqueue(MockResponse().setBody(mixed)) + assertEquals(listOf("qwen", "old"), api.agentModelList("dev1").models.map(ModelInfo::id)) + } + + @Test + fun theMcpServersAndWhoHasToSignIn() = runTest { + val servers = LembasJson.decodeFromString(McpServerList.serializer(), contract("mcp_servers")).servers + assertEquals(listOf("Tracker", "Mail", "Notes", "Wiki"), servers.map { it.label }) + assertEquals(listOf("ready", "signed_in", "signed_out", "needs_signin"), servers.map { it.auth.state }) + assertEquals(listOf(false, false, true, true), servers.map { it.auth.needsSignIn }) + assertEquals("frodo@example.org", servers[1].auth.account) + assertTrue(servers[1].auth.renews) + // One's own sign-in has a page; a shared one has none for a person who is no administrator. + assertEquals("https://lembas.example.org/settings/mcp/mcp3/sign-in", servers[2].auth.signinUrl) + assertTrue(servers[3].auth.shared) + assertNull(servers[3].auth.signinUrl) + + server.enqueue(MockResponse().setBody(contract("mcp_servers"))) + assertEquals(4, client().mcpServers().size) + assertEquals("/api/v2/mcp", server.takeRequest().path) + } + + @Test + fun aSignInOpensAPageOfTheInstanceAndNothingElse() { + val base = "https://lembas.example.org" + val page = "/settings/mcp/mcp3/sign-in" + assertEquals(base + page, signInAddress(base, base + page)) + assertEquals(base + page, signInAddress(base, page)) + assertEquals(base + page, signInAddress("$base/", page)) + // The instance named itself otherwise (another name, another port): the same page, on the instance the app knows. + assertEquals(base + page, signInAddress(base, "https://other.example.net$page")) + assertEquals("$base$page?x=1", signInAddress(base, "http://lembas.example.org:8080$page?x=1")) + assertEquals("http://lembas.example.org:8080$page", signInAddress("http://lembas.example.org:8080", "http://lembas.example.org:8080$page")) + // Nothing that is not a page, and never a host hidden in a path or before an @. + assertNull(signInAddress(base, null)) + assertNull(signInAddress(base, " ")) + assertNull(signInAddress(base, "javascript:alert(1)")) + assertNull(signInAddress(base, "intent://settings#Intent;end")) + assertEquals("$base/settings", signInAddress(base, "//other.example.net/settings")) + assertEquals("$base/settings", signInAddress(base, "https://lembas.example.org@other.example.net/settings")) + // The app's token is in none of them: there is no place for one. + assertFalse(signInAddress(base, base + page)!!.contains("token")) + } +} diff --git a/contract/file_create_exists.json b/contract/file_create_exists.json new file mode 100644 index 0000000..49fb786 --- /dev/null +++ b/contract/file_create_exists.json @@ -0,0 +1,5 @@ +{ + "detail": "There is already something called lembas.md here.", + "exists": true, + "path": "/home/frodo/lembas.md" +} diff --git a/contract/lock.json b/contract/lock.json index d44c277..9ff4ef9 100644 --- a/contract/lock.json +++ b/contract/lock.json @@ -1,5 +1,5 @@ { - "ref": "59bebe2", - "commit": "59bebe234cae114309e40d3f96e6074bd91db46a", - "sha256": "e0e4bba98c130740c1e4c3727e86ef7e0672772789b7e85cac3a674aae91d163" + "ref": "d726573", + "commit": "d72657352314d0147584bf6dc6c1df78b836f22d", + "sha256": "da28913755ec208ee85275a28f57b8b66f3ae3871748e6a8840187467b161f4b" } diff --git a/contract/media_job.json b/contract/media_job.json new file mode 100644 index 0000000..c85b37c --- /dev/null +++ b/contract/media_job.json @@ -0,0 +1,18 @@ +{ + "id": "mjob1", + "kind": "video", + "state": "running", + "active": true, + "chat_id": "chat1", + "message_id": "msg2", + "source": "Studio · Text to video", + "prompt": "a kite over dunes", + "started": "2026-01-02T03:04:05+00:00", + "ended": null, + "deadline": "2026-01-02T03:34:05+00:00", + "seconds": 42, + "error": "", + "result": null, + "cost": null, + "told": false +} diff --git a/contract/media_job_done.json b/contract/media_job_done.json new file mode 100644 index 0000000..4205af6 --- /dev/null +++ b/contract/media_job_done.json @@ -0,0 +1,32 @@ +{ + "id": "mjob2", + "kind": "video", + "state": "done", + "active": false, + "chat_id": "chat1", + "message_id": "msg2", + "source": "Studio · Text to video", + "prompt": "a kite over dunes", + "started": "2026-01-02T03:04:05+00:00", + "ended": "2026-01-02T03:05:40+00:00", + "deadline": "2026-01-02T03:34:05+00:00", + "seconds": 95, + "error": "", + "result": { + "kind": "video", + "path": "/home/frodo/Generated/video-20260102-030405.mp4", + "node_id": "node7", + "version_id": "ver7", + "name": "video-20260102-030405.mp4", + "mime": "video/mp4", + "size": 2400000, + "width": 832, + "height": 480, + "seconds": 5 + }, + "cost": { + "amount": 0.1, + "currency": "" + }, + "told": true +} diff --git a/contract/media_job_failed.json b/contract/media_job_failed.json new file mode 100644 index 0000000..2347720 --- /dev/null +++ b/contract/media_job_failed.json @@ -0,0 +1,18 @@ +{ + "id": "mjob3", + "kind": "video", + "state": "failed", + "active": false, + "chat_id": "chat1", + "message_id": "msg2", + "source": "Studio · Text to video", + "prompt": "a kite over dunes", + "started": "2026-01-02T03:04:05+00:00", + "ended": "2026-01-02T03:05:40+00:00", + "deadline": "2026-01-02T03:34:05+00:00", + "seconds": 95, + "error": "ComfyUI ran out of video memory in KSampler.", + "result": null, + "cost": null, + "told": true +} diff --git a/contract/media_jobs.json b/contract/media_jobs.json new file mode 100644 index 0000000..c7cddcc --- /dev/null +++ b/contract/media_jobs.json @@ -0,0 +1,72 @@ +{ + "jobs": [ + { + "id": "mjob1", + "kind": "video", + "state": "running", + "active": true, + "chat_id": "chat1", + "message_id": "msg2", + "source": "Studio · Text to video", + "prompt": "a kite over dunes", + "started": "2026-01-02T03:04:05+00:00", + "ended": null, + "deadline": "2026-01-02T03:34:05+00:00", + "seconds": 42, + "error": "", + "result": null, + "cost": null, + "told": false + }, + { + "id": "mjob2", + "kind": "video", + "state": "done", + "active": false, + "chat_id": "chat1", + "message_id": "msg2", + "source": "Studio · Text to video", + "prompt": "a kite over dunes", + "started": "2026-01-02T03:04:05+00:00", + "ended": "2026-01-02T03:05:40+00:00", + "deadline": "2026-01-02T03:34:05+00:00", + "seconds": 95, + "error": "", + "result": { + "kind": "video", + "path": "/home/frodo/Generated/video-20260102-030405.mp4", + "node_id": "node7", + "version_id": "ver7", + "name": "video-20260102-030405.mp4", + "mime": "video/mp4", + "size": 2400000, + "width": 832, + "height": 480, + "seconds": 5 + }, + "cost": { + "amount": 0.1, + "currency": "" + }, + "told": true + }, + { + "id": "mjob3", + "kind": "video", + "state": "failed", + "active": false, + "chat_id": "chat1", + "message_id": "msg2", + "source": "Studio · Text to video", + "prompt": "a kite over dunes", + "started": "2026-01-02T03:04:05+00:00", + "ended": "2026-01-02T03:05:40+00:00", + "deadline": "2026-01-02T03:34:05+00:00", + "seconds": 95, + "error": "ComfyUI ran out of video memory in KSampler.", + "result": null, + "cost": null, + "told": true + } + ] +} diff --git a/contract/models.json b/contract/models.json index 4a7d3fa..c6dc941 100644 --- a/contract/models.json +++ b/contract/models.json @@ -6,6 +6,7 @@ "provider": "local", "connection": "Local", "name": "Qwen", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -34,6 +35,7 @@ "provider": "local", "connection": "Local", "name": "gpt-oss", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -65,6 +67,7 @@ "provider": "local", "connection": "Local", "name": "Vision", + "capability": "chat", "vision": true, "tools": false, "efforts": [], diff --git a/contract/models_agent.json b/contract/models_agent.json index dc1d03f..88f7f55 100644 --- a/contract/models_agent.json +++ b/contract/models_agent.json @@ -6,6 +6,7 @@ "provider": "local", "connection": "Local", "name": "Qwen", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -34,6 +35,7 @@ "provider": "local", "connection": "Local", "name": "gpt-oss", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -65,6 +67,7 @@ "provider": "local", "connection": "Local", "name": "Vision", + "capability": "chat", "vision": true, "tools": false, "efforts": [], diff --git a/contract/models_agent_directory.json b/contract/models_agent_directory.json index f7e8069..892601f 100644 --- a/contract/models_agent_directory.json +++ b/contract/models_agent_directory.json @@ -6,6 +6,7 @@ "provider": "local", "connection": "Local", "name": "Qwen", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -34,6 +35,7 @@ "provider": "local", "connection": "Local", "name": "gpt-oss", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -65,6 +67,7 @@ "provider": "local", "connection": "Local", "name": "Vision", + "capability": "chat", "vision": true, "tools": false, "efforts": [], diff --git a/contract/schedule_models.json b/contract/schedule_models.json index 0caeaf5..c4aa475 100644 --- a/contract/schedule_models.json +++ b/contract/schedule_models.json @@ -6,6 +6,7 @@ "provider": "local", "connection": "Local", "name": "gpt-oss", + "capability": "chat", "vision": false, "tools": true, "efforts": [ @@ -40,6 +41,7 @@ "provider": "local", "connection": "Local", "name": "Qwen", + "capability": "chat", "vision": false, "tools": true, "efforts": [ diff --git a/contract/tool_media.json b/contract/tool_media.json new file mode 100644 index 0000000..cf1d623 --- /dev/null +++ b/contract/tool_media.json @@ -0,0 +1,65 @@ +{ + "calls": [ + { + "id": "call4", + "name": "image_generate", + "kind": "image", + "status": "ok", + "query": "a kite", + "text": "1024x1024", + "detail": "Cloud · qwen-image-3.0", + "results": [], + "image": { + "id": "att1", + "width": 1024, + "height": 1024 + }, + "media": { + "kind": "image", + "path": "/home/frodo/Generated/image-20260102-030405.png", + "node_id": "node8", + "version_id": "ver8", + "name": "image-20260102-030405.png", + "mime": "image/png", + "size": 180000, + "width": 1024, + "height": 1024 + }, + "block": { + "kind": "tool", + "title": "a kite", + "chips": [], + "added": 0, + "removed": 0, + "state": "done", + "duration": "", + "label": "Image" + } + }, + { + "id": "call5", + "name": "video_generate", + "kind": "image", + "status": "ok", + "query": "a kite over dunes", + "text": "video · job mjob1", + "detail": "Studio · Text to video", + "results": [], + "media_job": { + "id": "mjob1", + "kind": "video", + "state": "running" + }, + "block": { + "kind": "tool", + "title": "a kite over dunes", + "chips": [], + "added": 0, + "removed": 0, + "state": "done", + "duration": "", + "label": "Video" + } + } + ] +}