ai-app: a phone interface to Claude Code and llama.cpp sessions
A Rust backend that owns the sessions and an Android app that reads them. The server spawns and adopts CLI processes, normalises everything they emit into one event model, keeps the transcript, and serves it over pinned TLS on a WireGuard interface; the phone streams that, replies, sends images, and imports conversations the machine already has. `AGENTS.md` is the working guide -- what runs where, what has been measured, and the faults that were expensive to find. `PLAN.md` is the design record. History before this point was squashed away. It was a personal project's running commentary and carried a name and a couple of machine paths that have no business in a public repository; the tree is what mattered and the tree is here.
This commit is contained in:
commit
b172c464ea
100 files changed
+31795
No files matched your search
@@ -0,0 +1,826 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
// The REST half of the backend's surface (see server/src/routes.rs for the
|
||||
// table); the SSE half is EventStream.kt. All blocking network calls --
|
||||
// invoke from a background dispatcher. Each throws ApiException on failure,
|
||||
// carrying the server's own explanation where it sent one, since those
|
||||
// messages are written to be read on this screen.
|
||||
|
||||
// Shared with EventStream.kt, which connects the same way but then reads
|
||||
// without a deadline.
|
||||
const val CONNECT_TIMEOUT_MS = 5000
|
||||
private const val READ_TIMEOUT_MS = 5000
|
||||
|
||||
class ApiException(message: String, cause: Throwable? = null) : Exception(message, cause)
|
||||
|
||||
/**
|
||||
* Runs one request against the backend, with the pinned TLS setup, the bearer token, and the
|
||||
* failure translation every call needs. [readBody] gets the connected, already-status-checked
|
||||
* connection to read from.
|
||||
*
|
||||
* @param readTimeoutMs how long to wait on the response body. The SSE stream doesn't come through
|
||||
* here -- an event stream has no bounded read time (see EventStream.kt).
|
||||
*/
|
||||
fun <T> requestFromServer(
|
||||
settings: ServerSettings,
|
||||
path: String,
|
||||
method: String = "GET",
|
||||
jsonBody: String? = null,
|
||||
/** Raw request body as content-type to bytes -- the upload path. */
|
||||
binaryBody: Pair<String, ByteArray>? = null,
|
||||
readTimeoutMs: Int = READ_TIMEOUT_MS,
|
||||
readBody: (HttpURLConnection) -> T,
|
||||
): T {
|
||||
val connection = URL("${settings.baseUrl}$path").openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.applyPinnedTls()
|
||||
connection.requestMethod = method
|
||||
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
connection.readTimeout = readTimeoutMs
|
||||
connection.setRequestProperty("Authorization", "Bearer ${settings.token}")
|
||||
if (jsonBody != null) {
|
||||
connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.outputStream.use { it.write(jsonBody.encodeToByteArray()) }
|
||||
} else if (binaryBody != null) {
|
||||
connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", binaryBody.first)
|
||||
connection.outputStream.use { it.write(binaryBody.second) }
|
||||
}
|
||||
if (connection.responseCode !in 200..299) {
|
||||
val detail = connection.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
throw ApiException(
|
||||
when {
|
||||
connection.responseCode == 401 ->
|
||||
"The server rejected this device's token. Re-enroll by scanning " +
|
||||
"the server's QR (or rotate with --rotate-token and scan the new one)."
|
||||
detail.isNullOrEmpty() ->
|
||||
"Server returned HTTP ${connection.responseCode} for $path"
|
||||
else -> detail
|
||||
}
|
||||
)
|
||||
}
|
||||
return readBody(connection)
|
||||
} catch (e: ApiException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
// Surfacing the real exception (rather than one canned message for
|
||||
// every failure mode) is what lets this be diagnosed on a device
|
||||
// with no logcat access.
|
||||
throw ApiException(
|
||||
"Couldn't reach the server at ${settings.baseUrl} " +
|
||||
"(${e::class.simpleName}: ${e.message}) -- is ai-server running, and is " +
|
||||
"this device able to reach that address (WireGuard up)?",
|
||||
e,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
throw ApiException(
|
||||
"Reached ${settings.baseUrl}$path but couldn't read its response " +
|
||||
"(${e::class.simpleName}: ${e.message})",
|
||||
e,
|
||||
)
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
/** The response body as one JSON object. */
|
||||
private fun HttpURLConnection.jsonObject(): JSONObject =
|
||||
JSONObject(inputStream.bufferedReader().readText())
|
||||
|
||||
/** The response body as a JSON array of objects, each mapped through [parse]. */
|
||||
private fun <T> HttpURLConnection.jsonObjects(parse: (JSONObject) -> T): List<T> =
|
||||
JSONArray(inputStream.bufferedReader().readText()).mapObjects(parse)
|
||||
|
||||
private fun <T> JSONArray.mapObjects(parse: (JSONObject) -> T): List<T> =
|
||||
(0 until length()).map { parse(getJSONObject(it)) }
|
||||
|
||||
private fun JSONArray.strings(): List<String> = (0 until length()).map { getString(it) }
|
||||
|
||||
/** Percent-encodes a value going into a query string. */
|
||||
private fun String.urlEncoded(): String = java.net.URLEncoder.encode(this, Charsets.UTF_8.name())
|
||||
|
||||
// One row of GET /sessions. A session names the machine it runs on and
|
||||
// which of that machine's providers it runs.
|
||||
data class SessionSummary(
|
||||
val id: String,
|
||||
/**
|
||||
* Id of the machine this session runs on. Only ever used to *address* that machine -- to pick
|
||||
* this session's row out of the per-machine usage snapshots for the header's five-hour bar.
|
||||
*
|
||||
* It was deliberately left out until 2026-08-29, on the grounds that nothing here addressed a
|
||||
* setup and holding both the id and the name invited showing the wrong one, which had already
|
||||
* happened once. Something addresses one now, so the reason lapsed rather than being overruled.
|
||||
* The guard that replaces it is the rule below: never show this.
|
||||
*/
|
||||
val setup: String,
|
||||
/** The machine's current label. This is the one to display; [setup] is never shown. */
|
||||
val setupName: String,
|
||||
val provider: String,
|
||||
val title: String,
|
||||
val model: String?,
|
||||
/**
|
||||
* Whether the conversation would outlive deleting this session, decided by the server from the
|
||||
* provider's kind rather than here from its name.
|
||||
*
|
||||
* What it licenses is narrow, and the delete dialog is worded to match: the driver keeps its
|
||||
* own record of the conversation somewhere this app's delete does not reach. It is not a
|
||||
* promise that the file is still there, and re-importing is not a restore -- this app's
|
||||
* transcript holds things that record does not.
|
||||
*/
|
||||
val keepsOwnTranscript: Boolean,
|
||||
/** How much the session asks before acting; null when it was never set. */
|
||||
val permissionMode: String?,
|
||||
/**
|
||||
* Whether this continues a session the machine already had, which changes what deleting means.
|
||||
*/
|
||||
val imported: Boolean,
|
||||
/**
|
||||
* Whether this session announces itself when it wants attention.
|
||||
*
|
||||
* Reported rather than assumed, for the same reason [permissionMode] is: a switch that draws
|
||||
* itself from a default is one you can turn off while believing you are reading it. Defaults to
|
||||
* on when a backend is too old to say, which matches what that backend actually does.
|
||||
*/
|
||||
val notify: Boolean,
|
||||
/**
|
||||
* How much context this session is holding, as the server last measured it -- see
|
||||
* `SessionEvent.UsageDelta`.
|
||||
*
|
||||
* Null where nothing has been measured: a session that has not run a turn, a provider that does
|
||||
* not report usage, or a clear nobody has run a turn since. That is not zero, and the status
|
||||
* row says so in words rather than drawing an empty context for a conversation that may be
|
||||
* nearly full.
|
||||
*/
|
||||
val contextTokens: Long?,
|
||||
/**
|
||||
* The longest edge an image should have when it reaches this session, or null where the
|
||||
* provider has no limit.
|
||||
*
|
||||
* Null and "a big number" are different answers, and only the first stays true: a provider that
|
||||
* does not care about size should not be given a threshold this app invented. Decided by the
|
||||
* server because that is where a provider's kind is known -- see `uploadPickedImage`.
|
||||
*/
|
||||
val maxImageEdge: Int?,
|
||||
val status: String,
|
||||
val lastActivity: Double,
|
||||
)
|
||||
|
||||
private fun parseSession(session: JSONObject) =
|
||||
SessionSummary(
|
||||
id = session.getString("id"),
|
||||
setup = session.getString("setup"),
|
||||
keepsOwnTranscript = session.optBoolean("keepsOwnTranscript", false),
|
||||
setupName = session.getString("setupName"),
|
||||
provider = session.getString("provider"),
|
||||
title = session.getString("title"),
|
||||
model = session.optString("model").ifEmpty { null },
|
||||
permissionMode = session.optString("permissionMode").ifEmpty { null },
|
||||
imported = session.optBoolean("imported", false),
|
||||
notify = session.optBoolean("notify", true),
|
||||
contextTokens =
|
||||
if (session.has("contextTokens")) session.getLong("contextTokens") else null,
|
||||
maxImageEdge = session.optInt("maxImageEdge", 0).takeIf { it > 0 },
|
||||
status = session.getString("status"),
|
||||
lastActivity = session.getDouble("lastActivity"),
|
||||
)
|
||||
|
||||
fun fetchSessions(settings: ServerSettings): List<SessionSummary> =
|
||||
requestFromServer(settings, "/sessions") { it.jsonObjects(::parseSession) }
|
||||
|
||||
/**
|
||||
* One session as the server has it now.
|
||||
*
|
||||
* For screens whose controls are *set to* something rather than merely showing it. A screen opened
|
||||
* from a list row carries the row the list last fetched, which is a snapshot: fine for a title,
|
||||
* wrong for a switch, since a switch drawn from a stale row shows a position that may have been
|
||||
* changed since -- here or on another device -- and nothing on screen says which.
|
||||
*/
|
||||
fun fetchSession(settings: ServerSettings, sessionId: String): SessionSummary =
|
||||
requestFromServer(settings, "/sessions/$sessionId") { parseSession(it.jsonObject()) }
|
||||
|
||||
// What the server offers, so the spawn screen has no hardcoded lists: a
|
||||
// setup added to the server's config.ron appears here with no app rebuild.
|
||||
//
|
||||
// One list rather than two. A provider only exists on a machine that has
|
||||
// it installed, so offering machines and providers as independent choices
|
||||
// would offer pairs that cannot work.
|
||||
data class Provider(val name: String, val kind: String, val models: List<String>)
|
||||
|
||||
/**
|
||||
* A machine, and what it can run. [address] is absent for the backend itself.
|
||||
*
|
||||
* [id] is stable and [name] is not: renaming a machine keeps its sessions, so everything that
|
||||
* refers to a setup uses the id and everything a person reads uses the name.
|
||||
*/
|
||||
data class Setup(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val address: String?,
|
||||
val providers: List<Provider>,
|
||||
)
|
||||
|
||||
private fun parseProvider(provider: JSONObject) =
|
||||
Provider(
|
||||
name = provider.getString("name"),
|
||||
kind = provider.getString("kind"),
|
||||
// Omitted entirely when the provider offers none.
|
||||
models = provider.optJSONArray("models")?.strings().orEmpty(),
|
||||
)
|
||||
|
||||
private fun parseSetup(setup: JSONObject) =
|
||||
Setup(
|
||||
id = setup.getString("id"),
|
||||
name = setup.getString("name"),
|
||||
address = setup.optString("address").ifEmpty { null },
|
||||
providers = setup.getJSONArray("providers").mapObjects(::parseProvider),
|
||||
)
|
||||
|
||||
fun fetchSetups(settings: ServerSettings): List<Setup> =
|
||||
requestFromServer(settings, "/setups") { it.jsonObjects(::parseSetup) }
|
||||
|
||||
/**
|
||||
* A Claude Code session already on a machine, which can be continued here.
|
||||
*
|
||||
* Identified by [id] and never by a path. The server resolves which file that is, so this app has
|
||||
* no way to ask it to read one -- the same rule that keeps a provider's command out of this client.
|
||||
*/
|
||||
data class Importable(
|
||||
val id: String,
|
||||
val cwd: String,
|
||||
val title: String,
|
||||
val modified: Double,
|
||||
val lines: Int,
|
||||
/**
|
||||
* Size of the session file in bytes.
|
||||
*
|
||||
* Worth a place on the row because it is the only thing there that predicts what continuing the
|
||||
* session costs, and the line count does not: these transcripts embed screenshots as base64, so
|
||||
* a single line can be a megabyte.
|
||||
*/
|
||||
val bytes: Long,
|
||||
/**
|
||||
* Tokens the model was holding at the last turn, or null if no turn has recorded any.
|
||||
*
|
||||
* The number that predicts what continuing this session costs. It disagrees with [bytes] in the
|
||||
* direction that matters: most of a large transcript is usually history from before a
|
||||
* compaction, which the model is no longer given.
|
||||
*/
|
||||
val contextTokens: Long?,
|
||||
/** Whether [title] is a name somebody chose rather than the last thing said in the session. */
|
||||
val named: Boolean,
|
||||
/**
|
||||
* Whether a Claude Code is running this session right now.
|
||||
*
|
||||
* "unknown" is a third answer and not a synonym for "no": the machine may keep no record of
|
||||
* what is running, and a session that cannot be checked is not a session that is free. The
|
||||
* server refuses an import of a "yes"; the row says so before you press it.
|
||||
*/
|
||||
val inUse: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* What a machine has that could be continued.
|
||||
*
|
||||
* The slowest call this app makes, and it was the only expensive one left on the 5 second default —
|
||||
* which is how it came to time out against a server that was answering perfectly well. Listing
|
||||
* means reading every transcript Claude Code has ever written: about four seconds against a
|
||||
* gigabyte of them before the tunnel adds anything, and that figure grows with every session
|
||||
* anybody has. A timeout is for a server that has stopped answering, so it is set well clear of how
|
||||
* long the work takes rather than just above it.
|
||||
*/
|
||||
fun fetchImportable(settings: ServerSettings, setup: String): List<Importable> =
|
||||
requestFromServer(settings, "/setups/$setup/importable", readTimeoutMs = 60000) {
|
||||
it.jsonObjects { session ->
|
||||
Importable(
|
||||
id = session.getString("id"),
|
||||
cwd = session.optString("cwd"),
|
||||
title = session.optString("title"),
|
||||
modified = session.optDouble("modified", 0.0),
|
||||
lines = session.optInt("lines", 0),
|
||||
bytes = session.optLong("bytes", 0L),
|
||||
// Absent means nothing has been measured -- which is not a context of zero, so
|
||||
// it stays null and the row simply does not claim a figure.
|
||||
contextTokens =
|
||||
if (session.isNull("contextTokens")) null
|
||||
else session.optLong("contextTokens").takeIf { it > 0L },
|
||||
// Absent means an older backend that cannot answer, which is exactly what
|
||||
// "unknown" says -- so the default is the honest one rather than "no".
|
||||
inUse = session.optString("inUse", "unknown"),
|
||||
named = session.optBoolean("named", false),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How to reach a machine. Deliberately carries no command: the server discovers what a machine can
|
||||
* run by asking it, so this app has no way to introduce something to run.
|
||||
*
|
||||
* [identityFile] is a path on the *backend*, not a key -- private keys do not travel.
|
||||
*/
|
||||
data class SshDetails(
|
||||
val address: String,
|
||||
val port: Int? = null,
|
||||
val identityFile: String? = null,
|
||||
)
|
||||
|
||||
private fun SshDetails.toJson() =
|
||||
JSONObject().put("address", address).apply {
|
||||
if (port != null) put("port", port)
|
||||
if (!identityFile.isNullOrBlank()) put("identityFile", identityFile)
|
||||
}
|
||||
|
||||
/** What a machine turns out to have, without saving anything. */
|
||||
fun probeSetup(settings: ServerSettings, ssh: SshDetails?): List<Provider> =
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/setups/probe",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().apply { if (ssh != null) put("ssh", ssh.toJson()) }.toString(),
|
||||
readTimeoutMs = 40000,
|
||||
) {
|
||||
it.jsonObjects(::parseProvider)
|
||||
}
|
||||
|
||||
fun addSetup(settings: ServerSettings, name: String, ssh: SshDetails?): Setup =
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/setups",
|
||||
method = "POST",
|
||||
jsonBody =
|
||||
JSONObject()
|
||||
.put("name", name)
|
||||
.apply { if (ssh != null) put("ssh", ssh.toJson()) }
|
||||
.toString(),
|
||||
readTimeoutMs = 40000,
|
||||
) {
|
||||
parseSetup(it.jsonObject())
|
||||
}
|
||||
|
||||
/** Renames a machine, and optionally asks it again what it has. */
|
||||
fun updateSetup(
|
||||
settings: ServerSettings,
|
||||
id: String,
|
||||
name: String? = null,
|
||||
rediscover: Boolean = false,
|
||||
): Setup =
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/setups/${id.urlEncoded()}",
|
||||
method = "PUT",
|
||||
jsonBody =
|
||||
JSONObject()
|
||||
.apply {
|
||||
if (name != null) put("name", name)
|
||||
if (rediscover) put("rediscover", true)
|
||||
}
|
||||
.toString(),
|
||||
readTimeoutMs = 40000,
|
||||
) {
|
||||
parseSetup(it.jsonObject())
|
||||
}
|
||||
|
||||
fun deleteSetup(settings: ServerSettings, id: String) {
|
||||
requestFromServer(settings, "/setups/${id.urlEncoded()}", method = "DELETE") {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawns a session and returns it as the list would show it. [setup] names the machine and
|
||||
* [provider] one of the things that machine offers.
|
||||
*/
|
||||
fun spawnSession(
|
||||
settings: ServerSettings,
|
||||
setup: String,
|
||||
provider: String,
|
||||
title: String,
|
||||
model: String? = null,
|
||||
cwd: String? = null,
|
||||
permissionMode: String? = null,
|
||||
params: Map<String, String> = emptyMap(),
|
||||
/** Continue this Claude Code session instead of starting an empty one. */
|
||||
import: String? = null,
|
||||
): SessionSummary =
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions",
|
||||
method = "POST",
|
||||
jsonBody =
|
||||
JSONObject()
|
||||
.put("setup", setup)
|
||||
.put("provider", provider)
|
||||
.put("title", title)
|
||||
.apply {
|
||||
if (!model.isNullOrBlank()) put("model", model)
|
||||
if (!cwd.isNullOrBlank()) put("cwd", cwd)
|
||||
if (!permissionMode.isNullOrBlank()) put("permissionMode", permissionMode)
|
||||
if (!import.isNullOrBlank()) put("import", import)
|
||||
if (params.isNotEmpty()) {
|
||||
put("params", JSONObject(params.toMap<String, Any>()))
|
||||
}
|
||||
}
|
||||
.toString(),
|
||||
readTimeoutMs = 30000,
|
||||
) { connection ->
|
||||
parseSession(connection.jsonObject())
|
||||
}
|
||||
|
||||
fun sendMessage(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
text: String,
|
||||
attachmentIds: List<String> = emptyList(),
|
||||
) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/message",
|
||||
method = "POST",
|
||||
jsonBody =
|
||||
JSONObject()
|
||||
.put("text", text)
|
||||
.put("attachmentIds", JSONArray(attachmentIds))
|
||||
.toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
/** Uploads one picked image; the returned id goes into [sendMessage]. */
|
||||
fun uploadAttachment(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
bytes: ByteArray,
|
||||
mime: String,
|
||||
): String {
|
||||
val boundary = "----aiapp-${System.currentTimeMillis()}"
|
||||
val head =
|
||||
("--$boundary\r\n" +
|
||||
"Content-Disposition: form-data; name=\"file\"; filename=\"image\"\r\n" +
|
||||
"Content-Type: $mime\r\n\r\n")
|
||||
.encodeToByteArray()
|
||||
val tail = "\r\n--$boundary--\r\n".encodeToByteArray()
|
||||
return requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/attachments",
|
||||
method = "POST",
|
||||
binaryBody = "multipart/form-data; boundary=$boundary" to (head + bytes + tail),
|
||||
readTimeoutMs = 60000,
|
||||
) { connection ->
|
||||
connection.jsonObject().getString("id")
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches an image the transcript references (produced or uploaded). */
|
||||
fun fetchSessionFile(settings: ServerSettings, sessionId: String, name: String): ByteArray =
|
||||
requestFromServer(settings, "/sessions/$sessionId/files/$name", readTimeoutMs = 30000) {
|
||||
it.inputStream.readBytes()
|
||||
}
|
||||
|
||||
// One rate-limit window, rendered as a labeled bar on the usage screen.
|
||||
data class UsageWindow(
|
||||
/**
|
||||
* The API's own word for which window this is -- "session" for the five-hour one.
|
||||
*
|
||||
* How to find a particular window. The label beside it is written for a person to read, so
|
||||
* matching on it would select nothing the day its wording changes.
|
||||
*/
|
||||
val kind: String,
|
||||
val label: String,
|
||||
val percent: Double,
|
||||
val resetsAt: String?,
|
||||
val active: Boolean,
|
||||
)
|
||||
|
||||
data class UsageSnapshot(
|
||||
val provider: String,
|
||||
/** Stable id of the machine these numbers belong to. */
|
||||
val setup: String,
|
||||
/** That machine's current label. */
|
||||
val setupName: String,
|
||||
/**
|
||||
* What came back: "ok", "notLoggedIn", "unreachable" or "failed".
|
||||
*
|
||||
* Four rather than a flag, because the screen has to treat them differently. "notLoggedIn" is a
|
||||
* machine somebody chose not to put an account on -- a fact, not a fault -- while the other two
|
||||
* are faults worth chasing. Collapsing them made a healthy setup read as broken.
|
||||
*/
|
||||
val state: String,
|
||||
/** Why, for the two states that are faults. Absent otherwise. */
|
||||
val detail: String?,
|
||||
val windows: List<UsageWindow>,
|
||||
)
|
||||
|
||||
/** The backend caches; refreshing more often than its poll interval just re-reads the cache. */
|
||||
fun fetchUsage(settings: ServerSettings): List<UsageSnapshot> =
|
||||
requestFromServer(settings, "/usage", readTimeoutMs = 30000) { connection ->
|
||||
connection.jsonObjects { snapshot ->
|
||||
UsageSnapshot(
|
||||
provider = snapshot.getString("provider"),
|
||||
setup = snapshot.optString("setup"),
|
||||
setupName = snapshot.optString("setupName"),
|
||||
// Unknown to an older backend, and unknown is not "fine": defaulting to "ok"
|
||||
// would draw an empty card as a healthy one.
|
||||
state = snapshot.optString("state").ifEmpty { "failed" },
|
||||
detail = snapshot.optString("detail").ifEmpty { null },
|
||||
windows =
|
||||
snapshot.getJSONArray("windows").mapObjects { window ->
|
||||
UsageWindow(
|
||||
kind = window.optString("kind").ifEmpty { "unknown" },
|
||||
label = window.getString("label"),
|
||||
percent = window.getDouble("percent"),
|
||||
resetsAt = window.optString("resetsAt").ifEmpty { null },
|
||||
active = window.getBoolean("active"),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers one question with everything that was chosen.
|
||||
*
|
||||
* A list even when one thing was picked, because that is the shape of the answer rather than a
|
||||
* special case of it. What a provider makes of several answers is its own business and is decided
|
||||
* on the server; nothing here joins, splits or reformats them for one.
|
||||
*/
|
||||
fun answerQuestion(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
questionId: String,
|
||||
answers: List<String>,
|
||||
) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/answer",
|
||||
method = "POST",
|
||||
jsonBody =
|
||||
JSONObject()
|
||||
.put("questionId", questionId)
|
||||
.put("answers", JSONArray(answers))
|
||||
.toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
fun interruptSession(settings: ServerSettings, sessionId: String) {
|
||||
requestFromServer(settings, "/sessions/$sessionId/interrupt", method = "POST") {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the process behind a session, leaving the session and its transcript.
|
||||
*
|
||||
* Not a delete and not an interrupt: the conversation stays exactly where it is and [startSession]
|
||||
* picks it back up. The server reports what it could not do -- there was nothing running, or the
|
||||
* machine would not say whether there was -- rather than answering the same way either way.
|
||||
*/
|
||||
fun stopSession(settings: ServerSettings, sessionId: String) {
|
||||
requestFromServer(settings, "/sessions/$sessionId/stop", method = "POST") {}
|
||||
}
|
||||
|
||||
/** Starts the process again on the conversation it left. See [stopSession]. */
|
||||
fun startSession(settings: ServerSettings, sessionId: String) {
|
||||
requestFromServer(settings, "/sessions/$sessionId/start", method = "POST") {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a Claude Code session from the machine.
|
||||
*
|
||||
* The transcript *is* the session, so this ends any chance of resuming that conversation. The
|
||||
* caller confirms first; see ImportScreen.
|
||||
*/
|
||||
fun deleteImportable(settings: ServerSettings, setup: String, sessionId: String) {
|
||||
requestFromServer(settings, "/setups/$setup/importable/$sessionId", method = "DELETE") {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A page of a session's transcript, oldest first within the page.
|
||||
*
|
||||
* One request instead of one stream frame per event. The SSE stream is the right shape for live
|
||||
* events and the wrong one for a backlog: opening an imported session replayed hundreds of frames
|
||||
* before anything was readable, which looked exactly like the app loading top-down, because it was.
|
||||
*
|
||||
* [before] pages backwards for history somebody scrolls to; absent means the newest page.
|
||||
*/
|
||||
fun fetchTranscript(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
before: Long? = null,
|
||||
limit: Int = 80,
|
||||
): List<SeqEvent> {
|
||||
val query = buildString {
|
||||
append("?limit=").append(limit)
|
||||
if (before != null) append("&before=").append(before)
|
||||
}
|
||||
return requestFromServer(settings, "/sessions/$sessionId/transcript$query") { connection ->
|
||||
val body = JSONArray(connection.inputStream.bufferedReader().readText())
|
||||
(0 until body.length()).map { parseSeqEvent(body.getJSONObject(it).toString()) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames a session.
|
||||
*
|
||||
* The name is the backend's own -- it is what the list shows and it exists before any process does
|
||||
* -- so this settles it rather than asking. Where the thing running the session has a name of its
|
||||
* own, the backend passes it on, which is what makes a session the same session in Claude Code's
|
||||
* picker and to any other agent that lists it.
|
||||
*/
|
||||
fun renameSession(settings: ServerSettings, sessionId: String, title: String) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/title",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("title", title).toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
/** Switches a running session's model; the CLI changes it in place. */
|
||||
fun setSessionModel(settings: ServerSettings, sessionId: String, model: String) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/model",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("model", model).toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The permission modes the Claude CLI accepts, in the order they give up asking. "manual" asks for
|
||||
* everything (each ask arrives on the phone as a question card); the others are the CLI's own
|
||||
* escalating levels of autonomy.
|
||||
*
|
||||
* One list for every screen that offers them -- spawn, import, and the session's own picker --
|
||||
* because three copies had already drifted: the import screen was missing "plan".
|
||||
*/
|
||||
val PERMISSION_MODES = listOf("manual", "acceptEdits", "auto", "bypassPermissions", "plan")
|
||||
|
||||
/** Switches how much a running session asks before acting, also in place. */
|
||||
fun setSessionPermissionMode(settings: ServerSettings, sessionId: String, mode: String) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/permission-mode",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("mode", mode).toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
/** Turns this session's notifications on or off. Stored on the backend -- see `SessionConfig`. */
|
||||
fun setSessionNotify(settings: ServerSettings, sessionId: String, notify: Boolean) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/notify",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("notify", notify).toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the session to run one of its own commands.
|
||||
*
|
||||
* Sent as typed. The server turns the two it understands into its own operations -- a compaction, a
|
||||
* rename, which is also what the settings screen sends -- and passes anything else to whatever runs
|
||||
* the session. Either way it waits for the turn to end if one is in flight, and says so on the
|
||||
* event stream, which is where the waiting bubble comes from.
|
||||
*/
|
||||
fun runCommand(settings: ServerSettings, sessionId: String, text: String) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/sessions/$sessionId/command",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("text", text).toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the session to summarise its own history and carry on from the summary.
|
||||
*
|
||||
* Nothing comes back here: a compaction takes a minute or two, and what it is doing arrives on the
|
||||
* event stream like everything else -- a `compacting` status while it runs, then how much context
|
||||
* it recovered. A call that waited would be a second, worse account of the same thing.
|
||||
*/
|
||||
fun compactSession(settings: ServerSettings, sessionId: String) {
|
||||
requestFromServer(settings, "/sessions/$sessionId/compact", method = "POST") {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a session, and optionally the machine's own transcript of the same conversation.
|
||||
*
|
||||
* [deleteForeign] is the delete this app cannot otherwise reach: Claude Code keeps its own record
|
||||
* under `~/.claude/projects`, and leaving it is what makes an ordinary delete recoverable. The
|
||||
* server does both halves, and does the unrecoverable one first, so a machine it cannot reach
|
||||
* leaves the session exactly where it was rather than half-deleted.
|
||||
*/
|
||||
fun deleteSession(settings: ServerSettings, sessionId: String, deleteForeign: Boolean = false) {
|
||||
val query = if (deleteForeign) "?deleteForeign=true" else ""
|
||||
requestFromServer(settings, "/sessions/$sessionId$query", method = "DELETE") {}
|
||||
}
|
||||
|
||||
// Models: what this backend has downloaded, what it is downloading, and
|
||||
// what HuggingFace offers. Browsing is proxied by the server rather than
|
||||
// done here, because this app trusts exactly one certificate and has no
|
||||
// general internet trust to spend on huggingface.co.
|
||||
|
||||
data class LocalModel(val key: String, val repo: String, val file: String, val bytes: Long)
|
||||
|
||||
/**
|
||||
* A download in flight or finished. [total] is null when the server never said how big the file is
|
||||
* -- which must render as "not known", never as a bar at some invented position.
|
||||
*/
|
||||
data class Download(
|
||||
val key: String,
|
||||
val run: Long,
|
||||
val repo: String,
|
||||
val file: String,
|
||||
val state: String,
|
||||
val done: Long,
|
||||
val total: Long?,
|
||||
val error: String?,
|
||||
)
|
||||
|
||||
data class Models(val local: List<LocalModel>, val downloads: List<Download>)
|
||||
|
||||
data class RemoteRepo(val id: String, val downloads: Long, val likes: Long)
|
||||
|
||||
data class RemoteFile(val path: String, val bytes: Long, val have: Boolean)
|
||||
|
||||
private fun parseDownload(o: JSONObject) =
|
||||
Download(
|
||||
key = o.getString("key"),
|
||||
run = o.getLong("run"),
|
||||
repo = o.getString("repo"),
|
||||
file = o.getString("file"),
|
||||
state = o.getString("state"),
|
||||
done = o.getLong("done"),
|
||||
// Absent rather than zero when unknown; see the field's comment.
|
||||
total = if (o.has("total")) o.getLong("total") else null,
|
||||
error = if (o.has("error")) o.getString("error") else null,
|
||||
)
|
||||
|
||||
fun fetchModels(settings: ServerSettings): Models =
|
||||
requestFromServer(settings, "/models") { connection ->
|
||||
val body = JSONObject(connection.inputStream.bufferedReader().readText())
|
||||
Models(
|
||||
local =
|
||||
body.getJSONArray("local").mapObjects { m ->
|
||||
LocalModel(
|
||||
key = m.getString("key"),
|
||||
repo = m.getString("repo"),
|
||||
file = m.getString("file"),
|
||||
bytes = m.getLong("bytes"),
|
||||
)
|
||||
},
|
||||
downloads = body.getJSONArray("downloads").mapObjects(::parseDownload),
|
||||
)
|
||||
}
|
||||
|
||||
fun searchModels(settings: ServerSettings, query: String): List<RemoteRepo> =
|
||||
requestFromServer(settings, "/models/search?q=${query.urlEncoded()}") { connection ->
|
||||
connection.jsonObjects { r ->
|
||||
RemoteRepo(
|
||||
id = r.getString("id"),
|
||||
downloads = r.getLong("downloads"),
|
||||
likes = r.getLong("likes"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun fetchRepoFiles(settings: ServerSettings, repo: String): List<RemoteFile> =
|
||||
requestFromServer(settings, "/models/files?repo=${repo.urlEncoded()}") { connection ->
|
||||
connection.jsonObjects { f ->
|
||||
RemoteFile(
|
||||
path = f.getString("path"),
|
||||
bytes = f.getLong("bytes"),
|
||||
have = f.getBoolean("have"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun startDownload(settings: ServerSettings, repo: String, file: String): Download =
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/models/download",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("repo", repo).put("file", file).toString(),
|
||||
) { connection ->
|
||||
parseDownload(JSONObject(connection.inputStream.bufferedReader().readText()))
|
||||
}
|
||||
|
||||
fun cancelDownload(settings: ServerSettings, key: String) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/models/cancel",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("key", key).toString(),
|
||||
) {}
|
||||
}
|
||||
|
||||
fun deleteModel(settings: ServerSettings, key: String) {
|
||||
requestFromServer(
|
||||
settings,
|
||||
"/models/delete",
|
||||
method = "POST",
|
||||
jsonBody = JSONObject().put("key", key).toString(),
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.example.wgapplink.localNetworkAllowed
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* One `when` rather than a navigation library: a handful of screens, with [Screen.Main] as the root
|
||||
* and the back button the only other way between them.
|
||||
*
|
||||
* Import, models and setups are not here any more. They are tabs inside [MainScreen] -- four views
|
||||
* of the same backend, none of them a step down from another -- and what is left in this `when` is
|
||||
* only what genuinely is a step down: one session, spawning one, and settings. A session's own
|
||||
* settings are not among them: they are a dialog over the session, which is where the thing they
|
||||
* change is.
|
||||
*/
|
||||
private sealed class Screen {
|
||||
data object Main : Screen()
|
||||
|
||||
data class Session(val summary: SessionSummary) : Screen()
|
||||
|
||||
data object Spawn : Screen()
|
||||
|
||||
data object Settings : Screen()
|
||||
}
|
||||
|
||||
/**
|
||||
* A session a notification tap asked to open, before it is a screen.
|
||||
*
|
||||
* The notification names an id and nothing else, so opening it means fetching the session first.
|
||||
* [serial] tells two taps on the same session's notification apart, since they are two requests and
|
||||
* would otherwise compare equal -- see MainActivity, which counts them.
|
||||
*/
|
||||
data class SessionOpenRequest(val sessionId: String, val serial: Int)
|
||||
|
||||
/** A tap that could not be turned into a screen, kept with its request so Try again knows what. */
|
||||
private data class FailedOpen(val request: SessionOpenRequest, val message: String)
|
||||
|
||||
/**
|
||||
* [settingsVersion] bumps when enrollment lands via an `aiapp://` intent (see MainActivity),
|
||||
* re-reading the stored settings -- a plain `remember` would keep serving the pre-enrollment null.
|
||||
*
|
||||
* [openRequest] is the session a notification tap asked for, likewise from MainActivity.
|
||||
*/
|
||||
@Composable
|
||||
fun AppRoot(settingsVersion: Int, openRequest: SessionOpenRequest?) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var settings by remember(settingsVersion) { mutableStateOf(loadServerSettings(context)) }
|
||||
var screen by remember { mutableStateOf<Screen>(Screen.Main) }
|
||||
// A notification tap this could not follow, and why. Null both before one is asked for and
|
||||
// after one succeeds, since success is a screen rather than a message.
|
||||
var failedOpen by remember { mutableStateOf<FailedOpen?>(null) }
|
||||
// Bumped whenever another screen changes something the list shows, so
|
||||
// returning to it refetches instead of showing a stale list.
|
||||
var reloadToken by remember { mutableIntStateOf(0) }
|
||||
|
||||
// A standing condition rather than a per-request failure, so it is
|
||||
// stated once here instead of appended to every error that might be
|
||||
// caused by it. Without this the app is simply unreachable and every
|
||||
// screen blames the server or the tunnel for it.
|
||||
if (!localNetworkAllowed(context)) {
|
||||
Text(
|
||||
"This app is not allowed to reach local network addresses, so it cannot " +
|
||||
"connect to the backend at all. Grant \"local network\" in Android's app " +
|
||||
"settings; until then every screen here will look like the server is down.",
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(16.dp),
|
||||
)
|
||||
}
|
||||
|
||||
val current = settings
|
||||
if (current == null) {
|
||||
// Not enrolled yet: settings is the only usable screen. The QR
|
||||
// path lands in MainActivity and recomposes from the top.
|
||||
Box(Modifier.imePadding()) {
|
||||
SettingsScreen(
|
||||
existing = null,
|
||||
onSaved = { saved ->
|
||||
settings = saved
|
||||
screen = Screen.Main
|
||||
},
|
||||
onBack = null,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// The one way back, whichever screen is showing and whether it was
|
||||
// reached by the system back gesture or a screen's own Back button.
|
||||
// Every leaf screen can have changed something the list shows, so it
|
||||
// always refetches.
|
||||
val goToMain = {
|
||||
reloadToken++
|
||||
screen = Screen.Main
|
||||
}
|
||||
if (screen !is Screen.Main) {
|
||||
BackHandler(onBack = goToMain)
|
||||
}
|
||||
|
||||
// Turning a notification into the screen it points at. The id has to be resolved to a session
|
||||
// first, because that is what SessionScreen is given -- and unlike a list row, which is a
|
||||
// snapshot the list already fetched, there is nothing here to seed it from.
|
||||
//
|
||||
// A failure is reported rather than swallowed: somebody deliberately tapped a notification, so
|
||||
// an app that opens to the session list with no explanation looks like the tap missed.
|
||||
val open: suspend (SessionOpenRequest) -> Unit = { request ->
|
||||
failedOpen = null
|
||||
try {
|
||||
val session = withContext(Dispatchers.IO) { fetchSession(current, request.sessionId) }
|
||||
screen = Screen.Session(session)
|
||||
} catch (e: ApiException) {
|
||||
failedOpen = FailedOpen(request, e.message ?: "Unknown error")
|
||||
}
|
||||
}
|
||||
LaunchedEffect(openRequest) { openRequest?.let { open(it) } }
|
||||
|
||||
val failed = failedOpen
|
||||
if (failed != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { failedOpen = null },
|
||||
title = { Text("Couldn't open that session") },
|
||||
text = { Text(failed.message) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { scope.launch { open(failed.request) } }) {
|
||||
Text("Try again")
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { failedOpen = null }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
// Every screen but the session takes the keyboard as bottom padding here. The session
|
||||
// screen deliberately does not: resizing a whole screen on every frame of the keyboard
|
||||
// animation is the cost that made it lag, so it moves only its composer and transcript --
|
||||
// see the layout note in SessionScreen.
|
||||
when (val here = screen) {
|
||||
is Screen.Main ->
|
||||
Box(Modifier.imePadding()) {
|
||||
MainScreen(
|
||||
settings = current,
|
||||
reloadToken = reloadToken,
|
||||
onOpen = { screen = Screen.Session(it) },
|
||||
onSpawn = { screen = Screen.Spawn },
|
||||
onImported = { imported ->
|
||||
reloadToken++
|
||||
screen = Screen.Session(imported)
|
||||
},
|
||||
onSettings = { screen = Screen.Settings },
|
||||
)
|
||||
}
|
||||
is Screen.Session ->
|
||||
// Keyed on the id, because a different session is a different screen rather than this
|
||||
// one showing other rows. SessionScreen remembers a transcript, an open event stream, a
|
||||
// draft and a scroll position, and without the key Compose keeps all of it across the
|
||||
// change and merges two conversations -- which crashes the list on the first duplicate
|
||||
// row key. Only reachable since a notification can move straight from one session to
|
||||
// another; every other way here passes through [Screen.Main], which disposes it anyway.
|
||||
key(here.summary.id) {
|
||||
SessionScreen(settings = current, summary = here.summary, onBack = goToMain)
|
||||
}
|
||||
is Screen.Spawn ->
|
||||
Box(Modifier.imePadding()) {
|
||||
SpawnScreen(
|
||||
settings = current,
|
||||
onSpawned = { spawned ->
|
||||
reloadToken++
|
||||
screen = Screen.Session(spawned)
|
||||
},
|
||||
onBack = goToMain,
|
||||
)
|
||||
}
|
||||
is Screen.Settings ->
|
||||
Box(Modifier.imePadding()) {
|
||||
SettingsScreen(
|
||||
existing = current,
|
||||
onSaved = { saved ->
|
||||
settings = saved
|
||||
goToMain()
|
||||
},
|
||||
onBack = goToMain,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Last, so it draws over the screen above rather than under it: these are stacked in the Box
|
||||
// the activity puts around this, and that Box paints in the order it was given. A session
|
||||
// wanting attention is not a fact about the page somebody happens to be on, so it is not the
|
||||
// page's job to leave room for it. Tapping one is the same act as tapping a notification, so
|
||||
// it goes through the same `open`, failure dialog included.
|
||||
SessionAlerts(onOpen = { request -> scope.launch { open(request) } })
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedCard
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* Every question one tool call is waiting on.
|
||||
*
|
||||
* All of it comes from the question events themselves -- what each option means, what picking it
|
||||
* would produce, whether several may be picked at once. None of it is read out of the call's own
|
||||
* input, which is one provider's JSON: parsing that here would put that provider's schema in the
|
||||
* app, where no other provider can reach it and where it drifts the first time the schema moves.
|
||||
*/
|
||||
@Composable
|
||||
fun AskUserQuestionBody(
|
||||
asks: List<TranscriptItem.QuestionCard>,
|
||||
onAnswer: (questionId: String, answers: List<String>) -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
asks.forEach { ask ->
|
||||
Spacer(Modifier.height(12.dp))
|
||||
AskedQuestion(ask) { answers -> onAnswer(ask.id, answers) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One question: what is being asked, what can be answered, and what was.
|
||||
*
|
||||
* The same body wherever a question appears -- on the call that asked it, or as a card of its own
|
||||
* when nothing did. A question is the same thing either way, and two renderings of it would be two
|
||||
* places for an answer to go missing.
|
||||
*/
|
||||
@Composable
|
||||
fun AskedQuestion(ask: TranscriptItem.QuestionCard, onAnswer: (List<String>) -> Unit) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
ask.header?.let { header ->
|
||||
// Its own line rather than beside the question, because it is a label *for* the
|
||||
// question and the question is the thing to read.
|
||||
Text(
|
||||
header.uppercase(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(ask.prompt, style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
if (ask.answers.isNotEmpty()) {
|
||||
// Joined for reading only: they arrived as a list and stay one everywhere else.
|
||||
Text(
|
||||
"Answered: ${ask.answers.joinToString(", ")}",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
return@Column
|
||||
}
|
||||
if (ask.multiSelect) {
|
||||
MultipleChoice(ask.options, onAnswer)
|
||||
} else if (ask.options.all { it.description == null && it.preview == null }) {
|
||||
// Nothing to read, so nothing to lay out: Allow and Deny are two words, and two words
|
||||
// do not need a card each.
|
||||
AnswerOptions(ask.options, onAnswer)
|
||||
} else {
|
||||
ask.options.forEach { option ->
|
||||
OptionCard(option, selected = false) { onAnswer(listOf(option.label)) }
|
||||
}
|
||||
}
|
||||
OtherAnswer(onAnswer)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Options that can be chosen together, with one button to send them.
|
||||
*
|
||||
* The answer goes back as the list it is. What a provider makes of several answers is decided where
|
||||
* that provider is spoken to -- Claude Code's answers map holds a string, so they are joined there
|
||||
* -- and nothing on this side has to know that.
|
||||
*/
|
||||
@Composable
|
||||
private fun MultipleChoice(options: List<QuestionOption>, onAnswer: (List<String>) -> Unit) {
|
||||
var chosen by remember { mutableStateOf(setOf<String>()) }
|
||||
options.forEach { option ->
|
||||
OptionCard(option, selected = option.label in chosen) {
|
||||
chosen = if (option.label in chosen) chosen - option.label else chosen + option.label
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
OutlinedButton(
|
||||
// In the order they were offered rather than the order they were tapped: the reader is
|
||||
// answering a list, and it should read back as that list.
|
||||
onClick = { onAnswer(options.map { it.label }.filter { it in chosen }) },
|
||||
enabled = chosen.isNotEmpty(),
|
||||
) {
|
||||
Text(if (chosen.size <= 1) "Send answer" else "Send ${chosen.size} answers")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One option: what it is called, what it means, and what it would produce.
|
||||
*
|
||||
* Outlined rather than tinted. Drawn first as a card one step up the surface ladder, it was
|
||||
* indistinguishable from the card behind it -- three paragraphs of text where three things to press
|
||||
* should have been, which is the failure a tint step routinely produces on a dark theme. A border
|
||||
* is one cue and it is unambiguous.
|
||||
*/
|
||||
@Composable
|
||||
private fun OptionCard(option: QuestionOption, selected: Boolean, onPick: () -> Unit) {
|
||||
OutlinedCard(
|
||||
onClick = onPick,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
colors =
|
||||
CardDefaults.outlinedCardColors(
|
||||
containerColor =
|
||||
if (selected) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surface
|
||||
),
|
||||
// Picked shows in the border as well as the fill, because the fill alone is a colour
|
||||
// difference somebody has to have seen the unpicked version to notice.
|
||||
border =
|
||||
BorderStroke(
|
||||
if (selected) 2.dp else 1.dp,
|
||||
if (selected) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(option.label, style = MaterialTheme.typography.titleSmall)
|
||||
option.description?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
option.preview?.let { Preview(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An option's worked example, shown as written.
|
||||
*
|
||||
* On its own surface, because it is a different kind of thing from the sentence above it: that
|
||||
* describes the option, this is a sample of what the option produces, and monospace alone reads as
|
||||
* a description that happens to be in code font.
|
||||
*/
|
||||
@Composable
|
||||
private fun Preview(preview: String) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLowest,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
preview,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
// Not wrapped: these are mockups and diffs, where a wrapped line reads as two lines
|
||||
// of the thing being previewed.
|
||||
softWrap = false,
|
||||
modifier = Modifier.padding(8.dp).horizontalScroll(rememberScrollState()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The choice the asker always leaves open, and the app has to as well.
|
||||
*
|
||||
* Every AskUserQuestion carries an implicit "Other" -- the reader may answer in their own words
|
||||
* rather than pick. Leaving it out narrows a question that was never that narrow, and the reader
|
||||
* cannot tell that it was ever open.
|
||||
*/
|
||||
@Composable
|
||||
private fun OtherAnswer(onAnswer: (List<String>) -> Unit) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
Row(Modifier.fillMaxWidth().padding(top = 8.dp)) {
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
label = { Text("Other") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { onAnswer(listOf(text.trim())) }, enabled = text.isNotBlank()) {
|
||||
Text("Send")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bare options, wrapped rather than in a row.
|
||||
*
|
||||
* A Row hands out intrinsic widths in order and clips whatever runs past the edge, so a question
|
||||
* with four options showed the first one or two and dropped the rest off the side of the screen.
|
||||
* That does not read as a bug: it reads as those having been the only choices, which is the worst
|
||||
* way for a list of choices to be wrong.
|
||||
*/
|
||||
@Composable
|
||||
fun AnswerOptions(options: List<QuestionOption>, onAnswer: (List<String>) -> Unit) {
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
options.forEach { option ->
|
||||
OutlinedButton(onClick = { onAnswer(listOf(option.label)) }) { Text(option.label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import android.net.Uri
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import java.io.ByteArrayOutputStream
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Getting a picked photo to a session, at a size the session can actually take.
|
||||
*
|
||||
* A phone camera produces twelve megapixels and several megabytes. The Claude API resizes anything
|
||||
* larger than 1568px on its long edge before looking at it and refuses images past a much higher
|
||||
* bound outright, so a photo sent straight off the camera roll was uploaded whole over the tunnel
|
||||
* to be either thrown away or rejected -- which is what "sending an image is broken" was.
|
||||
*
|
||||
* Shrunk here rather than on the backend, so the bytes that never mattered are never sent: the
|
||||
* expensive part of this on a phone is the upload, not the decode. What the limit *is* comes from
|
||||
* the server, per session -- see `DriverKind::max_image_edge` -- because that is where a provider's
|
||||
* requirements are known, and a phone that carried its own copy of them would be a second place to
|
||||
* update when one changes.
|
||||
*/
|
||||
suspend fun uploadPickedImage(
|
||||
context: Context,
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
uri: Uri,
|
||||
maxEdge: Int?,
|
||||
): String {
|
||||
val (bytes, mime) = readForUpload(context, uri, maxEdge)
|
||||
return uploadAttachment(settings, sessionId, bytes, mime)
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes to upload and what they are, scaled down only if they need to be.
|
||||
*
|
||||
* An image already inside the limit is uploaded exactly as it came, rather than decoded and
|
||||
* re-encoded to the same size: a round trip through JPEG loses a little every time, and there is
|
||||
* nothing to gain from it. This is also the path a provider with no limit always takes.
|
||||
*/
|
||||
private fun readForUpload(context: Context, uri: Uri, maxEdge: Int?): Pair<ByteArray, String> {
|
||||
val resolver = context.contentResolver
|
||||
val mime = resolver.getType(uri) ?: "image/jpeg"
|
||||
val original =
|
||||
resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw ApiException("couldn't read the picked image")
|
||||
if (maxEdge == null) return original to mime
|
||||
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(original, 0, original.size, bounds)
|
||||
val longest = max(bounds.outWidth, bounds.outHeight)
|
||||
// outWidth is -1 when the bytes are not an image this device can decode. Sent on untouched:
|
||||
// this function's job is the size, and refusing something the server might understand is a
|
||||
// decision it has no business making.
|
||||
if (longest <= 0 || longest <= maxEdge) return original to mime
|
||||
|
||||
// Powers of two first, which is all the decoder can do, and then the exact scale. Decoding
|
||||
// the full twelve megapixels only to shrink it is how this runs out of memory on the images
|
||||
// it most needs to handle.
|
||||
val decode =
|
||||
BitmapFactory.Options().apply {
|
||||
inSampleSize = Integer.highestOneBit(max(1, longest / maxEdge))
|
||||
}
|
||||
val decoded =
|
||||
BitmapFactory.decodeByteArray(original, 0, original.size, decode) ?: return original to mime
|
||||
val scale = maxEdge.toFloat() / max(decoded.width, decoded.height)
|
||||
val matrix = Matrix()
|
||||
if (scale < 1f) matrix.postScale(scale, scale)
|
||||
// The camera writes which way up the picture is into EXIF rather than rotating the pixels, and
|
||||
// re-encoding drops the tag -- so a portrait photo would arrive at the model on its side, with
|
||||
// nothing anywhere saying so. Applied to the same matrix as the scale, so it costs no second
|
||||
// copy of the bitmap.
|
||||
matrix.postRotate(exifRotation(original))
|
||||
val scaled = Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||
val out = ByteArrayOutputStream()
|
||||
// JPEG whatever came in: this is a photograph being made smaller, which is what JPEG is for,
|
||||
// and a PNG of a resampled photo is several times the size for no visible difference.
|
||||
scaled.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)
|
||||
return out.toByteArray() to "image/jpeg"
|
||||
}
|
||||
|
||||
/** How far to turn the picture so it is the way up it was taken. */
|
||||
private fun exifRotation(bytes: ByteArray): Float =
|
||||
try {
|
||||
when (
|
||||
ExifInterface(bytes.inputStream())
|
||||
.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
|
||||
) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> 90f
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> 180f
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> 270f
|
||||
else -> 0f
|
||||
}
|
||||
} catch (_: java.io.IOException) {
|
||||
// No EXIF, or none this can read. Upright is the assumption every
|
||||
// image without the tag is displayed under anyway.
|
||||
0f
|
||||
}
|
||||
|
||||
/** High enough that resampling is what the reader notices, not the encoder. */
|
||||
private const val JPEG_QUALITY = 90
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.graphics.ColorFilter
|
||||
import androidx.compose.ui.graphics.ColorMatrix
|
||||
import androidx.compose.ui.graphics.Paint
|
||||
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* An item something is happening to: dimmed, drained of colour, inert, with a spinner and the name
|
||||
* of the operation over it.
|
||||
*
|
||||
* One composable rather than a pattern each list repeats, because "this row is busy" has to look
|
||||
* the same in the import list and the session list or the appearance becomes a per-screen dialect
|
||||
* rather than something the reader learns once.
|
||||
*
|
||||
* [label] names the operation and `null` means none is running. One parameter rather than a boolean
|
||||
* beside a string, which can disagree: there is no such thing as busy with nothing happening. It is
|
||||
* a *word* because a spinner alone cannot say which operation this is — deleting and importing are
|
||||
* different in kind, and losing a session to the wrong one is not recoverable by waiting.
|
||||
*
|
||||
* It does **not** make the row inert; the caller disables its own click handling while it passes a
|
||||
* label. That was the other way round at first — an overlay consuming pointer events, so no caller
|
||||
* had to remember — and it swallowed the drag along with the tap, which meant a list could not be
|
||||
* scrolled while anything in it was busy. Consuming taps but not drags means re-deciding what a
|
||||
* gesture is above the components that already decide it; disabling the click is the platform's own
|
||||
* answer and leaves the scroll where it belongs.
|
||||
*/
|
||||
@Composable
|
||||
fun BusyItem(label: String?, content: @Composable () -> Unit) {
|
||||
Box {
|
||||
Box(Modifier.busy(label != null)) { content() }
|
||||
if (label != null) {
|
||||
Box(Modifier.matchParentSize(), contentAlignment = Alignment.Center) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.width(16.dp).height(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// Full strength, over content that is not: the operation is the one thing on
|
||||
// this row that is still current, and it has to read against a card whose own
|
||||
// text is still visible behind it.
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How an item looks while it is being acted on: darker, and nearly grey.
|
||||
*
|
||||
* Both, rather than either alone. Dimming by itself is what this app already used for a row on its
|
||||
* way out, and it is the same cue as a disabled control, so a busy row read as one more thing that
|
||||
* could not be tapped. Draining the colour is what says the row is *suspended* — the status word,
|
||||
* the accent on a warning and everything else that means something by its colour stop meaning it
|
||||
* for as long as the operation runs, which is exactly true: none of them is being kept up to date.
|
||||
*
|
||||
* Not all the way to grey. A row with no colour left is hard to find again in a list, and the
|
||||
* reader is watching this one.
|
||||
*/
|
||||
private fun Modifier.busy(busy: Boolean): Modifier =
|
||||
if (!busy) this
|
||||
else
|
||||
this.graphicsLayer { alpha = 0.5f }
|
||||
.drawWithContent {
|
||||
drawIntoCanvas { canvas ->
|
||||
canvas.saveLayer(
|
||||
Rect(Offset.Zero, size),
|
||||
Paint().apply {
|
||||
colorFilter =
|
||||
ColorFilter.colorMatrix(
|
||||
ColorMatrix().apply { setToSaturation(0.2f) }
|
||||
)
|
||||
},
|
||||
)
|
||||
drawContent()
|
||||
canvas.restore()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* A chevron, pointing up or down.
|
||||
*
|
||||
* Drawn rather than set in a font: a chevron from an icon font is one of the glyphs a system font
|
||||
* may simply not have, and the reader who gets an empty box instead is never the one who wrote it.
|
||||
*
|
||||
* One composable for both directions rather than two that differ by a minus sign -- the pair would
|
||||
* drift, and the drift would be a bug in exactly one direction.
|
||||
*
|
||||
* It draws no label of its own, so every caller owes it a `contentDescription`: this is the whole
|
||||
* of what assistive technology has to go on, and it is also the answer to "what was that arrow for"
|
||||
* six months from now.
|
||||
*/
|
||||
@Composable
|
||||
fun Chevron(
|
||||
pointingUp: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
colour: Color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
) {
|
||||
Canvas(modifier.width(20.dp).height(10.dp)) {
|
||||
val inset = 2.dp.toPx()
|
||||
val point = if (pointingUp) inset else size.height - inset
|
||||
val ends = if (pointingUp) size.height - inset else inset
|
||||
val stroke = 2.dp.toPx()
|
||||
drawLine(
|
||||
colour,
|
||||
Offset(inset, ends),
|
||||
Offset(size.width / 2, point),
|
||||
strokeWidth = stroke,
|
||||
cap = StrokeCap.Round,
|
||||
)
|
||||
drawLine(
|
||||
colour,
|
||||
Offset(size.width / 2, point),
|
||||
Offset(size.width - inset, ends),
|
||||
strokeWidth = stroke,
|
||||
cap = StrokeCap.Round,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* Something a session can be asked to do to itself, rather than something to say to it.
|
||||
*
|
||||
* These are the two this app understands, and understanding them is what lets it show them: a
|
||||
* suggestion while one is being typed, a name in the settings screen that sends one, and a bubble
|
||||
* that stays up while the session is too busy to run it. Anything else beginning with "/" is passed
|
||||
* through to whatever runs the session, because a dialect's own vocabulary is its own and grows
|
||||
* without this list -- it just arrives unannounced and unexplained.
|
||||
*/
|
||||
data class SessionCommand(
|
||||
/** With the slash, as it is typed and as it is sent. */
|
||||
val name: String,
|
||||
/** One line, in the suggestion list: what it does, not how. */
|
||||
val summary: String,
|
||||
/** What follows the name, named for the reader, or null when nothing does. */
|
||||
val argument: String?,
|
||||
) {
|
||||
/** What to put in the box when this is picked: ready to send, or ready to be finished. */
|
||||
fun typed(): String = if (argument == null) name else "$name "
|
||||
}
|
||||
|
||||
val SESSION_COMMANDS =
|
||||
listOf(
|
||||
SessionCommand(
|
||||
"/compact",
|
||||
"Summarise the conversation so far and carry on from the summary",
|
||||
null,
|
||||
),
|
||||
SessionCommand(
|
||||
"/clear",
|
||||
"Start fresh: drop the conversation from the session's context, keeping it on screen",
|
||||
null,
|
||||
),
|
||||
SessionCommand("/rename", "Change what this session is called", "name"),
|
||||
)
|
||||
|
||||
/**
|
||||
* The commands worth offering for what has been typed so far.
|
||||
*
|
||||
* Only for a line that starts with a slash and has not yet become a whole command with an argument
|
||||
* -- once there is something after "/rename ", the reader is writing the name and a list of
|
||||
* commands underneath it is in the way.
|
||||
*/
|
||||
fun suggestedCommands(input: String): List<SessionCommand> {
|
||||
if (!input.startsWith("/") || input.contains(' ')) return emptyList()
|
||||
return SESSION_COMMANDS.filter { it.name.startsWith(input) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands matching what is being typed, above the box they are being typed into.
|
||||
*
|
||||
* Above rather than over: a list that covers the transcript hides what the command is about, and
|
||||
* the reader is usually looking at the thing they mean to act on.
|
||||
*/
|
||||
@Composable
|
||||
fun CommandSuggestions(
|
||||
commands: List<SessionCommand>,
|
||||
onPick: (SessionCommand) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (commands.isEmpty()) return
|
||||
Card(modifier.fillMaxWidth().padding(horizontal = 16.dp)) {
|
||||
Column(Modifier.padding(vertical = 4.dp)) {
|
||||
commands.forEach { command ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth()
|
||||
.clickable { onPick(command) }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
// The command in the colour commands are, so the suggestion and the
|
||||
// bubble it becomes are visibly the same thing.
|
||||
if (command.argument == null) command.name
|
||||
else "${command.name} <${command.argument}>",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = commandColor,
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
command.summary,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A command, where the reader put it: at their end of the conversation.
|
||||
*
|
||||
* Blue rather than the colour of something they said, because they did not say it to the model --
|
||||
* it is an instruction to the session, and the reply to it is the session changing rather than
|
||||
* anything appearing here.
|
||||
*
|
||||
* [waiting] is a command the session is too busy to run yet, which is a state with a spinner and a
|
||||
* reason: pressing Compact in the middle of a long turn otherwise does nothing visible for minutes
|
||||
* and reads as having been missed.
|
||||
*/
|
||||
@Composable
|
||||
fun CommandBubble(text: String, waiting: Boolean = false) {
|
||||
Box(Modifier.fillMaxWidth()) {
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = commandColor),
|
||||
modifier = Modifier.align(Alignment.CenterEnd).padding(start = 48.dp),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
// Stated beside the fill rather than inherited: a semantic colour has to carry
|
||||
// its own contrast, because the surface under it will not change to rescue it.
|
||||
Text(text, color = MaterialTheme.colorScheme.inverseOnSurface)
|
||||
if (waiting) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.width(12.dp).height(12.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.inverseOnSurface,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"waiting for this turn to end",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.inverseOnSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
|
||||
/**
|
||||
* The mark a compaction leaves in the transcript.
|
||||
*
|
||||
* A divider rather than something anybody said: everything above it is out of the session's context
|
||||
* now, and that is a fact about the conversation, not a turn in it. It has no collapsed form -- it
|
||||
* is already one line, and there is nothing behind it to open. Drawn by [TranscriptDivider], which
|
||||
* a clear also uses, so the two marks cannot drift apart.
|
||||
*
|
||||
* Blue is [commandColor]: the session acting on itself rather than working on what was asked of it,
|
||||
* which is the same thing the status line says while the compaction runs.
|
||||
*/
|
||||
@Composable
|
||||
fun CompactedRow(item: TranscriptItem.CompactedNote, modifier: Modifier = Modifier) {
|
||||
TranscriptDivider(compactionSummary(item), commandColor, modifier)
|
||||
}
|
||||
|
||||
/**
|
||||
* What to say about a compaction: the two sizes, and nothing else.
|
||||
*
|
||||
* The counts are the whole point -- "a million tokens became ten thousand" is the reader's answer
|
||||
* to why the wait was worth it -- and they are all this says, because a divider is read in passing.
|
||||
* When they were not reported this says only that a compaction happened, rather than filling in a
|
||||
* plausible number or explaining at length what was missing.
|
||||
*/
|
||||
fun compactionSummary(item: TranscriptItem.CompactedNote): String {
|
||||
val pre = item.preTokens
|
||||
val post = item.postTokens
|
||||
return if (pre != null && post != null) {
|
||||
"Compacted • ${tokens(pre)} → ${tokens(post)} tok"
|
||||
} else {
|
||||
"Compacted"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A token count as a reader reads one.
|
||||
*
|
||||
* Shared with the status row rather than formatted at each: the divider and the row report the same
|
||||
* quantity about the same moment, and one of them grouping its thousands while the other did not
|
||||
* read as two different measurements.
|
||||
*/
|
||||
fun tokens(count: Long): String = "%,d".format(count)
|
||||
|
||||
/**
|
||||
* What the working indicator says while a compaction is running.
|
||||
*
|
||||
* Elapsed time and nothing else, because elapsed time is all there is: the CLI announces that a
|
||||
* compaction has begun and then says nothing until it has finished, so any bar, percentage or
|
||||
* estimate here would be this screen's guess wearing a measurement's clothes. Knowing it has been
|
||||
* going forty seconds is what a reader actually wants -- it is the difference between waiting and
|
||||
* going to look at why.
|
||||
*
|
||||
* [seconds] is null when this device did not see the compaction start, which is what opening a
|
||||
* session that is already compacting looks like. That case says only "compacting": no number is the
|
||||
* honest answer, and a number counted from the moment the screen opened would be wrong in the
|
||||
* direction that matters, since a compaction somebody is asking about is a long one.
|
||||
*/
|
||||
fun compactingLabel(seconds: Long?): String =
|
||||
when {
|
||||
seconds == null -> "compacting"
|
||||
seconds < 60 -> "compacting ${seconds}s"
|
||||
else -> "compacting ${seconds / 60}m ${seconds % 60}s"
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
import java.io.StringWriter
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The last crash, kept so the debug button can hand it over.
|
||||
*
|
||||
* The alternative is asking somebody to reproduce a crash with the phone plugged into a computer
|
||||
* and `logcat` running, which is the one thing nobody has set up at the moment it happens -- and a
|
||||
* crash report that arrives a day later, without the stack, is a guess. This costs one file write
|
||||
* on a process that is already dying, and it turns "it crashes when I open that chat" into the
|
||||
* frame it crashed in.
|
||||
*
|
||||
* Kept until it is read rather than cleared on the next launch: the app restarts before anybody can
|
||||
* ask about it, so a log that lives for one session is a log that is never read.
|
||||
*/
|
||||
private const val CRASH_FILE = "last-crash.txt"
|
||||
|
||||
/**
|
||||
* How much of a stack is kept.
|
||||
*
|
||||
* This is pasted into a conversation, so it has a budget like any other output written for a
|
||||
* reader. The top of a stack is what identifies a crash and the bottom is framework plumbing, so
|
||||
* what gets cut is the part nobody reads.
|
||||
*/
|
||||
private const val CRASH_LIMIT = 4000
|
||||
|
||||
/**
|
||||
* Records uncaught exceptions, then lets the platform do what it was going to do.
|
||||
*
|
||||
* Chained rather than replacing: the default handler is what shows the "app has stopped" dialog and
|
||||
* ends the process, and an app that swallows that instead sits there in an unknown state. This only
|
||||
* adds a witness.
|
||||
*/
|
||||
fun installCrashLog(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
runCatching { File(app.filesDir, CRASH_FILE).writeText(describe(thread, error)) }
|
||||
previous?.uncaughtException(thread, error)
|
||||
}
|
||||
}
|
||||
|
||||
private fun describe(thread: Thread, error: Throwable): String {
|
||||
val when_ = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
val stack = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
|
||||
val kept =
|
||||
if (stack.length <= CRASH_LIMIT) stack
|
||||
else stack.take(CRASH_LIMIT) + "\n ... ${stack.length - CRASH_LIMIT} more characters"
|
||||
return "$when_ on thread ${thread.name}\n$kept"
|
||||
}
|
||||
|
||||
/** The last crash, or null if there has not been one since it was last read. */
|
||||
fun lastCrash(context: Context): String? =
|
||||
File(context.applicationContext.filesDir, CRASH_FILE).takeIf { it.exists() }?.readText()
|
||||
|
||||
/** Forgets the last crash, once somebody has taken a copy of it. */
|
||||
fun clearCrash(context: Context) {
|
||||
File(context.applicationContext.filesDir, CRASH_FILE).delete()
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import androidx.core.content.getSystemService
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* Counters and timers for the work the transcript does, for the readout behind the debug button.
|
||||
*
|
||||
* Here because the emulator cannot answer the question this is for. Its own scroll sits at the same
|
||||
* frame times as the stock Settings app -- 21ms at the median for both -- so every app-level cost
|
||||
* is under the floor of what it can measure, and a frame number taken in it says nothing about a
|
||||
* 120Hz phone. Counts do not have that problem: how many times a row was composed, or a reply
|
||||
* parsed, is the same number on any machine, and it is the number that says whether the work is
|
||||
* proportional to what is on screen or to everything ever loaded.
|
||||
*
|
||||
* Always on rather than behind a build flag. What is measured is an atomic increment on paths that
|
||||
* already allocate lists and parse markdown, and a counter that is only compiled into the build
|
||||
* nobody is holding when it is slow is not an instrument.
|
||||
*/
|
||||
object DebugStats {
|
||||
private val counts = ConcurrentHashMap<String, AtomicLong>()
|
||||
private val nanos = ConcurrentHashMap<String, AtomicLong>()
|
||||
private val worst = ConcurrentHashMap<String, AtomicLong>()
|
||||
|
||||
private fun at(map: ConcurrentHashMap<String, AtomicLong>, name: String) =
|
||||
map.computeIfAbsent(name) { AtomicLong() }
|
||||
|
||||
fun count(name: String, by: Long = 1) {
|
||||
at(counts, name).addAndGet(by)
|
||||
}
|
||||
|
||||
/** Keeps [name] at the largest value it has been given, for a high-water mark. */
|
||||
fun atLeast(name: String, value: Long) {
|
||||
val slot = at(counts, name)
|
||||
while (true) {
|
||||
val had = slot.get()
|
||||
if (value <= had || slot.compareAndSet(had, value)) break
|
||||
}
|
||||
}
|
||||
|
||||
/** Records one occurrence of [name] that took [elapsed] nanoseconds. */
|
||||
fun record(name: String, elapsed: Long) {
|
||||
count(name)
|
||||
at(nanos, name).addAndGet(elapsed)
|
||||
val slot = at(worst, name)
|
||||
while (true) {
|
||||
val had = slot.get()
|
||||
if (elapsed <= had || slot.compareAndSet(had, elapsed)) break
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> timed(name: String, body: () -> T): T {
|
||||
val started = System.nanoTime()
|
||||
try {
|
||||
return body()
|
||||
} finally {
|
||||
record(name, System.nanoTime() - started)
|
||||
}
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
counts.clear()
|
||||
nanos.clear()
|
||||
worst.clear()
|
||||
}
|
||||
|
||||
/** One line per counter: how many, how long in total, and the worst single one. */
|
||||
fun lines(): List<String> =
|
||||
counts.keys.sorted().map { name ->
|
||||
val n = counts[name]?.get() ?: 0
|
||||
val total = nanos[name]?.get() ?: 0
|
||||
if (total == 0L) " $name: $n"
|
||||
else
|
||||
" $name: $n, ${ms(total)}ms total, ${ms(total / n.coerceAtLeast(1))}ms mean," +
|
||||
" ${ms(worst[name]?.get() ?: 0)}ms worst"
|
||||
}
|
||||
|
||||
/** How long everything named [name] took in total, or zero if it never happened. */
|
||||
fun nanosOf(name: String): Long = nanos[name]?.get() ?: 0
|
||||
|
||||
private fun ms(nanos: Long) = "%.1f".format(nanos / 1_000_000.0)
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of the frame's draw phase is this app's own work, and how much is not.
|
||||
*
|
||||
* The draw phase is where Compose's measurement lands as well as its recording -- the platform
|
||||
* calls `measureAndLayout()` from `dispatchDraw` -- so "draw is high" has never said which of three
|
||||
* different things is high. The transcript times its own measure, its own placement and its own
|
||||
* recording, and this is the subtraction that was otherwise done by hand in a conversation every
|
||||
* time a report arrived. What is left over is the framework's per-frame bookkeeping after a layout,
|
||||
* which grows with how many nodes are alive rather than with how many are on screen.
|
||||
*
|
||||
* Per frame rather than in total, because the budget it has to fit in is per frame. The recordings
|
||||
* are not themselves per-frame -- a measurement happens on the frames that need one -- so these are
|
||||
* shares of an average frame, not a claim about any particular one.
|
||||
*/
|
||||
fun drawAccounting(drawNanos: Long, frames: Int): List<String> {
|
||||
if (frames == 0 || drawNanos == 0L) return emptyList()
|
||||
val measure = DebugStats.nanosOf("measure: the whole transcript")
|
||||
val place = DebugStats.nanosOf("place: the whole transcript")
|
||||
// The rows and blocks record *inside* this one, so adding them too would count them twice.
|
||||
val record = DebugStats.nanosOf("draw: the whole transcript")
|
||||
val ours = measure + place + record
|
||||
val rest = (drawNanos - ours).coerceAtLeast(0)
|
||||
fun per(n: Long) = "%.2f".format(n / 1_000_000.0 / frames)
|
||||
return listOf(
|
||||
" draw phase ${per(drawNanos)}ms per frame, of which:",
|
||||
" the transcript: ${per(ours)}ms" +
|
||||
" (measure ${per(measure)}, place ${per(place)}, record ${per(record)})",
|
||||
" everything else: ${per(rest)}ms" +
|
||||
" (${if (drawNanos == 0L) "n/a" else "${rest * 100 / drawNanos}%"})",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the debug button copies: what the device is, what the transcript is holding, where the
|
||||
* frames went, and what the app did to produce them.
|
||||
*
|
||||
* Written for somebody to paste into a conversation, so it is plain text with the units on every
|
||||
* number -- a report whose reader has to ask what the columns mean costs another round trip, and
|
||||
* the whole point of it is to save one.
|
||||
*/
|
||||
fun debugReport(
|
||||
device: String,
|
||||
transcript: List<String>,
|
||||
frames: List<String>,
|
||||
accounting: List<String>,
|
||||
crash: String?,
|
||||
): String = buildString {
|
||||
appendLine("ai-app render report")
|
||||
appendLine(device)
|
||||
appendLine()
|
||||
// First, because a crash outranks every timing below it and the reader should not have to
|
||||
// scroll past two screens of counters to find out the app fell over.
|
||||
if (crash != null) {
|
||||
appendLine("last crash:")
|
||||
crash.trimEnd().lines().forEach { appendLine(" $it") }
|
||||
appendLine()
|
||||
}
|
||||
appendLine("transcript:")
|
||||
transcript.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
appendLine("frames:")
|
||||
frames.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
if (accounting.isNotEmpty()) {
|
||||
appendLine("where the draw phase went:")
|
||||
accounting.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
}
|
||||
appendLine("work since this was last copied:")
|
||||
val work = DebugStats.lines()
|
||||
if (work.isEmpty()) appendLine(" nothing recorded") else work.forEach { appendLine(it) }
|
||||
}
|
||||
|
||||
/** Puts [text] on the clipboard under [label], which is what the system offers as its name. */
|
||||
fun Context.copyToClipboard(label: String, text: String) {
|
||||
getSystemService<ClipboardManager>()?.setPrimaryClip(ClipData.newPlainText(label, text))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* A line across the transcript saying what left the session's context.
|
||||
*
|
||||
* Centred between two rules, because it is a divider rather than something anybody said. Two things
|
||||
* produce one -- a compaction and a clear -- and they are drawn the same way on purpose: to a
|
||||
* reader scrolling back, both mean "the session no longer has what is above this", and which of the
|
||||
* two it was is said by the words and the colour.
|
||||
*
|
||||
* The rules take [color] too, so the whole divider reads as one mark of one kind rather than a
|
||||
* coloured phrase sitting in an unrelated grey line.
|
||||
*
|
||||
* Written once here rather than styled at each of them, so the two cannot drift into looking like
|
||||
* different kinds of thing.
|
||||
*/
|
||||
@Composable
|
||||
fun TranscriptDivider(text: String, color: Color, modifier: Modifier = Modifier) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
) {
|
||||
HorizontalDivider(Modifier.weight(1f), color = color)
|
||||
Text(text, style = MaterialTheme.typography.bodySmall, color = color)
|
||||
HorizontalDivider(Modifier.weight(1f), color = color)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The mark a clear leaves.
|
||||
*
|
||||
* Red, and no counts: a clear takes the conversation out of what the session is given, and unlike a
|
||||
* compaction it summarises nothing and measures nothing, so there is nothing to report but the
|
||||
* fact. Everything above stays on screen and stays scrollable -- the reader can see that, which is
|
||||
* why this does not say it.
|
||||
*/
|
||||
@Composable
|
||||
fun ClearedRow(modifier: Modifier = Modifier) {
|
||||
TranscriptDivider("Context cleared", clearedColor, modifier)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.content.Context
|
||||
import androidx.core.content.edit
|
||||
|
||||
private const val DRAFTS = "session-drafts"
|
||||
|
||||
/**
|
||||
* A message typed into a session and not sent yet.
|
||||
*
|
||||
* On this device rather than on the backend, which is where this app otherwise keeps state so that
|
||||
* every device sees it. A draft is the case that rule is not about: it is the contents of a text
|
||||
* box on the phone somebody is holding, written on every keystroke, and half a sentence surfacing
|
||||
* on another device would be a surprise rather than a convenience. What has been *sent* is the
|
||||
* server's, and that is the part which has to outlive this phone.
|
||||
*
|
||||
* Kept per session id, because the thing being typed belongs to the conversation it is aimed at:
|
||||
* one shared box would hand a message meant for one session to whichever was opened next.
|
||||
*/
|
||||
fun loadDraft(context: Context, sessionId: String): String =
|
||||
context.getSharedPreferences(DRAFTS, Context.MODE_PRIVATE).getString(sessionId, "").orEmpty()
|
||||
|
||||
/**
|
||||
* Records [text] as the draft for [sessionId], or forgets it when there is nothing left to keep.
|
||||
*
|
||||
* The path out is emptying the box, which is what sending does -- so a sent message removes its own
|
||||
* entry and nothing accumulates for a session in ordinary use. A session *deleted* while it held a
|
||||
* draft does leave its key behind: pruning those means a pass over the live session list, which
|
||||
* this file would otherwise have no reason to know about, and the residue is a few bytes per
|
||||
* session ever abandoned mid-sentence. That is a trade rather than an oversight.
|
||||
*/
|
||||
fun saveDraft(context: Context, sessionId: String, text: String) {
|
||||
context.getSharedPreferences(DRAFTS, Context.MODE_PRIVATE).edit {
|
||||
if (text.isEmpty()) remove(sessionId) else putString(sessionId, text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* The frame name the server uses to say a cursor was too far behind to continue from. Must match
|
||||
* `send_backlog` in the backend's routes.rs.
|
||||
*/
|
||||
private const val RESET_EVENT = "reset"
|
||||
|
||||
/**
|
||||
* The SSE half of the API: one long-lived GET per open session screen, replaying the transcript
|
||||
* after a cursor and then following it live.
|
||||
*
|
||||
* Blocking -- run() occupies its thread until the stream ends. [close] (from any thread) is the
|
||||
* cancellation path: it disconnects the socket, which unblocks the read; run() then returns instead
|
||||
* of throwing, so a deliberate close doesn't surface as a connection error. The caller owns
|
||||
* reconnecting (with the last seq it saw as the new cursor) -- see SessionScreen.
|
||||
*/
|
||||
class EventStream(private val settings: ServerSettings, private val sessionId: String) {
|
||||
@Volatile private var connection: HttpURLConnection? = null
|
||||
@Volatile private var closed = false
|
||||
|
||||
fun close() {
|
||||
closed = true
|
||||
connection?.disconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams events after [after] into [onEvent] until the stream drops.
|
||||
*
|
||||
* [onOpen] fires once the server has accepted the connection. That is the measured moment the
|
||||
* stream is live again, and the only honest thing to clear a previous failure on: an earlier
|
||||
* version cleared on the first event instead, so an idle session went on displaying a
|
||||
* connection error that had already been recovered from, indefinitely.
|
||||
*
|
||||
* [onReset] fires when the server answers that the cursor is too far behind to continue from:
|
||||
* everything already displayed is stale and the events that follow are a fresh window, so the
|
||||
* caller drops what it holds and rebuilds -- the same thing it does when the screen opens. It
|
||||
* arrives before those events, so a caller that clears on it stays in order.
|
||||
*/
|
||||
fun run(after: Long, onOpen: () -> Unit, onReset: () -> Unit, onEvent: (SeqEvent) -> Unit) {
|
||||
val connection =
|
||||
URL("${settings.baseUrl}/sessions/$sessionId/events?after=$after").openConnection()
|
||||
as HttpURLConnection
|
||||
this.connection = connection
|
||||
try {
|
||||
connection.applyPinnedTls()
|
||||
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
// No read timeout: between events there is nothing to read for
|
||||
// as long as the session is idle; the server's keep-alives and
|
||||
// a dead socket erroring out are the liveness story.
|
||||
connection.readTimeout = 0
|
||||
connection.setRequestProperty("Authorization", "Bearer ${settings.token}")
|
||||
connection.setRequestProperty("Accept", "text/event-stream")
|
||||
if (connection.responseCode != 200) {
|
||||
val detail = connection.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
throw ApiException(detail ?: "HTTP ${connection.responseCode} for the event stream")
|
||||
}
|
||||
|
||||
onOpen()
|
||||
val reader = connection.inputStream.bufferedReader()
|
||||
// SSE framing: `data:` and `event:` lines accumulate until a
|
||||
// blank line ends the frame. `id:` (the seq) is also inside the
|
||||
// JSON payload, so it needs no separate handling; comment lines
|
||||
// (keep-alives) start with ':' and are skipped.
|
||||
val data = StringBuilder()
|
||||
var name: String? = null
|
||||
while (true) {
|
||||
val line = reader.readLine() ?: break
|
||||
when {
|
||||
line.isEmpty() -> {
|
||||
// A named frame carries no payload and a data frame
|
||||
// has no name, so this is one or the other.
|
||||
if (name == RESET_EVENT) onReset()
|
||||
else if (data.isNotEmpty()) onEvent(parseSeqEvent(data.toString()))
|
||||
data.clear()
|
||||
name = null
|
||||
}
|
||||
line.startsWith("data:") -> data.append(line.removePrefix("data:").trim())
|
||||
line.startsWith("event:") -> name = line.removePrefix("event:").trim()
|
||||
else -> {} // id:, comments -- nothing to do
|
||||
}
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
if (!closed) {
|
||||
throw ApiException(
|
||||
"Can't reach the server -- retrying. (${e.message ?: e::class.simpleName})",
|
||||
e,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
this.connection = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
// The common event model, mirrored from server/src/session/driver.rs --
|
||||
// the app renders purely from this stream (replayed from the transcript by
|
||||
// cursor, then live), so there is no separate "load history" shape to keep
|
||||
// in sync with it.
|
||||
|
||||
/** One transcript line: the event plus its resume cursor and time. */
|
||||
data class SeqEvent(val seq: Long, val ts: Double, val event: SessionEvent)
|
||||
|
||||
/**
|
||||
* One choice offered in answer to a question.
|
||||
*
|
||||
* More than a label because the reader is deciding rather than confirming: what an option means,
|
||||
* and what picking it would produce, are the things that decide it. Both are absent on a
|
||||
* permission, whose Allow and Deny mean exactly what they say.
|
||||
*/
|
||||
data class QuestionOption(val label: String, val description: String?, val preview: String?)
|
||||
|
||||
sealed class SessionEvent {
|
||||
data class UserMessage(
|
||||
val text: String,
|
||||
/**
|
||||
* The [MessageQueued] this resolves, or null when it never waited.
|
||||
*
|
||||
* Matched on rather than the text, because the same message sent twice is two waiting
|
||||
* bubbles and clearing whichever one matched first would leave the wrong one on screen.
|
||||
*/
|
||||
val id: String?,
|
||||
/**
|
||||
* What was attached to it, by the ref the files route serves.
|
||||
*
|
||||
* On the message rather than beside it: these arrived as separate image events until
|
||||
* 2026-08-30, which drew somebody's screenshot as a row floating above the bubble that sent
|
||||
* it, and left this app deciding from adjacency alone which message an image went with --
|
||||
* something the sender knew and could simply have said.
|
||||
*/
|
||||
val images: List<String>,
|
||||
) : SessionEvent()
|
||||
|
||||
/**
|
||||
* A message the server has accepted and the session has not read yet.
|
||||
*
|
||||
* From the server, not from this app's memory of what it sent. The pending bubble used to be
|
||||
* screen state, so leaving the session or restarting the app drew nothing waiting while the
|
||||
* message was still queued -- and nothing waiting is what "there is nothing" looks like.
|
||||
*
|
||||
* Resolved by the [UserMessage] carrying the same id, exactly as [CommandQueued] is resolved by
|
||||
* [CommandSent].
|
||||
*/
|
||||
data class MessageQueued(val id: String, val text: String, val images: List<String>) :
|
||||
SessionEvent()
|
||||
|
||||
data class AssistantText(val delta: String) : SessionEvent()
|
||||
|
||||
data class ToolStart(val id: String, val tool: String, val input: String) : SessionEvent()
|
||||
|
||||
data class ToolUpdate(val id: String, val output: String) : SessionEvent()
|
||||
|
||||
data class ToolEnd(val id: String, val output: String) : SessionEvent()
|
||||
|
||||
data class Image(
|
||||
val ref: String,
|
||||
/** The tool call whose result carried it, or null for a person's own attachment. */
|
||||
val about: String?,
|
||||
) : SessionEvent()
|
||||
|
||||
data class Question(
|
||||
val id: String,
|
||||
val prompt: String,
|
||||
/** A few words naming what the question is about, when the asker offered one. */
|
||||
val header: String?,
|
||||
val options: List<QuestionOption>,
|
||||
/** Whether several options may be chosen at once. */
|
||||
val multiSelect: Boolean,
|
||||
/** The tool call this is permission for, or null when it is not about one. */
|
||||
val about: String?,
|
||||
) : SessionEvent()
|
||||
|
||||
/** Everything chosen for one question, in the order it was offered. */
|
||||
data class Answered(val id: String, val answers: List<String>) : SessionEvent()
|
||||
|
||||
/**
|
||||
* A message another agent sent this session.
|
||||
*
|
||||
* Not a [UserMessage]: nobody holding the phone said it, and drawing it in their voice would
|
||||
* claim they had. It is also the explanation for a session that starts working on something
|
||||
* this device never asked for.
|
||||
*/
|
||||
data class PeerMessage(val from: String, val text: String) : SessionEvent()
|
||||
|
||||
/**
|
||||
* A command the session was asked to run on itself and cannot run yet.
|
||||
*
|
||||
* Resolved by [CommandSent] with the same id. A command that ran straight away has only that
|
||||
* one, so nothing here ever draws a bubble that resolves in the same frame.
|
||||
*/
|
||||
data class CommandQueued(val id: String, val text: String) : SessionEvent()
|
||||
|
||||
/** The same command, handed to the session. */
|
||||
data class CommandSent(val id: String, val text: String) : SessionEvent()
|
||||
|
||||
data class Status(val state: String) : SessionEvent()
|
||||
|
||||
/**
|
||||
* What the session is set to, as the session itself reports it.
|
||||
*
|
||||
* Either field alone: the two are confirmed separately and by different things. Asking for a
|
||||
* change is not having one, so this -- not the request -- is what the pickers show.
|
||||
*/
|
||||
data class Settings(val model: String?, val permissionMode: String?) : SessionEvent()
|
||||
|
||||
/**
|
||||
* What a turn cost, and how much the model was holding when it ended.
|
||||
*
|
||||
* [context] is prompt plus both cache figures, measured by the backend from the turn's own
|
||||
* usage. Carried on the event rather than summed by the reader, because it is not a sum: a
|
||||
* conversation's context drops at a compaction and a clear, so adding turns up would report a
|
||||
* figure the session stopped being true of. Null where the dialect did not say, and on entries
|
||||
* recorded before the backend sent it -- which leaves the context unmeasured rather than
|
||||
* unchanged.
|
||||
*/
|
||||
data class UsageDelta(val tokens: Long, val context: Long?) : SessionEvent()
|
||||
|
||||
/**
|
||||
* A compaction that finished, and how much context it recovered.
|
||||
*
|
||||
* The counts are nullable because the server sends them only when it was told them: a
|
||||
* compaction whose size nobody measured has to be able to say so, since a zero here would read
|
||||
* as "recovered nothing" and a made-up number would read as a measurement.
|
||||
*/
|
||||
data class Compacted(
|
||||
val preTokens: Long?,
|
||||
val postTokens: Long?,
|
||||
/** What asked for it, in the CLI's own word; `auto` is the one worth naming. */
|
||||
val trigger: String?,
|
||||
) : SessionEvent()
|
||||
|
||||
/**
|
||||
* The conversation was cleared. Everything above this is still here to read and is no longer in
|
||||
* the session's context.
|
||||
*
|
||||
* An object rather than a class because it carries nothing: what it means is entirely its
|
||||
* position in the transcript.
|
||||
*/
|
||||
data object Cleared : SessionEvent()
|
||||
|
||||
data class Error(val message: String) : SessionEvent()
|
||||
|
||||
/**
|
||||
* An event type this app build doesn't know -- a newer server. Kept (not thrown) so one new
|
||||
* event kind degrades to a placeholder row instead of killing the stream.
|
||||
*/
|
||||
data class Unknown(val type: String) : SessionEvent()
|
||||
}
|
||||
|
||||
/**
|
||||
* A JSON array of strings under [name], empty when the field is absent.
|
||||
*
|
||||
* Absent is the ordinary case -- most messages carry no attachment, and the server omits the field
|
||||
* rather than sending an empty list -- so this is the shape every caller wants.
|
||||
*/
|
||||
private fun JSONObject.stringList(name: String): List<String> {
|
||||
val array = optJSONArray(name) ?: return emptyList()
|
||||
return (0 until array.length()).map { array.getString(it) }
|
||||
}
|
||||
|
||||
fun parseSeqEvent(json: String): SeqEvent {
|
||||
val body = JSONObject(json)
|
||||
val event =
|
||||
when (val type = body.getString("type")) {
|
||||
"userMessage" ->
|
||||
SessionEvent.UserMessage(
|
||||
body.getString("text"),
|
||||
body.optString("id").ifEmpty { null },
|
||||
body.stringList("images"),
|
||||
)
|
||||
"messageQueued" ->
|
||||
SessionEvent.MessageQueued(
|
||||
body.getString("id"),
|
||||
body.getString("text"),
|
||||
body.stringList("images"),
|
||||
)
|
||||
"assistantText" -> SessionEvent.AssistantText(body.getString("delta"))
|
||||
"toolStart" ->
|
||||
SessionEvent.ToolStart(
|
||||
id = body.getString("id"),
|
||||
tool = body.getString("tool"),
|
||||
// Kept as raw JSON text: the input shape is the tool's own
|
||||
// business, and the UI only ever shows it verbatim.
|
||||
input = body.get("input").toString(),
|
||||
)
|
||||
"toolUpdate" -> SessionEvent.ToolUpdate(body.getString("id"), body.getString("output"))
|
||||
"toolEnd" -> SessionEvent.ToolEnd(body.getString("id"), body.getString("output"))
|
||||
"image" ->
|
||||
SessionEvent.Image(
|
||||
ref = body.getString("ref"),
|
||||
about = body.optString("about").ifEmpty { null },
|
||||
)
|
||||
"question" ->
|
||||
SessionEvent.Question(
|
||||
id = body.getString("id"),
|
||||
prompt = body.getString("prompt"),
|
||||
header = body.optString("header").ifEmpty { null },
|
||||
options =
|
||||
body.getJSONArray("options").let { options ->
|
||||
(0 until options.length()).map { at ->
|
||||
val option = options.getJSONObject(at)
|
||||
QuestionOption(
|
||||
label = option.getString("label"),
|
||||
description = option.optString("description").ifEmpty { null },
|
||||
preview = option.optString("preview").ifEmpty { null },
|
||||
)
|
||||
}
|
||||
},
|
||||
multiSelect = body.optBoolean("multiSelect", false),
|
||||
about = body.optString("about").ifEmpty { null },
|
||||
)
|
||||
"answered" ->
|
||||
SessionEvent.Answered(
|
||||
body.getString("id"),
|
||||
body.getJSONArray("answers").let { answers ->
|
||||
(0 until answers.length()).map { answers.getString(it) }
|
||||
},
|
||||
)
|
||||
"peerMessage" ->
|
||||
SessionEvent.PeerMessage(body.getString("from"), body.getString("text"))
|
||||
"commandQueued" ->
|
||||
SessionEvent.CommandQueued(body.getString("id"), body.getString("text"))
|
||||
"commandSent" -> SessionEvent.CommandSent(body.getString("id"), body.getString("text"))
|
||||
"status" -> SessionEvent.Status(body.getString("state"))
|
||||
"settings" ->
|
||||
SessionEvent.Settings(
|
||||
model = body.optString("model").ifEmpty { null },
|
||||
permissionMode = body.optString("permissionMode").ifEmpty { null },
|
||||
)
|
||||
"usageDelta" ->
|
||||
SessionEvent.UsageDelta(
|
||||
body.getLong("tokens"),
|
||||
if (body.has("context")) body.getLong("context") else null,
|
||||
)
|
||||
"compacted" ->
|
||||
SessionEvent.Compacted(
|
||||
preTokens = if (body.has("preTokens")) body.getLong("preTokens") else null,
|
||||
postTokens = if (body.has("postTokens")) body.getLong("postTokens") else null,
|
||||
trigger = body.optString("trigger").ifEmpty { null },
|
||||
)
|
||||
"cleared" -> SessionEvent.Cleared
|
||||
"error" -> SessionEvent.Error(body.getString("message"))
|
||||
else -> SessionEvent.Unknown(type)
|
||||
}
|
||||
return SeqEvent(seq = body.getLong("seq"), ts = body.getDouble("ts"), event = event)
|
||||
}
|
||||
|
||||
/**
|
||||
* The context after [event], given what it was before.
|
||||
*
|
||||
* The same rule the server folds with, because the screen has to keep up between page loads: the
|
||||
* summary it opened with is a measurement from before this stream started, and every event that
|
||||
* moves the figure arrives here.
|
||||
*
|
||||
* The two that lower it are the point. A clear takes the conversation away and a compaction
|
||||
* replaces it with a summary, so a figure measured before either stopped being true at that moment
|
||||
* -- and carrying it forward is how a session that had just been cleared went on reporting the
|
||||
* context it no longer had.
|
||||
*
|
||||
* Null is "we don't know", which is a state each of them can reach: nothing measured yet, a
|
||||
* compaction that finished without saying how much it recovered, or a clear nobody has run a turn
|
||||
* since.
|
||||
*/
|
||||
fun contextAfter(current: Long?, event: SessionEvent): Long? =
|
||||
when (event) {
|
||||
// Falls back to what we had, so a turn the dialect reported no usage for is stale by a
|
||||
// turn -- which every context figure is -- rather than unknown.
|
||||
is SessionEvent.UsageDelta -> event.context ?: current
|
||||
is SessionEvent.Compacted -> event.postTokens
|
||||
is SessionEvent.Cleared -> null
|
||||
else -> current
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.view.FrameMetrics
|
||||
import android.view.Window
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/**
|
||||
* How long each frame took, and which phase of it, taken from the platform rather than from a frame
|
||||
* counter of our own.
|
||||
*
|
||||
* The point of splitting it up is that "the scroll is laggy" has two completely different causes
|
||||
* and one appearance. If the layout-and-measure and draw figures are small and the total is large,
|
||||
* the time is going into rasterising and compositing, and no amount of doing less work per row will
|
||||
* move it. If they are large, the work per row is the problem and it is ours to fix. Guessing
|
||||
* between those two is how a day gets spent rewriting the half that was already fast.
|
||||
*
|
||||
* The phases are the platform's own: [FrameMetrics] reports each frame's cost in nanoseconds,
|
||||
* broken down into the parts the UI thread is responsible for -- handling input, running
|
||||
* animations, measuring and laying out, recording the draw -- and the parts after it.
|
||||
*/
|
||||
class FrameStats {
|
||||
private val total = ArrayList<Long>()
|
||||
private val waited = ArrayList<Long>()
|
||||
private val input = ArrayList<Long>()
|
||||
private val animation = ArrayList<Long>()
|
||||
private val layout = ArrayList<Long>()
|
||||
private val draw = ArrayList<Long>()
|
||||
private val sync = ArrayList<Long>()
|
||||
private val issue = ArrayList<Long>()
|
||||
private val swap = ArrayList<Long>()
|
||||
private val gpu = ArrayList<Long>()
|
||||
private var since = System.currentTimeMillis()
|
||||
|
||||
@Synchronized
|
||||
fun add(metrics: FrameMetrics) {
|
||||
// The first frame after a window opens includes inflating it and is nobody's scroll.
|
||||
if (metrics.getMetric(FrameMetrics.FIRST_DRAW_FRAME) == 1L) return
|
||||
if (total.size >= CAP) return
|
||||
total += metrics.getMetric(FrameMetrics.TOTAL_DURATION)
|
||||
// How long the frame waited for the UI thread to be free before it could start. Reported
|
||||
// because the phases otherwise do not add up to the total, and the gap is the interesting
|
||||
// part: it is the frame being held up by work that is not the frame's.
|
||||
waited += metrics.getMetric(FrameMetrics.UNKNOWN_DELAY_DURATION)
|
||||
input += metrics.getMetric(FrameMetrics.INPUT_HANDLING_DURATION)
|
||||
animation += metrics.getMetric(FrameMetrics.ANIMATION_DURATION)
|
||||
layout += metrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION)
|
||||
draw += metrics.getMetric(FrameMetrics.DRAW_DURATION)
|
||||
sync += metrics.getMetric(FrameMetrics.SYNC_DURATION)
|
||||
issue += metrics.getMetric(FrameMetrics.COMMAND_ISSUE_DURATION)
|
||||
swap += metrics.getMetric(FrameMetrics.SWAP_BUFFERS_DURATION)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
gpu += metrics.getMetric(FrameMetrics.GPU_DURATION)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun reset() {
|
||||
listOf(total, waited, input, animation, layout, draw, sync, issue, swap, gpu).forEach {
|
||||
it.clear()
|
||||
}
|
||||
since = System.currentTimeMillis()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun lines(refreshHz: Float): List<String> {
|
||||
if (total.isEmpty()) return listOf(" no frames recorded -- scroll first, then press this")
|
||||
val seconds = (System.currentTimeMillis() - since) / 1000.0
|
||||
val budget = if (refreshHz > 0) 1000.0 / refreshHz else 16.7
|
||||
val late = total.count { it / 1_000_000.0 > budget }
|
||||
return listOf(
|
||||
" ${total.size} frames over ${"%.1f".format(seconds)}s" +
|
||||
" at ${"%.0f".format(refreshHz)}Hz (${"%.1f".format(budget)}ms budget)",
|
||||
" late: $late (${percent(late, total.size)})" +
|
||||
if (total.size >= CAP) " [capped]" else "",
|
||||
phase("total ", total),
|
||||
phase("waited", waited),
|
||||
phase("input ", input),
|
||||
phase("anim ", animation),
|
||||
phase("layout", layout),
|
||||
phase("draw ", draw),
|
||||
phase("sync ", sync),
|
||||
phase("issue ", issue),
|
||||
phase("swap ", swap),
|
||||
) + if (gpu.isEmpty()) emptyList() else listOf(phase("gpu ", gpu))
|
||||
}
|
||||
|
||||
/** How long the frames recorded here spent in their draw phase, and how many there were. */
|
||||
@Synchronized fun drawPhase(): Pair<Long, Int> = draw.sum() to draw.size
|
||||
|
||||
private fun phase(name: String, samples: List<Long>): String {
|
||||
val sorted = samples.sorted()
|
||||
return " $name p50 ${at(sorted, 50)} p90 ${at(sorted, 90)} p99 ${at(sorted, 99)}"
|
||||
}
|
||||
|
||||
private fun at(sorted: List<Long>, percentile: Int): String {
|
||||
if (sorted.isEmpty()) return "-"
|
||||
val index = (sorted.size - 1) * percentile / 100
|
||||
return "%.1fms".format(sorted[index] / 1_000_000.0)
|
||||
}
|
||||
|
||||
private fun percent(part: Int, whole: Int) = "%.1f%%".format(100.0 * part / whole)
|
||||
|
||||
private companion object {
|
||||
/** Enough for a couple of minutes of scrolling; this is a diagnostic, not a log. */
|
||||
const val CAP = 20_000
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Frame timings for as long as this screen is on it.
|
||||
*
|
||||
* The listener is handed its own thread because the platform calls it for every frame and the
|
||||
* documentation is explicit that doing that on the main thread taxes the very thing being measured.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberFrameStats(): FrameStats {
|
||||
val stats = remember { FrameStats() }
|
||||
val window = LocalContext.current.activity()?.window
|
||||
DisposableEffect(window) {
|
||||
if (window == null) return@DisposableEffect onDispose {}
|
||||
val thread = HandlerThread("frame-stats").apply { start() }
|
||||
val listener = Window.OnFrameMetricsAvailableListener { _, metrics, _ ->
|
||||
stats.add(metrics)
|
||||
}
|
||||
window.addOnFrameMetricsAvailableListener(listener, Handler(thread.looper))
|
||||
onDispose {
|
||||
window.removeOnFrameMetricsAvailableListener(listener)
|
||||
thread.quitSafely()
|
||||
}
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
/** The activity behind a composable's context, which is what owns the window. */
|
||||
fun Context.activity(): Activity? {
|
||||
var context: Context? = this
|
||||
while (context is ContextWrapper) {
|
||||
if (context is Activity) return context
|
||||
context = context.baseContext
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** What the display is actually refreshing at, so "late" is measured against the real budget. */
|
||||
fun Context.refreshHz(): Float =
|
||||
@Suppress("DEPRECATION") (activity()?.windowManager?.defaultDisplay?.refreshRate ?: 60f)
|
||||
@@ -0,0 +1,602 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** What a row says about itself while an operation is running on it. See [BusyItem]. */
|
||||
private const val IMPORTING = "importing"
|
||||
private const val DELETING = "deleting"
|
||||
|
||||
/**
|
||||
* What the rows further down a batch say while they wait their turn.
|
||||
*
|
||||
* Its own word rather than the operation's, because it is its own state and the difference is the
|
||||
* kind that matters: nothing has been done to this session yet, so a batch stopped here leaves it
|
||||
* exactly as it was. Marked from the moment the batch is handed over all the same -- a queued row
|
||||
* that still looked ordinary was still tappable, and tapping it would import it a second time
|
||||
* behind the batch already coming for it.
|
||||
*/
|
||||
private const val WAITING = "waiting"
|
||||
|
||||
/**
|
||||
* How long a row that has just moved ignores being touched.
|
||||
*
|
||||
* A batch takes rows out of the list as each one lands, so everything below the one that went
|
||||
* slides up -- and a tap already on its way then arrives at whichever row moved into that place. On
|
||||
* this screen that means importing a session nobody chose, which is not something a second tap can
|
||||
* undo.
|
||||
*
|
||||
* Swallowed silently rather than shown, because anything drawn on every row a batch passes would be
|
||||
* a flicker running down the list. Half a second: long enough to cover a tap already travelling
|
||||
* when the row moved, short enough that it is not in the way of a deliberate one.
|
||||
*/
|
||||
private const val SETTLE_MS = 500L
|
||||
|
||||
/**
|
||||
* Continuing a Claude Code session the machine already has.
|
||||
*
|
||||
* The list is the machine's answer, not this app's: it asks a setup what sessions it holds and
|
||||
* shows them. Choosing one sends its **id**, never a path, so an enrolled phone cannot turn this
|
||||
* screen into a file reader.
|
||||
*
|
||||
* Holding a row selects it and puts the screen in selection mode, where the options that act on a
|
||||
* selection appear along the bottom. That exists because these arrive in bulk — a machine
|
||||
* accumulates dozens of abandoned sessions — and one confirmation dialog per row is the reason
|
||||
* clearing them out was not worth doing.
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun ImportScreen(settings: ServerSettings, reloadToken: Int, onImported: (SessionSummary) -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var setups by remember { mutableStateOf<LoadState<List<Setup>>>(LoadState.Loading) }
|
||||
var chosen by remember { mutableStateOf<Setup?>(null) }
|
||||
var sessions by remember { mutableStateOf<LoadState<List<Importable>>>(LoadState.Loading) }
|
||||
|
||||
// What is happening to each row right now, as the word the row shows: "importing" or
|
||||
// "deleting". A map keyed by id rather than a flag per row, because the rows are rebuilt from
|
||||
// whatever the server last said and this belongs to the request rather than to the session --
|
||||
// the same arrangement the session list uses for its deletes.
|
||||
var running by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
// Which rows the reader has picked out. Empty means selection mode is off: there is no
|
||||
// separate flag, because a selection mode with nothing selected is a state with no controls
|
||||
// in it and no way to leave except Back.
|
||||
var selected by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
// Failures that belong to one row rather than to the screen, shown on that row. A batch is
|
||||
// exactly where a single banner fails: nine deletes succeeded and one did not, and the
|
||||
// banner cannot say which.
|
||||
var rowErrors by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
// Deleting a transcript cannot be undone, so it is asked rather than done. Held as the rows
|
||||
// themselves, not a flag, so the dialog can say what it is about.
|
||||
var confirming by remember { mutableStateOf<List<Importable>?>(null) }
|
||||
// Same default as the spawn screen, and for the same reason: a phone
|
||||
// is the wrong place to answer "allow Bash?" forty times.
|
||||
var permissionMode by remember { mutableStateOf("auto") }
|
||||
// When each row last slid upwards, as a plain map rather than state: nothing is drawn from
|
||||
// it, so a tap reading it needs no recomposition and there is no timer to cancel when a
|
||||
// second removal lands on top of the first.
|
||||
val movedAt = remember { mutableMapOf<String, Long>() }
|
||||
fun settling(id: String) = System.currentTimeMillis() - (movedAt[id] ?: 0L) < SETTLE_MS
|
||||
|
||||
fun loadSessions(setup: Setup) {
|
||||
sessions = LoadState.Loading
|
||||
selected = emptySet()
|
||||
rowErrors = emptyMap()
|
||||
scope.launch {
|
||||
sessions =
|
||||
try {
|
||||
LoadState.Loaded(
|
||||
withContext(Dispatchers.IO) { fetchImportable(settings, setup.id) }
|
||||
)
|
||||
} catch (err: Exception) {
|
||||
LoadState.Error(err.message ?: "Couldn't list sessions")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(reloadToken) {
|
||||
setups =
|
||||
try {
|
||||
val found = withContext(Dispatchers.IO) { fetchSetups(settings) }
|
||||
found.firstOrNull()?.let {
|
||||
chosen = it
|
||||
loadSessions(it)
|
||||
}
|
||||
LoadState.Loaded(found)
|
||||
} catch (err: Exception) {
|
||||
LoadState.Error(err.message ?: "Couldn't list machines")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs [operation] over [targets] one at a time, marking each row with [label] while its turn
|
||||
* lasts and taking it off the list when it succeeds.
|
||||
*
|
||||
* One runner for both operations and for both the single tap and the batch, so "what a row
|
||||
* looks like while something is happening to it" and "what happens when one of ten fails" are
|
||||
* decided once. Sequentially, because each import starts a CLI on the machine and ten at once
|
||||
* is a load nobody asked for; the reader sees the work walk down the list, which is also the
|
||||
* only honest progress this screen can show.
|
||||
*
|
||||
* The selection is dropped the moment the work is handed over, not when it finishes: the screen
|
||||
* goes back to how it started, and what says the work is happening is the rows it is happening
|
||||
* to. Holding the selection until the end left the bar up over rows that could no longer be
|
||||
* pressed, offering to start again something already running.
|
||||
*
|
||||
* A failure keeps its row and puts the server's words on it. Selecting those rows again is then
|
||||
* the reader's decision rather than a state the screen carried for them — and it is the
|
||||
* decision worth making deliberately, because retrying a delete that the server refused is
|
||||
* usually not what somebody wants to do by pressing the same button twice.
|
||||
*/
|
||||
fun runOn(targets: List<Importable>, label: String, operation: suspend (Importable) -> Unit) {
|
||||
selected = emptySet()
|
||||
running = running + targets.associate { it.id to WAITING }
|
||||
scope.launch {
|
||||
for (target in targets) {
|
||||
running = running + (target.id to label)
|
||||
rowErrors = rowErrors - target.id
|
||||
try {
|
||||
operation(target)
|
||||
val loaded = sessions
|
||||
if (loaded is LoadState.Loaded) {
|
||||
// As each one lands, not all of them at the end. Holding the finished
|
||||
// rows in place to keep the list still was tried and is worse: a row
|
||||
// that has been imported but is still sitting there looks exactly like
|
||||
// one that has not, and tapping it starts a second CLI on the same
|
||||
// transcript. A row that is gone cannot be tapped at all.
|
||||
//
|
||||
// Only this row, and only what changed -- refetching instead put every
|
||||
// other row back through a loading spinner to report a change that was
|
||||
// never in doubt.
|
||||
val now = System.currentTimeMillis()
|
||||
loaded.value
|
||||
.asSequence()
|
||||
.dropWhile { it.id != target.id }
|
||||
.drop(1)
|
||||
.forEach { movedAt[it.id] = now }
|
||||
sessions = LoadState.Loaded(loaded.value.filterNot { it.id == target.id })
|
||||
}
|
||||
} catch (err: Exception) {
|
||||
rowErrors = rowErrors + (target.id to (err.message ?: "Didn't work"))
|
||||
} finally {
|
||||
running = running - target.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val provider = chosen?.providers?.firstOrNull { it.kind == "claude_cli" }
|
||||
|
||||
/**
|
||||
* Imports [targets], and goes to the session it made when [thenOpen].
|
||||
*
|
||||
* One function for the tap and for the bar, differing in that one flag: continuing a session
|
||||
* and then looking at it is what a tap on a row means, and a batch has several results and no
|
||||
* reason to pick one of them to become the screen.
|
||||
*/
|
||||
fun importAll(targets: List<Importable>, thenOpen: Boolean) {
|
||||
val setup = chosen ?: return
|
||||
val useProvider = provider ?: return
|
||||
runOn(targets, IMPORTING) { session ->
|
||||
val spawned =
|
||||
withContext(Dispatchers.IO) {
|
||||
spawnSession(
|
||||
settings,
|
||||
setup = setup.id,
|
||||
provider = useProvider.name,
|
||||
// Nothing to say: the server titles it from the session it is continuing.
|
||||
title = "",
|
||||
permissionMode = permissionMode,
|
||||
import = session.id,
|
||||
)
|
||||
}
|
||||
if (thenOpen) onImported(spawned)
|
||||
}
|
||||
}
|
||||
|
||||
// Back leaves selection mode rather than the tab, which is the level it is one step above.
|
||||
// Nested inside MainScreen's own handler, so it wins while there is a selection.
|
||||
BackHandler(enabled = selected.isNotEmpty()) { selected = emptySet() }
|
||||
|
||||
// Measured rather than assumed: the list reserves exactly what the bar covers, so the last
|
||||
// row can still be scrolled to while it is up, and nothing is nudged by a number that was
|
||||
// right for one font size.
|
||||
var barHeight by remember { mutableStateOf(0.dp) }
|
||||
val density = LocalDensity.current
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
Column(Modifier.fillMaxSize().padding(16.dp)) {
|
||||
// No heading: the tab that selected this one already says "Import". The sentence below
|
||||
// stays, because it says what importing *does*, which the tab label cannot.
|
||||
Text(
|
||||
"Sessions Claude Code already has on the machine. Importing continues one where " +
|
||||
"it left off; the transcript here shows its recent history. Hold one to " +
|
||||
"select it, and several at a time.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
when (val loaded = setups) {
|
||||
is LoadState.Loading -> CircularProgressIndicator()
|
||||
is LoadState.Error -> Text(loaded.message, color = MaterialTheme.colorScheme.error)
|
||||
is LoadState.Loaded -> {
|
||||
// Only worth choosing when there is a choice.
|
||||
if (loaded.value.size > 1) {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
loaded.value.forEach { setup ->
|
||||
TextButton(
|
||||
onClick = {
|
||||
chosen = setup
|
||||
loadSessions(setup)
|
||||
}
|
||||
) {
|
||||
Text(
|
||||
setup.name,
|
||||
color =
|
||||
if (setup.id == chosen?.id)
|
||||
MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (chosen != null && provider == null) {
|
||||
Text(
|
||||
"${chosen?.name} has no Claude CLI, so there is nothing here to " +
|
||||
"continue.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
ChipGroup(
|
||||
label = "Permissions",
|
||||
options = PERMISSION_MODES,
|
||||
selected = permissionMode,
|
||||
onSelect = { permissionMode = it },
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
ImportableList(
|
||||
state = sessions,
|
||||
running = running,
|
||||
settling = ::settling,
|
||||
selected = selected,
|
||||
errors = rowErrors,
|
||||
bottomInset = barHeight,
|
||||
onToggle = { session ->
|
||||
selected =
|
||||
if (session.id in selected) selected - session.id
|
||||
else selected + session.id
|
||||
},
|
||||
onOpen = { session -> importAll(listOf(session), thenOpen = true) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Beside nothing in particular, because a selection is not one row: the options that act
|
||||
// on it belong to the screen, and the bottom is where a thumb already is.
|
||||
if (selected.isNotEmpty()) {
|
||||
val picked =
|
||||
(sessions as? LoadState.Loaded)?.value?.filter { it.id in selected }.orEmpty()
|
||||
SelectionBar(
|
||||
count = picked.size,
|
||||
modifier =
|
||||
Modifier.align(Alignment.BottomCenter).onSizeChanged {
|
||||
barHeight = with(density) { it.height.toDp() }
|
||||
},
|
||||
onDelete = { confirming = picked },
|
||||
onImport = { importAll(picked, thenOpen = false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
confirming?.let { targets ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirming = null },
|
||||
title = {
|
||||
Text(
|
||||
if (targets.size == 1) "Delete this session?"
|
||||
else "Delete ${targets.size} sessions?"
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Text(
|
||||
// One name is worth showing and twelve are not, so the count stands in for
|
||||
// them. The sentence after it is the same either way, because what deleting
|
||||
// costs does not change with how many.
|
||||
(if (targets.size == 1) "\"${targets.first().title}\"\n\n" else "") +
|
||||
"Claude Code keeps no copy: its transcript is the session, so this ends " +
|
||||
"any chance of resuming that conversation. Sessions already imported " +
|
||||
"here keep the history they replayed, but cannot be continued."
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
val setup = chosen ?: return@TextButton
|
||||
confirming = null
|
||||
runOn(targets, DELETING) { session ->
|
||||
withContext(Dispatchers.IO) {
|
||||
deleteImportable(settings, setup.id, session.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
) {
|
||||
// Coloured by consequence: this takes something away, wherever it appears.
|
||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirming = null }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What can be done to the rows that are selected.
|
||||
*
|
||||
* Delete and Import only, for now: they are the two things this screen has ever done to a session,
|
||||
* and an option that appears here has to work on every row in a selection rather than on the one
|
||||
* somebody was thinking of.
|
||||
*/
|
||||
@Composable
|
||||
private fun SelectionBar(
|
||||
count: Int,
|
||||
modifier: Modifier = Modifier,
|
||||
onDelete: () -> Unit,
|
||||
onImport: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
tonalElevation = 3.dp,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
"$count selected",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onDelete) {
|
||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
TextButton(onClick = onImport) { Text("Import") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun ImportableList(
|
||||
state: LoadState<List<Importable>>,
|
||||
/** Rows an operation is running on, as the word each one shows. */
|
||||
running: Map<String, String>,
|
||||
/** Whether this row has just moved and should ignore being touched -- see [SETTLE_MS]. */
|
||||
settling: (String) -> Boolean,
|
||||
selected: Set<String>,
|
||||
errors: Map<String, String>,
|
||||
/** What the selection bar covers, so the last row can still be reached under it. */
|
||||
bottomInset: Dp,
|
||||
onToggle: (Importable) -> Unit,
|
||||
onOpen: (Importable) -> Unit,
|
||||
) {
|
||||
when (state) {
|
||||
is LoadState.Loading -> CircularProgressIndicator()
|
||||
is LoadState.Error -> Text(state.message, color = MaterialTheme.colorScheme.error)
|
||||
is LoadState.Loaded ->
|
||||
if (state.value.isEmpty()) {
|
||||
Text(
|
||||
"No Claude Code sessions on that machine.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
val selecting = selected.isNotEmpty()
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(bottom = bottomInset),
|
||||
) {
|
||||
items(state.value, key = { it.id }) { session ->
|
||||
val picked = session.id in selected
|
||||
BusyItem(label = running[session.id]) {
|
||||
Card(
|
||||
colors =
|
||||
if (picked)
|
||||
CardDefaults.cardColors(
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.secondaryContainer,
|
||||
contentColor =
|
||||
MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
else CardDefaults.cardColors(),
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.padding(vertical = 4.dp)
|
||||
.combinedClickable(
|
||||
// Off while something is happening to this row --
|
||||
// see [BusyItem], which draws that but deliberately
|
||||
// leaves the gestures alone so the list still
|
||||
// scrolls.
|
||||
enabled = running[session.id] == null,
|
||||
onClick = {
|
||||
if (settling(session.id)) return@combinedClickable
|
||||
// In selection mode a tap is a selection, so the
|
||||
// reader is never one mis-tap away from starting
|
||||
// a CLI they were only picking rows for.
|
||||
//
|
||||
// Outside it, a tap continues the session --
|
||||
// except on a row that cannot be continued,
|
||||
// where it selects instead. That row's only
|
||||
// remaining action is Delete, and a tap that
|
||||
// did nothing at all would be a worse answer
|
||||
// than one that offers the thing it can do.
|
||||
// Two `--resume` processes on one transcript
|
||||
// each replay the other's writes, which is why
|
||||
// this must not simply try.
|
||||
if (selecting || session.inUse == "yes")
|
||||
onToggle(session)
|
||||
else onOpen(session)
|
||||
},
|
||||
onLongClick = {
|
||||
if (!settling(session.id)) onToggle(session)
|
||||
},
|
||||
),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.Top) {
|
||||
Text(
|
||||
session.title,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// Beside the title, because "which one was I just in" is
|
||||
// the question this list answers and the order already
|
||||
// reflects it -- the reader should be able to see the
|
||||
// ordering they are being given rather than infer it.
|
||||
Text(
|
||||
relativeTime(session.modified),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
// The path first, and the only thing here that is cut: it is
|
||||
// one long value with no natural break, where the lines below
|
||||
// it are short enough to wrap readably. Cut at the head,
|
||||
// because a path is identified by its tail and these all
|
||||
// share a long prefix. By the row's real width rather than a
|
||||
// character count, which was one guess for every font size
|
||||
// and screen.
|
||||
session.cwd
|
||||
.takeIf { it.isNotEmpty() }
|
||||
?.let { cwd ->
|
||||
Text(
|
||||
cwd,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
statsOf(session),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
// Its own line and its own colour, because it differs in kind
|
||||
// from the stats above rather than in degree: those describe
|
||||
// the session, this says whether taking it is safe at all.
|
||||
warningOf(session)?.let { warning ->
|
||||
Text(
|
||||
warning,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = warningColor,
|
||||
)
|
||||
}
|
||||
// Reported where it happened, in the server's own words, the
|
||||
// way every other failure in this app is shown.
|
||||
errors[session.id]?.let { message ->
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
message,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A byte count at the coarsest unit that still says something, so rows stay comparable. */
|
||||
private fun humanSize(bytes: Long): String? =
|
||||
when {
|
||||
bytes <= 0L -> null
|
||||
bytes >= 1_000_000L -> "${bytes / 1_000_000L} MB"
|
||||
bytes >= 1_000L -> "${bytes / 1_000L} kB"
|
||||
else -> "$bytes B"
|
||||
}
|
||||
|
||||
/** What this session is: the measurements, in the order they are worth knowing. */
|
||||
private fun statsOf(session: Importable): String =
|
||||
listOfNotNull(
|
||||
// Said, because a name and a last message are different claims: one describes the
|
||||
// session, the other is only what happened last in it.
|
||||
if (session.named) "named" else null,
|
||||
// What continuing it costs, which is the question this list is really asked. First
|
||||
// of the measurements for that reason, and absent rather than zero when nothing has
|
||||
// been measured -- a session with no turns yet has no figure, not a figure of none.
|
||||
session.contextTokens?.let { "${it / 1000}k context" },
|
||||
"${session.lines} lines",
|
||||
// Kept beside the context figure because the two disagree usefully: most of a large
|
||||
// transcript is history from before a compaction, which the model is no longer
|
||||
// given, so a big file can be cheap to continue and a small one expensive.
|
||||
humanSize(session.bytes),
|
||||
)
|
||||
.joinToString(" · ")
|
||||
|
||||
/**
|
||||
* Why this session might not be safe to take, if it isn't.
|
||||
*
|
||||
* Words rather than only a colour: "open somewhere else" and "we could not check" differ in kind,
|
||||
* and no shade distinguishes them. The colour is what makes it findable; the words are what make it
|
||||
* actionable.
|
||||
*/
|
||||
private fun warningOf(session: Importable): String? =
|
||||
when (session.inUse) {
|
||||
// What was measured is that a live process on that machine holds this session open. Which
|
||||
// process is not measured, so it isn't claimed: "a terminal — close it there first" sent
|
||||
// people looking for a window that need not exist. It is just as likely another agent, or
|
||||
// this app on a session it spawned. Naming a place the reader then can't find turns a
|
||||
// correct refusal into a wrong instruction.
|
||||
"yes" -> "something on that machine is running it"
|
||||
"unknown" -> "can't tell if it's open"
|
||||
else -> null
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.aiapp
|
||||
|
||||
/**
|
||||
* What a screen knows about something it had to fetch: still finding out, got it, or couldn't.
|
||||
*
|
||||
* Three states rather than a value alongside a nullable error, because "we couldn't find out" must
|
||||
* not share a representation with "there is nothing" -- a failed fetch would otherwise render as an
|
||||
* empty list, which is the one wrong answer that looks like a right one.
|
||||
*
|
||||
* [Loading] and [Error] carry no payload, so they are `LoadState<Nothing>` and this is covariant in
|
||||
* [T]: one `LoadState.Loading` serves every screen rather than each needing its own.
|
||||
*/
|
||||
sealed class LoadState<out T> {
|
||||
data object Loading : LoadState<Nothing>()
|
||||
|
||||
data class Loaded<out T>(val value: T) : LoadState<T>()
|
||||
|
||||
data class Error(val message: String) : LoadState<Nothing>()
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* The failure a fetch produces. Api.kt writes its messages to be read on this screen, so
|
||||
* this passes one through rather than replacing it; the fallback covers only a throwable
|
||||
* with no message at all, which [ApiException] never is.
|
||||
*/
|
||||
fun failed(e: ApiException): Error = Error(e.message ?: "Unknown error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.core.view.WindowCompat
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
// Bumped whenever enrollment lands via an aiapp:// intent so the
|
||||
// composition below re-reads the stored settings.
|
||||
private var settingsVersion by mutableIntStateOf(0)
|
||||
|
||||
// The session a notification tap asked for, or null if nothing has. The
|
||||
// serial is what makes a second tap on the same session's notification a
|
||||
// second request: without it the two compare equal and the composition
|
||||
// below has nothing to react to.
|
||||
private var openRequest by mutableStateOf<SessionOpenRequest?>(null)
|
||||
private var opens = 0
|
||||
|
||||
// Registered up front since permission launchers must be registered
|
||||
// before the activity reaches STARTED.
|
||||
private val requestLocalNetworkPermission =
|
||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) {}
|
||||
|
||||
/**
|
||||
* The service starts either way, and posts nothing if this is refused.
|
||||
*
|
||||
* Deliberately not gated on the answer: the permission can be granted later from Android's own
|
||||
* settings, and a service that only ever started at the moment it was granted would then stay
|
||||
* down until the app was launched again -- which is the case notifications exist to avoid.
|
||||
*/
|
||||
private val requestNotificationPermission =
|
||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) {}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
// Before anything else that could throw, so the first crash of a launch is caught too.
|
||||
installCrashLog(this)
|
||||
|
||||
// Transparent status bar on every version; the Surface below paints
|
||||
// through underneath it and content insets itself. Same reasoning
|
||||
// as dev-updater's MainActivity.
|
||||
enableEdgeToEdge()
|
||||
// Dark status-bar icons only over a light background, decided from the scheme rather
|
||||
// than fixed. It was hardcoded to `true` -- dark icons -- which was right against the
|
||||
// default light surface and became unreadable the moment the app wore Catppuccin Mocha.
|
||||
// Asking the colour means a future palette change cannot reintroduce that: whatever
|
||||
// `background` becomes, the icons follow it.
|
||||
WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars =
|
||||
AiAppColors.background.luminance() > 0.5f
|
||||
|
||||
// Android 17+ silently drops local-network traffic without this;
|
||||
// requested up front because a denial is invisible at the socket
|
||||
// layer (it just times out).
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN) {
|
||||
requestLocalNetworkPermission.launch(Manifest.permission.ACCESS_LOCAL_NETWORK)
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
|
||||
handleIntent(intent)
|
||||
// After enrollment, so a first launch that arrives with a token
|
||||
// starts the service with something to connect to rather than
|
||||
// stopping it and waiting for the next launch.
|
||||
NotificationService.sync(this)
|
||||
|
||||
setContent {
|
||||
MaterialTheme(colorScheme = AiAppColors) {
|
||||
Surface(modifier = Modifier.fillMaxSize()) {
|
||||
Box(
|
||||
modifier =
|
||||
// Timed like the transcript times itself, and for the same reason:
|
||||
// the frame's draw phase is where Compose's measurement lands, and
|
||||
// a report saying "draw is high" cannot otherwise say whether the
|
||||
// cost is the transcript or the chrome around it. The keyboard is
|
||||
// the case that made it matter -- every frame of the IME animation
|
||||
// relays out and re-records this whole box.
|
||||
Modifier.layout { measurable, constraints ->
|
||||
val started = System.nanoTime()
|
||||
val placeable = measurable.measure(constraints)
|
||||
DebugStats.record(
|
||||
"measure: the app root",
|
||||
System.nanoTime() - started,
|
||||
)
|
||||
layout(placeable.width, placeable.height) {
|
||||
val placing = System.nanoTime()
|
||||
placeable.place(0, 0)
|
||||
DebugStats.record(
|
||||
"place: the app root",
|
||||
System.nanoTime() - placing,
|
||||
)
|
||||
}
|
||||
}
|
||||
.drawWithContent {
|
||||
val started = System.nanoTime()
|
||||
drawContent()
|
||||
DebugStats.record(
|
||||
"record: the app root",
|
||||
System.nanoTime() - started,
|
||||
)
|
||||
}
|
||||
.fillMaxSize()
|
||||
.statusBarsPadding()
|
||||
// The gesture strip at the bottom of most
|
||||
// phones. Without it the send row sits under
|
||||
// the swipe area, where a tap is as likely to
|
||||
// navigate away as to press a button.
|
||||
//
|
||||
// No imePadding here, deliberately: applied at the root it
|
||||
// resizes this whole box on every frame of the keyboard
|
||||
// animation, which re-measures, re-places and re-records every
|
||||
// screen's entire tree per frame -- measured above as most of
|
||||
// the frame budget. Each screen takes the keyboard itself
|
||||
// (AppRoot wraps the ordinary ones; the session screen moves
|
||||
// only its composer and transcript), so the per-frame cost is
|
||||
// scoped to what actually moves.
|
||||
.navigationBarsPadding()
|
||||
) {
|
||||
AppRoot(settingsVersion, openRequest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// launchMode="singleTop": an enrollment scan, or a notification tapped
|
||||
// while the app is open, lands here rather than in a second activity
|
||||
// instance.
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
/**
|
||||
* The one place an incoming `aiapp://` URI is sorted into what it means.
|
||||
*
|
||||
* Two things arrive this way -- an enrollment code and a notification naming a session -- and
|
||||
* they are told apart by the URI's host rather than by two entry points, so a third kind is a
|
||||
* branch here rather than another intent to remember to handle.
|
||||
*/
|
||||
private fun handleIntent(intent: Intent?) {
|
||||
val uri = intent?.data ?: return
|
||||
val sessionId = notifiedSessionId(uri)
|
||||
if (sessionId != null) {
|
||||
opens++
|
||||
openRequest = SessionOpenRequest(sessionId, opens)
|
||||
return
|
||||
}
|
||||
val settings = parseEnrollmentUri(uri)
|
||||
if (settings == null) {
|
||||
Toast.makeText(this, "Not a valid enrollment code", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
saveServerSettings(this, settings)
|
||||
settingsVersion++
|
||||
// Enrolling is the moment there is a backend to watch, and
|
||||
// re-enrolling elsewhere is the moment the old one stops being it.
|
||||
NotificationService.sync(this)
|
||||
Toast.makeText(this, "Enrolled with ${settings.baseUrl}", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.PrimaryTabRow
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
|
||||
/**
|
||||
* The app's root: one title, and four views of the backend behind it.
|
||||
*
|
||||
* These were four screens reached by four words in a row under the title, and the row was already
|
||||
* full -- the comment it replaced recorded that a fifth would have to go somewhere else. Tabs say
|
||||
* the same thing in less space and say one more thing besides: that these are places to be rather
|
||||
* than errands to run. Sessions, the machine's importable history, the models on it and the
|
||||
* machines themselves are all *the same backend*, looked at four ways, and none of them is a step
|
||||
* down from another. Settings still is a step down, which is why it stays a pushed screen and keeps
|
||||
* its own Back.
|
||||
*/
|
||||
private enum class MainTab(val label: String) {
|
||||
Sessions("Sessions"),
|
||||
Import("Import"),
|
||||
Models("Models"),
|
||||
Setups("Setups"),
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun MainScreen(
|
||||
settings: ServerSettings,
|
||||
reloadToken: Int,
|
||||
onOpen: (SessionSummary) -> Unit,
|
||||
onSpawn: () -> Unit,
|
||||
onImported: (SessionSummary) -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
) {
|
||||
var tab by remember { mutableStateOf(MainTab.Sessions) }
|
||||
var refreshToken by remember { mutableIntStateOf(0) }
|
||||
|
||||
// Coming back to the app asks again, on whichever tab is showing.
|
||||
//
|
||||
// What these four draw is a snapshot of a backend they are not connected to, so it is only as
|
||||
// fresh as the last answer -- and a *failed* answer is the one that outstays its welcome. A
|
||||
// phone that was away while the tunnel was down, or that fetched before the network came up,
|
||||
// came back to "Couldn't reach the server" sitting at the top of a list the server would now
|
||||
// answer for perfectly well, and nothing took it off until somebody pressed Refresh. A stale
|
||||
// failure is worse than a stale list: it is a claim about right now.
|
||||
//
|
||||
// Through the same token the Refresh button uses, so this is one instruction the tabs already
|
||||
// understand rather than a second path into each of them -- which is also what makes it cover
|
||||
// all four rather than the one the report came from.
|
||||
//
|
||||
// Not on the first entry: the tab composing already asks, and bumping here would make every
|
||||
// cold start fetch twice.
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
LaunchedEffect(lifecycleOwner) {
|
||||
var opening = true
|
||||
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
if (!opening) refreshToken++
|
||||
opening = false
|
||||
}
|
||||
}
|
||||
|
||||
// A tab the app put over the list has to step back to it rather than fall through to the
|
||||
// system default, which closes the app -- that reads as a crash to somebody who only meant to
|
||||
// get back to their sessions. Nested inside AppRoot's handler, so it wins while it is enabled.
|
||||
BackHandler(enabled = tab != MainTab.Sessions) { tab = MainTab.Sessions }
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 16.dp),
|
||||
) {
|
||||
Text(
|
||||
"AI Sessions",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// Glyphs rather than the words they replaced: neither ever changes, both are read
|
||||
// faster than they are spelled, and together they take the width that let the title
|
||||
// keep its own line. They sit on the title's row because they act on the whole
|
||||
// screen -- everything below this row is one tab's business, and a control belongs
|
||||
// with the thing it acts on.
|
||||
// Flush against each other: a glyph button carries its own padding, so two of them
|
||||
// side by side already have two rings between their marks and one ring plus this
|
||||
// row's padding to the screen edge.
|
||||
Row {
|
||||
GlyphButton(REFRESH_GLYPH, "Refresh", { refreshToken++ })
|
||||
GlyphButton(SETTINGS_GLYPH, "Settings", onSettings)
|
||||
}
|
||||
}
|
||||
// Primary rather than the plain TabRow, which is deprecated in favour of the two that
|
||||
// say where they sit: these are the app's top-level destinations.
|
||||
PrimaryTabRow(selectedTabIndex = tab.ordinal) {
|
||||
MainTab.entries.forEach { entry ->
|
||||
Tab(
|
||||
selected = tab == entry,
|
||||
onClick = { tab = entry },
|
||||
text = { Text(entry.label) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Refreshing means "ask again about what I am looking at", so the button feeds the tab
|
||||
// that is showing. The token from above means something else already changed what these
|
||||
// show; the two are the same instruction to the tab below, so they are summed rather than
|
||||
// tracked apart -- either one moving moves the sum, which is all a tab watches.
|
||||
val token = reloadToken + refreshToken
|
||||
when (tab) {
|
||||
MainTab.Sessions ->
|
||||
SessionListScreen(
|
||||
settings = settings,
|
||||
reloadToken = token,
|
||||
onOpen = onOpen,
|
||||
onSpawn = onSpawn,
|
||||
)
|
||||
MainTab.Import ->
|
||||
ImportScreen(settings = settings, reloadToken = token, onImported = onImported)
|
||||
MainTab.Models -> ModelsScreen(settings = settings, reloadToken = token)
|
||||
MainTab.Setups -> SetupsScreen(settings = settings, reloadToken = token)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import com.mikepenz.markdown.m3.Markdown
|
||||
import com.mikepenz.markdown.m3.markdownColor
|
||||
import com.mikepenz.markdown.m3.markdownTypography
|
||||
import com.mikepenz.markdown.model.State
|
||||
import com.mikepenz.markdown.model.parseMarkdown
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* An assistant's reply, rendered as the markdown it is written in.
|
||||
*
|
||||
* The parsing is the library's. Markdown is somebody else's specification, and a hand-written
|
||||
* subset of one disagrees with it at the edges -- which is where the bug reports come from, one
|
||||
* case at a time. This file's whole job is the mapping onto the app's palette and type scale.
|
||||
*
|
||||
* Colours come from the theme rather than from the renderer's defaults, so code, links and rules
|
||||
* are the same Catppuccin values the rest of the app uses. Nothing here picks a colour of its own.
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(text: String, replies: ParsedReplies, modifier: Modifier = Modifier) {
|
||||
val body = MaterialTheme.typography.bodyLarge
|
||||
val parsed = parsedMarkdown(text, replies)
|
||||
Markdown(
|
||||
parsed,
|
||||
colors =
|
||||
markdownColor(
|
||||
text = MaterialTheme.colorScheme.onSurface,
|
||||
dividerColor = MaterialTheme.colorScheme.outlineVariant,
|
||||
// The dark surface every verbatim thing in this app sits on -- see [rawSurface],
|
||||
// and the tool call above this reply, which now matches. `surfaceVariant` was
|
||||
// exactly a card's own fill, so a fenced block inside a tool call had no
|
||||
// background at all and one in a reply read as a step *up* out of the page.
|
||||
codeBackground = rawSurface,
|
||||
inlineCodeBackground = rawSurface,
|
||||
// The same tint a code block gets, rather than the renderer's 2%-alpha default:
|
||||
// two adjacent tints that differ by a fiftieth read as one flat block on a phone,
|
||||
// so the table would have had a border-less grid and nothing saying where it began.
|
||||
tableBackground = MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
typography =
|
||||
markdownTypography(
|
||||
// A ladder that starts near the body text and descends, because these are headings
|
||||
// inside a chat message rather than the top of a document. The renderer's defaults
|
||||
// are the Material *display* styles -- `#` came out at 57sp and `##` at 45sp, which
|
||||
// is bigger than this app's own screen titles and reads as the reply shouting.
|
||||
//
|
||||
// Every step is a different size, so two levels of nesting never draw the same:
|
||||
// one clear step per level is the whole job of a heading.
|
||||
h1 = MaterialTheme.typography.headlineSmall,
|
||||
h2 = MaterialTheme.typography.titleLarge,
|
||||
h3 = MaterialTheme.typography.titleMedium,
|
||||
h4 = MaterialTheme.typography.titleSmall,
|
||||
h5 = MaterialTheme.typography.labelMedium,
|
||||
h6 = MaterialTheme.typography.labelSmall,
|
||||
// Body text at the size everything else in the transcript uses.
|
||||
text = body,
|
||||
paragraph = body,
|
||||
ordered = body,
|
||||
bullet = body,
|
||||
list = body,
|
||||
table = body,
|
||||
// Code in a monospace face, in the ordinary text colour. The face and the tinted
|
||||
// background are what say "this is code"; colour is not, and it used to be green
|
||||
// -- the palette's colour for a *literal*. A block of code is not a literal, it
|
||||
// is text that happens to be code, and painting all of it green said the whole
|
||||
// block was one. Where a literal really does appear inside code, the thing that
|
||||
// should colour it is a syntax highlighter looking at the code, which is exactly
|
||||
// what a tool call's input already gets from `catppuccinSyntax`.
|
||||
//
|
||||
// The colour rides on the style here rather than in `markdownColor`, which
|
||||
// stopped carrying `codeText`/`inlineCodeText`/`linkText` when the renderer moved
|
||||
// them onto the typography.
|
||||
code =
|
||||
MaterialTheme.typography.bodyMedium.copy(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
inlineCode =
|
||||
body.copy(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
// Unspecified so an inline span keeps the size of the line it sits in.
|
||||
fontSize = TextUnit.Unspecified,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
textLink =
|
||||
TextLinkStyles(
|
||||
style =
|
||||
body
|
||||
.copy(
|
||||
color = linkColor,
|
||||
textDecoration = TextDecoration.Underline,
|
||||
)
|
||||
.toSpanStyle()
|
||||
),
|
||||
),
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* [text] parsed: on the composing thread the first time this row is drawn, and off it every time
|
||||
* afterwards.
|
||||
*
|
||||
* The first parse has to be inline. The renderer's own asynchronous path draws an empty loading
|
||||
* slot until its result arrives, so a row is measured at nothing before it is measured at its real
|
||||
* height, and the transcript above it collapses and springs back. Seen with five replies on screen
|
||||
* at once, every one of them blank, the whole conversation shrunk to fit a single screen; a moment
|
||||
* later it was all there again. That is the "skipping up and down" this list must never do, and no
|
||||
* amount of scroll anchoring can survive a row that lies about its height first.
|
||||
*
|
||||
* Every parse *after* the first is a different case, and it is the one that was costing: a reply
|
||||
* arrives as hundreds of deltas, each one re-parsing the whole message it has grown into. Measured
|
||||
* against `/stream 200` on the emulator, that was fifty-eight parses and 78ms of main-thread work
|
||||
* in three seconds, with single parses reaching 7ms -- most of a frame at 60Hz and more than one at
|
||||
* 120. Those go to a background thread, and the row keeps drawing the parse it already has until
|
||||
* the new one lands, so there is never a frame without a height. What is on screen is always a
|
||||
* real prefix of the reply rather than a guess at it; it is simply one parse behind.
|
||||
*/
|
||||
@Composable
|
||||
private fun parsedMarkdown(text: String, replies: ParsedReplies): State {
|
||||
// The text each parse came from, so the first composition's is not immediately repeated.
|
||||
val parsed = remember { mutableStateOf(text to replies.of(text)) }
|
||||
LaunchedEffect(text) {
|
||||
if (parsed.value.first == text) return@LaunchedEffect
|
||||
// Not through [replies]: this is a reply still arriving, and every delta would leave
|
||||
// another copy of a message that is about to be superseded.
|
||||
parsed.value =
|
||||
text to
|
||||
withContext(Dispatchers.Default) {
|
||||
DebugStats.timed("markdown reparsed while streaming") { parseMarkdown(text) }
|
||||
}
|
||||
}
|
||||
return parsed.value.second
|
||||
}
|
||||
|
||||
/**
|
||||
* Replies parsed before the row that draws them is composed.
|
||||
*
|
||||
* Parsing is the expensive half of drawing a reply, and it is expensive in proportion to how much
|
||||
* was written. Measured against a real Claude Code transcript on the emulator, one message took
|
||||
* **51ms** and several took 10-25ms, against 4.6ms for the short synthetic replies this was first
|
||||
* tuned on -- so a page of history landing composed several rows that each stalled the frame they
|
||||
* appeared in. That is the lag when a block loads.
|
||||
*
|
||||
* Nothing here changes what a row does when it has no answer waiting: it parses inline, on the
|
||||
* composing thread, because a row measured at nothing before it is measured at its real height
|
||||
* collapses the transcript above it. The point is only that by the time the reader scrolls to a
|
||||
* row, the answer is usually already made -- [warm] runs on a background thread as each page of
|
||||
* history arrives, which is seconds before anybody reaches the rows it brought.
|
||||
*
|
||||
* A miss is not stored, and that is what bounds this: the map holds one entry per message a page
|
||||
* warmed and nothing else, so a reply still streaming cannot fill it with hundreds of copies of
|
||||
* itself on the way to being finished. It is dropped with the screen, and emptied by the stream
|
||||
* reset that drops the rows it describes.
|
||||
*/
|
||||
@Stable
|
||||
class ParsedReplies {
|
||||
private val parsed = ConcurrentHashMap<String, State>()
|
||||
|
||||
/**
|
||||
* How each message divides into blocks, cached beside the parses of those blocks.
|
||||
*
|
||||
* Here rather than in a `remember` because the answer is wanted on two threads: by [warm], to
|
||||
* know which strings to make ready, and by the row that draws them. Finding it costs a parse of
|
||||
* the whole message, so doing it twice would undo what splitting is for.
|
||||
*/
|
||||
private val blocks = ConcurrentHashMap<String, List<String>>()
|
||||
|
||||
/**
|
||||
* How each message divides into prose and memory notes, cached for the same reason as
|
||||
* [blocksOf]: [transcriptUnits] asks per fold, and the regex scan behind [messageParts] is
|
||||
* proportional to the message every time where a lookup is proportional to nothing.
|
||||
*/
|
||||
private val parts = ConcurrentHashMap<String, List<MessagePart>>()
|
||||
|
||||
fun blocksOf(text: String): List<String> = blocks.computeIfAbsent(text) { markdownBlocks(it) }
|
||||
|
||||
fun partsOf(text: String): List<MessagePart> = parts.computeIfAbsent(text) { messageParts(it) }
|
||||
|
||||
/** The parse of [text] -- the one made ahead, or one made now. */
|
||||
fun of(text: String): State =
|
||||
parsed[text]?.also { DebugStats.count("markdown ready") }
|
||||
?: DebugStats.timed("markdown parsed while composing") { parseMarkdown(text) }
|
||||
|
||||
/**
|
||||
* Parses whatever is not held yet. Call off the composing thread; that is the whole point.
|
||||
*
|
||||
* Suspending, and yielding between messages, because "off the composing thread" is not the same
|
||||
* as "free". A page of history arrives as hundreds of parses at once -- 1.5 seconds of them in
|
||||
* a twelve second scroll, measured on a Pixel 9 Pro XL -- and on the default dispatcher that is
|
||||
* every core busy, with the frame's own thread waiting for one. That showed up as 21ms of
|
||||
* `waited` at the 90th percentile: the frame could not start, rather than taking too long.
|
||||
*/
|
||||
suspend fun warm(texts: List<String>) {
|
||||
texts.forEach { text ->
|
||||
parsed.computeIfAbsent(text) {
|
||||
DebugStats.timed("markdown warmed") { parseMarkdown(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Everything these described is gone; see [ParsedReplies]. */
|
||||
fun clear() {
|
||||
parsed.clear()
|
||||
blocks.clear()
|
||||
parts.clear()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* An assistant's reply, with anything it says it remembered drawn as a note rather than as markup.
|
||||
*
|
||||
* Claude Code marks a sentence that came from its stored memory by wrapping it in `<cc-memory
|
||||
* filenames="...">`. Markdown has nothing to say about that, so it arrived on screen as literal
|
||||
* angle brackets in the middle of a sentence -- which reads as the model having emitted broken
|
||||
* HTML. It is really the opposite: a claim about where something came from, which is worth showing,
|
||||
* because "I was told this before" and "I worked this out just now" are different things and the
|
||||
* reader cannot otherwise tell them apart.
|
||||
*
|
||||
* A tag that has not finished arriving is left alone. Streaming means the closing tag may be
|
||||
* seconds away, and a half-written marker is not a marker yet.
|
||||
*/
|
||||
@Composable
|
||||
fun AssistantMessage(
|
||||
text: String,
|
||||
replies: ParsedReplies,
|
||||
modifier: Modifier = Modifier,
|
||||
live: Boolean = false,
|
||||
) {
|
||||
DebugStats.count("message composed")
|
||||
val parts = remember(text) { messageParts(text) }
|
||||
val only = parts.singleOrNull()
|
||||
if (only is MessagePart.Prose) {
|
||||
BlockedMarkdown(only.text, replies, modifier, live)
|
||||
return
|
||||
}
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
parts.forEach { part ->
|
||||
when (part) {
|
||||
is MessagePart.Prose -> BlockedMarkdown(part.text, replies, live = live)
|
||||
is MessagePart.Remembered -> MemoryNote(part, replies)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The pieces [AssistantMessage] draws, which is [splitMemoryNotes] with one correction.
|
||||
*
|
||||
* A reply carrying no notes is drawn from the message as it arrived rather than from the trimmed
|
||||
* prose part made while looking for them -- inspecting a message must not change it. That belongs
|
||||
* here rather than at the places that need the answer, because [warm] has to name the same strings
|
||||
* the rows draw: a string warmed under a key no row ever looks up is a miss that nothing reports,
|
||||
* and the row pays the parse in the frame it appears, which is the cost being removed.
|
||||
*
|
||||
* Public because [transcriptUnits] flattens settled replies into the same parts; go through
|
||||
* [ParsedReplies.partsOf] on any path that runs per fold or per page, so the scan happens once per
|
||||
* message.
|
||||
*/
|
||||
fun messageParts(text: String): List<MessagePart> {
|
||||
val parts = splitMemoryNotes(text)
|
||||
return if (parts.singleOrNull() is MessagePart.Prose) listOf(MessagePart.Prose(text)) else parts
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun MemoryNote(note: MessagePart.Remembered, replies: ParsedReplies) {
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
// Named, not just tinted: a colour can say "this one is different", but it cannot say
|
||||
// what kind of different, and "recalled from a file" is a difference in kind.
|
||||
Text(
|
||||
if (note.files.size == 1) "remembered from ${note.files[0]}"
|
||||
else "remembered from ${note.files.joinToString(", ")}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
MarkdownText(note.text, replies, Modifier.padding(top = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One piece of a reply: ordinary prose, or a sentence attributed to a memory file. */
|
||||
sealed class MessagePart {
|
||||
/** The markdown this piece is drawn from. */
|
||||
abstract val text: String
|
||||
|
||||
data class Prose(override val text: String) : MessagePart()
|
||||
|
||||
data class Remembered(override val text: String, val files: List<String>) : MessagePart()
|
||||
}
|
||||
|
||||
private val MEMORY_NOTE =
|
||||
Regex("""<cc-memory\s+filenames="([^"]*)"\s*>(.*?)</cc-memory>""", RegexOption.DOT_MATCHES_ALL)
|
||||
|
||||
/**
|
||||
* Splits [text] into prose and memory notes, in order.
|
||||
*
|
||||
* Always returns at least one part, so a message with no notes in it is one piece of prose and
|
||||
* costs nothing extra to draw.
|
||||
*/
|
||||
fun splitMemoryNotes(text: String): List<MessagePart> {
|
||||
val parts = mutableListOf<MessagePart>()
|
||||
var at = 0
|
||||
for (match in MEMORY_NOTE.findAll(text)) {
|
||||
val before = text.substring(at, match.range.first)
|
||||
if (before.isNotBlank()) parts += MessagePart.Prose(before.trim())
|
||||
val files = match.groupValues[1].split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||
parts += MessagePart.Remembered(match.groupValues[2].trim(), files)
|
||||
at = match.range.last + 1
|
||||
}
|
||||
val rest = text.substring(at)
|
||||
if (rest.isNotBlank() || parts.isEmpty()) parts += MessagePart.Prose(rest.trim())
|
||||
return parts
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.mikepenz.markdown.model.State
|
||||
import com.mikepenz.markdown.model.parseMarkdown
|
||||
|
||||
/**
|
||||
* A message's top-level markdown blocks, cut where the parser says the blocks are.
|
||||
*
|
||||
* The point is the draw phase. A reply's display list holds every glyph of it, and it is
|
||||
* re-recorded whenever drawing is invalidated -- so one long message is as expensive to draw as a
|
||||
* hundred short ones, and skipping the rows around it cannot help while it is the one on screen.
|
||||
* Measured on a Pixel 9 Pro XL: 97% of rows correctly skipped, and the tallest row still being
|
||||
* drawn was 36,982px, about twenty-five screens in a single message. Cut into blocks, only the
|
||||
* screen or two actually being read is ever recorded.
|
||||
*
|
||||
* Cut at the parser's own boundaries rather than at blank lines, which is the whole reason this is
|
||||
* safe: a heading, a fenced code block, a table and a list are each one node whatever is inside
|
||||
* them, so a loose list does not become five one-item lists and a fence is never split down the
|
||||
* middle. Guessing at block boundaries with a line scanner gets all three of those wrong.
|
||||
*
|
||||
* It also bounds parsing, which was the other symptom: one message took **1.4 seconds** to parse as
|
||||
* a single unit, and a block is a paragraph.
|
||||
*/
|
||||
fun markdownBlocks(text: String): List<String> {
|
||||
// A reference definition sits at the foot of a message and is used by links above it. Parsed on
|
||||
// its own each block would lose the definition, and the link would draw as literal brackets --
|
||||
// so a message carrying one is kept whole. Rare enough to be worth giving up the split for.
|
||||
if (REFERENCE_DEFINITION.containsMatchIn(text)) return listOf(text)
|
||||
val parsed = parseMarkdown(text) as? State.Success ?: return listOf(text)
|
||||
val blocks =
|
||||
parsed.node.children
|
||||
.map { text.substring(it.startOffset, it.endOffset) }
|
||||
.filter { it.isNotBlank() }
|
||||
return if (blocks.size <= 1) listOf(text) else blocks
|
||||
}
|
||||
|
||||
/** `[label]: https://…` at the start of a line -- see [markdownBlocks]. */
|
||||
private val REFERENCE_DEFINITION = Regex("""^ {0,3}\[[^\]]+]:\s""", RegexOption.MULTILINE)
|
||||
|
||||
/**
|
||||
* A reply drawn a block at a time.
|
||||
*
|
||||
* Each block keeps its composition and its layout whichever way it is scrolled -- that is what
|
||||
* stops a message being rebuilt when somebody comes back to it. The heights come from the blocks
|
||||
* themselves as they are measured, so the running total is the same arrangement the list uses one
|
||||
* level up.
|
||||
*
|
||||
* [live] is the message currently arriving, and it is the only one that gets a layer per block. A
|
||||
* layer buys one thing here: when drawing is invalidated, only the block that changed is
|
||||
* re-recorded instead of the whole reply. That is worth a great deal while a reply is streaming,
|
||||
* because every delta invalidates the message and a finished one can be twenty-five screens tall.
|
||||
* It is worth nothing once the message stops changing -- measured on a Pixel 9 Pro XL, whole rows
|
||||
* were re-recorded 65 times in fifty seconds of reading -- and it is not free: each layer is a
|
||||
* layout node and a display list held for the life of the row, and live node count is what the
|
||||
* per-frame cost of the transcript scales with.
|
||||
*/
|
||||
@Composable
|
||||
fun BlockedMarkdown(
|
||||
text: String,
|
||||
replies: ParsedReplies,
|
||||
modifier: Modifier = Modifier,
|
||||
live: Boolean = false,
|
||||
) {
|
||||
val blocks = remember(text) { replies.blocksOf(text) }
|
||||
if (blocks.size == 1) {
|
||||
MarkdownText(blocks.first(), replies, modifier)
|
||||
return
|
||||
}
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(BLOCK_SPACING)) {
|
||||
blocks.forEach { block ->
|
||||
MarkdownText(
|
||||
block,
|
||||
replies,
|
||||
Modifier.fillMaxWidth()
|
||||
.then(if (live) Modifier.graphicsLayer() else Modifier)
|
||||
.drawWithContent {
|
||||
val started = System.nanoTime()
|
||||
drawContent()
|
||||
DebugStats.record("record: one block", System.nanoTime() - started)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The gap between one block of a reply and the next, here and in [transcriptUnits]. */
|
||||
val BLOCK_SPACING = 6.dp
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.example.aiapp
|
||||
|
||||
/**
|
||||
* What a session with no model of its own is called, in the button and in the list it opens.
|
||||
*
|
||||
* One constant rather than a literal in each place, because the two have to agree: a picker whose
|
||||
* options cannot say every state its button can display is one you can leave and not get back to.
|
||||
* It is also the Claude CLI's own word for "whatever is configured", so choosing it is a request
|
||||
* the session can act on rather than a name this app made up.
|
||||
*/
|
||||
const val DEFAULT_MODEL = "default"
|
||||
|
||||
/**
|
||||
* A model's name as a person reads it.
|
||||
*
|
||||
* Providers answer with their own full identifier -- Claude Code resolves `haiku` to
|
||||
* `claude-haiku-4-5-20251001` and reports that, which is the honest answer to "what is this session
|
||||
* using" and far too long for a button in a row that also has to hold Stop and Send.
|
||||
*
|
||||
* So the two ends that identify nothing are dropped and nothing else is: the vendor prefix, which
|
||||
* is the same on every model this app can show, and the release date, which distinguishes builds of
|
||||
* one model rather than one model from another. What is left is the part somebody chose --
|
||||
* `haiku-4-5` -- and anything that does not look like that is returned untouched, since a name this
|
||||
* does not recognise is a name it has no business editing.
|
||||
*
|
||||
* A display decision, not a correction: the full name is what the session reports and what a reader
|
||||
* is shown when there is room for it.
|
||||
*/
|
||||
fun modelLabel(model: String?): String {
|
||||
val name = model?.takeIf { it.isNotBlank() } ?: return DEFAULT_MODEL
|
||||
return name.removePrefix("claude-").replace(DATED_SUFFIX, "")
|
||||
}
|
||||
|
||||
/** A trailing `-YYYYMMDD`, which is how these identifiers carry their release date. */
|
||||
private val DATED_SUFFIX = Regex("""-\d{8}$""")
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Models on the backend, and HuggingFace to get more from.
|
||||
*
|
||||
* Everything here is the server's state rather than this screen's: what is downloaded, and what is
|
||||
* downloading, are the same answers on every enrolled device, and a download started here keeps
|
||||
* going when this screen closes.
|
||||
*/
|
||||
@Composable
|
||||
fun ModelsScreen(settings: ServerSettings, reloadToken: Int) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf<LoadState<Models>>(LoadState.Loading) }
|
||||
var query by remember { mutableStateOf("") }
|
||||
var results by remember { mutableStateOf<LoadState<List<RemoteRepo>>?>(null) }
|
||||
var openRepo by remember { mutableStateOf<String?>(null) }
|
||||
var repoFiles by remember { mutableStateOf<LoadState<List<RemoteFile>>?>(null) }
|
||||
var actionError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
suspend fun reload() {
|
||||
state =
|
||||
try {
|
||||
withContext(Dispatchers.IO) { LoadState.Loaded(fetchModels(settings)) }
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Polled rather than pushed: a download belongs to the machine, not to
|
||||
// any session, so it has no event stream of its own. Slow enough not
|
||||
// to matter, frequent enough that a bar moves.
|
||||
// Keyed on the token as well, so the header's Refresh restarts the loop with a read now
|
||||
// rather than leaving the reader watching for up to a second and a half to see whether
|
||||
// anything happened.
|
||||
LaunchedEffect(reloadToken) {
|
||||
while (true) {
|
||||
reload()
|
||||
delay(1500)
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(16.dp)) {
|
||||
actionError?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = { query = it },
|
||||
label = { Text("Search HuggingFace") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(
|
||||
enabled = query.isNotBlank(),
|
||||
onClick = {
|
||||
openRepo = null
|
||||
results = LoadState.Loading
|
||||
scope.launch {
|
||||
results =
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
LoadState.Loaded(searchModels(settings, query))
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text("Search")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
when (val current = state) {
|
||||
is LoadState.Loading -> item { CircularProgressIndicator() }
|
||||
is LoadState.Error ->
|
||||
item { Text(current.message, color = MaterialTheme.colorScheme.error) }
|
||||
is LoadState.Loaded -> {
|
||||
if (current.value.downloads.isNotEmpty()) {
|
||||
item { SectionLabel("Downloading") }
|
||||
items(current.value.downloads, key = { it.key + it.run }) { download ->
|
||||
DownloadCard(download) {
|
||||
scope.launch {
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
cancelDownload(settings, download.key)
|
||||
}
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item { SectionLabel("On the backend") }
|
||||
if (current.value.local.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"None yet. Search above to find one.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(current.value.local, key = { it.key }) { model ->
|
||||
LocalModelCard(model) {
|
||||
scope.launch {
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
deleteModel(settings, model.key)
|
||||
}
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results?.let { found ->
|
||||
item { SectionLabel("HuggingFace") }
|
||||
when (found) {
|
||||
is LoadState.Loading -> item { CircularProgressIndicator() }
|
||||
is LoadState.Error ->
|
||||
item { Text(found.message, color = MaterialTheme.colorScheme.error) }
|
||||
is LoadState.Loaded ->
|
||||
items(found.value, key = { it.id }) { repo ->
|
||||
val open = openRepo == repo.id
|
||||
RepoRow(repo, expanded = open) {
|
||||
if (open) {
|
||||
openRepo = null
|
||||
} else {
|
||||
openRepo = repo.id
|
||||
repoFiles = LoadState.Loading
|
||||
scope.launch {
|
||||
repoFiles =
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
LoadState.Loaded(
|
||||
fetchRepoFiles(settings, repo.id)
|
||||
)
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Inside the expanded repository's own item
|
||||
// rather than as a section after the list:
|
||||
// drawn after every card, a repository's files
|
||||
// read as belonging to whichever card happened
|
||||
// to be last.
|
||||
if (open) {
|
||||
when (val files = repoFiles) {
|
||||
null -> {}
|
||||
is LoadState.Loading -> CircularProgressIndicator()
|
||||
is LoadState.Error ->
|
||||
Text(files.message, color = MaterialTheme.colorScheme.error)
|
||||
is LoadState.Loaded ->
|
||||
Column {
|
||||
val busy =
|
||||
(state as? LoadState.Loaded)
|
||||
?.value
|
||||
?.downloads
|
||||
.orEmpty()
|
||||
.filter { it.state == "running" }
|
||||
.map { it.key }
|
||||
.toSet()
|
||||
files.value.forEach { file ->
|
||||
RepoFileRow(
|
||||
file,
|
||||
downloading = "${repo.id}/${file.path}" in busy,
|
||||
) {
|
||||
scope.launch {
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
startDownload(
|
||||
settings,
|
||||
repo.id,
|
||||
file.path,
|
||||
)
|
||||
}
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionLabel(text: String) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(text, style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DownloadCard(download: Download, onCancel: () -> Unit) {
|
||||
Card(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(download.file, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
download.repo,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// A determinate bar only when the size is known. The server
|
||||
// sends no total when it was never told one, and a bar drawn
|
||||
// from a guess is worse than one that admits it is counting.
|
||||
if (download.total != null && download.total > 0) {
|
||||
LinearProgressIndicator(
|
||||
progress = { download.done.toFloat() / download.total.toFloat() },
|
||||
// Blue at every value, unlike a quota bar: a download nearing its end is
|
||||
// nearing success, and colouring it like a limit being approached would say
|
||||
// the opposite of what is happening.
|
||||
color = progressColor,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text(
|
||||
"${gigabytes(download.done)} of ${gigabytes(download.total)}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
} else {
|
||||
LinearProgressIndicator(color = progressColor, modifier = Modifier.fillMaxWidth())
|
||||
Text(
|
||||
"${gigabytes(download.done)} so far, total size unknown",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
download.error?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
Row {
|
||||
Text(
|
||||
download.state,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (download.state == "running") {
|
||||
TextButton(onClick = onCancel) { Text("Cancel") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LocalModelCard(model: LocalModel, onDelete: () -> Unit) {
|
||||
Card(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(model.file, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
"${model.repo} · ${gigabytes(model.bytes)}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onDelete) { Text("Delete") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RepoRow(repo: RemoteRepo, expanded: Boolean, onToggle: () -> Unit) {
|
||||
Card(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
repo.id,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
maxLines = 1,
|
||||
// The owner is the part that repeats; the model name at
|
||||
// the end is what tells two entries apart.
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
Text(
|
||||
"${repo.downloads} downloads · ${repo.likes} likes",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onToggle) { Text(if (expanded) "Hide" else "Files") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RepoFileRow(file: RemoteFile, downloading: Boolean, onDownload: () -> Unit) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 16.dp, top = 4.dp, bottom = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(file.path, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
gigabytes(file.bytes),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
// Disabled rather than absent, so the row reads the same whether
|
||||
// this one is absent, already here, or on its way. Offering
|
||||
// "Download" for a file that is downloading would be a button that
|
||||
// does nothing anyone can see -- the server joins the running
|
||||
// download rather than starting a second.
|
||||
TextButton(enabled = !file.have && !downloading, onClick = onDownload) {
|
||||
Text(
|
||||
when {
|
||||
file.have -> "Downloaded"
|
||||
downloading -> "Downloading"
|
||||
else -> "Download"
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun gigabytes(bytes: Long): String =
|
||||
if (bytes >= 1_000_000_000) {
|
||||
"%.2f GB".format(bytes / 1_000_000_000.0)
|
||||
} else {
|
||||
"%.0f MB".format(bytes / 1_000_000.0)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.Font
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* The icons the app draws, as glyphs in a Nerd Fonts subset rather than as vector assets.
|
||||
*
|
||||
* Drawing them as *text* is what makes them cheap: an icon beside a line of text wants that line's
|
||||
* size, colour and baseline, and a `Text` gets all three for free where an `Icon` needs each one
|
||||
* set and kept in step by hand.
|
||||
*
|
||||
* This replaced a hand-drawn canvas gear, whose doc comment argued against icon fonts on the
|
||||
* grounds that a system font may not have the glyph and whoever gets the empty box instead is never
|
||||
* the person who wrote it. That objection is about *relying* on a system font, and it is exactly
|
||||
* right: the answer is not to avoid glyphs but to ship them. The font here is
|
||||
* `app/build-icon-font.sh`'s output -- eleven glyphs, 2.1 KB, subset out of the 3 MB symbols font
|
||||
* and committed -- so the codepoints below are resolved by an asset in the APK and cannot come back
|
||||
* as tofu. Adding one means adding its codepoint in *both* places; a codepoint here that the script
|
||||
* did not subset is a glyph that silently isn't there.
|
||||
*
|
||||
* The subset is the font's **Mono** face, where every glyph is exactly one em wide and one em tall.
|
||||
* That is what makes two icons the same size without either of them being given a size: the
|
||||
* proportional face's advances run from 0.46 em to 0.92 em, so a Send button and a Stop button side
|
||||
* by side came out visibly different widths, and matching them at the call site would have meant
|
||||
* one hardcoded measurement per pair. [GLYPH_SIZE] carries the cost.
|
||||
*
|
||||
* The same arrangement as dev-updater, down to the cog and the refresh arrow being the same two
|
||||
* Material Design codepoints. Those two must not drift: an icon that means "settings" in one app
|
||||
* and something else in the other is the failure this is worth preventing. The script is copied
|
||||
* rather than shared because most of what looks like duplication is the `GLYPHS` list, which has to
|
||||
* differ -- the point of subsetting is to ship only the codepoints one app draws. All Material
|
||||
* Design bar one, so they read as one family; the exception is noted where it is declared.
|
||||
*/
|
||||
val NerdIcons = FontFamily(Font(R.font.nerd_icons))
|
||||
|
||||
/** Nerd Fonts puts these in plane 15, so each is a surrogate pair. */
|
||||
private fun glyph(codePoint: Int) = String(Character.toChars(codePoint))
|
||||
|
||||
/** `md-cog` -- settings for the thing it sits beside. */
|
||||
val SETTINGS_GLYPH = glyph(0xF0493)
|
||||
|
||||
/** `md-refresh` -- ask the server again for whatever is on screen. */
|
||||
val REFRESH_GLYPH = glyph(0xF0450)
|
||||
|
||||
/** `md-send` -- the filled paper plane: submit what is in the composer. */
|
||||
val SEND_GLYPH = glyph(0xF048A)
|
||||
|
||||
/**
|
||||
* `md-stop` -- a filled square: end the process behind this session.
|
||||
*
|
||||
* The square is what stop has meant since tape decks, and it is spent here on the thing that
|
||||
* actually stops rather than on pausing. [PAUSE_GLYPH] is the turn; this is the session.
|
||||
*/
|
||||
val STOP_GLYPH = glyph(0xF04DB)
|
||||
|
||||
/**
|
||||
* `md-pause` -- two bars: take the running turn away and leave the session there.
|
||||
*
|
||||
* The pair with [STOP_GLYPH] and [PLAY_GLYPH] is the point: one button in the composer says what
|
||||
* pressing it now would do to the process, and the three marks are the three answers. An interrupt
|
||||
* ends a turn and nothing else -- the CLI is still there and still holds the conversation -- which
|
||||
* is a pause, not a stop, and drawing it as a square said otherwise.
|
||||
*/
|
||||
val PAUSE_GLYPH = glyph(0xF03E4)
|
||||
|
||||
/** `md-play` -- start the process again, on the conversation it left. See [PAUSE_GLYPH]. */
|
||||
val PLAY_GLYPH = glyph(0xF040A)
|
||||
|
||||
/**
|
||||
* `md-send_clock` -- the same paper plane with a clock on it: this message will wait its turn.
|
||||
*
|
||||
* The pair with [SEND_GLYPH] is the point. Sending during a turn queues the message rather than
|
||||
* starting one, and the two buttons have to be told apart at a glance -- one glyph doing both jobs
|
||||
* while looking identical would promise something immediate and do something that waits.
|
||||
*/
|
||||
val QUEUE_GLYPH = glyph(0xF1163)
|
||||
|
||||
/** `md-close` -- take this off again: an attachment picked and not wanted. */
|
||||
val CLOSE_GLYPH = glyph(0xF0156)
|
||||
|
||||
/** `md-arrow_left` -- back one level, to whatever this was opened from. */
|
||||
val BACK_GLYPH = glyph(0xF004D)
|
||||
|
||||
/** `md-bell` -- the notifications this session is allowed to raise. */
|
||||
val BELL_GLYPH = glyph(0xF009A)
|
||||
|
||||
/**
|
||||
* `fa-line_chart` -- how much of the account's rate limits is gone.
|
||||
*
|
||||
* Font Awesome's rather than Material's, which is the one break in the family above: it was asked
|
||||
* for by name, and Material's chart glyphs are a bare line where this one has its axes, which is
|
||||
* what makes it read as a measurement rather than as a trend.
|
||||
*/
|
||||
val USAGE_GLYPH = glyph(0xF201)
|
||||
|
||||
/**
|
||||
* `md-speedometer` -- what this session is costing to draw.
|
||||
*
|
||||
* A speedometer rather than a bug, because what it copies is a measurement rather than a fault
|
||||
* report: it is as useful on a screen that feels fine, where the answer is that nothing is slow.
|
||||
*/
|
||||
val SPEED_GLYPH = glyph(0xF04C5)
|
||||
|
||||
/**
|
||||
* The size an icon draws at beside a line of text.
|
||||
*
|
||||
* 17 rather than the 20 it was while the font was the proportional face. A glyph there filled at
|
||||
* most 0.83 em of its point size and most filled a good deal less, so the number was standing in
|
||||
* for the headroom above the tallest one; in the Mono face every glyph fills its em exactly, and
|
||||
* keeping 20 would have made every icon in the app step up by a fifth for no reason anybody asked
|
||||
* for. This is what the largest of them already drew at.
|
||||
*/
|
||||
private val GLYPH_SIZE = 17.sp
|
||||
|
||||
/**
|
||||
* The same measurement in dp: a glyph's em box is its point size, and a layout is laid out in dp.
|
||||
*/
|
||||
private val GLYPH_EXTENT = GLYPH_SIZE.value.dp
|
||||
|
||||
/**
|
||||
* The square a glyph button occupies: the mark, plus the same ring of padding on all four sides.
|
||||
*
|
||||
* The ring is the whole spacing rule. Every gap around a header icon comes out of it -- one ring to
|
||||
* the screen edge, two where a button meets its neighbour -- so nothing outside has to add a gap of
|
||||
* its own, and a mark cannot end up further from the button beside it than from the edge of the
|
||||
* screen. That is what it was: the box was the size of the mark (28dp) and the separation was
|
||||
* bolted on beside it, which left the two header icons 31dp apart and the outer one 14dp from the
|
||||
* edge, so a pair that acts on one screen read as two unrelated marks with one falling off it.
|
||||
*
|
||||
* 48dp is the platform's minimum touch target, so the square is also the whole of what a finger has
|
||||
* to find. It is what the pressed-state ripple draws, too: at 28dp that circle was inscribed in the
|
||||
* mark's own corners, and beside a title it arrived at the first letter. And it is taller than any
|
||||
* header's text, which is what lets the button fill a header row rather than sit in the middle of
|
||||
* one -- the rows add no vertical padding of their own for the same reason they add no gap.
|
||||
*/
|
||||
private val GLYPH_BUTTON_SIZE = 48.dp
|
||||
|
||||
/**
|
||||
* The ring itself, for putting something that is *not* a glyph button next to one -- a title beside
|
||||
* a back arrow.
|
||||
*
|
||||
* Two glyph buttons need nothing between them: each brings its own ring and the two add up, which
|
||||
* is why a row of them sets no spacing. Text brings none, so the second ring has to be asked for.
|
||||
* Without it the pressed-state circle, which fills the whole square, arrives at the first letter of
|
||||
* the title -- and the gap a reader sees between the mark and that title is then half the one
|
||||
* between the two marks at the other end of the same row.
|
||||
*/
|
||||
val GLYPH_BUTTON_MARGIN = (GLYPH_BUTTON_SIZE - GLYPH_EXTENT) / 2
|
||||
|
||||
/**
|
||||
* A glyph you can press: the icon equivalent of a `TextButton`.
|
||||
*
|
||||
* Its own composable so that every icon button in the app is one size and one colour without each
|
||||
* caller saying so, and so the [label] none of them displays is still there for a screen reader --
|
||||
* which is all assistive technology has to go on, and also the answer to "what was that button for"
|
||||
* six months from now.
|
||||
*
|
||||
* [enabled] is passed through rather than left to callers hiding the button: a control that comes
|
||||
* and goes makes its own absence the signal, and absence cannot say whether there was nothing to do
|
||||
* or nobody checked.
|
||||
*/
|
||||
@Composable
|
||||
fun GlyphButton(
|
||||
glyph: String,
|
||||
label: String,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
colour: Color = MaterialTheme.colorScheme.primary,
|
||||
) {
|
||||
IconButton(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = modifier.size(GLYPH_BUTTON_SIZE).semantics { contentDescription = label },
|
||||
) {
|
||||
Glyph(glyph, colour = if (enabled) colour else MaterialTheme.colorScheme.outline)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One icon, drawn as text.
|
||||
*
|
||||
* Callers that are already inside something pressable use this; [GlyphButton] is the one that adds
|
||||
* the press. Either way the caller owes it a description, since neither draws a word.
|
||||
*/
|
||||
@Composable
|
||||
fun Glyph(
|
||||
glyph: String,
|
||||
modifier: Modifier = Modifier,
|
||||
colour: Color = MaterialTheme.colorScheme.primary,
|
||||
size: TextUnit = GLYPH_SIZE,
|
||||
) {
|
||||
// Line height of the point size, which for this font is the square the glyph draws in: its
|
||||
// ascent and descent add up to exactly one em, and every glyph in the Mono face fills that em.
|
||||
// Left to the inherited body style the line box was 24sp tall around a 17sp-wide mark, so a
|
||||
// glyph took a seventh more vertical space than horizontal wherever one is drawn without a box
|
||||
// around it -- and where there is a box, that leading is what its padding is measured through.
|
||||
Text(
|
||||
glyph,
|
||||
fontFamily = NerdIcons,
|
||||
fontSize = size,
|
||||
lineHeight = size,
|
||||
color = colour,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.NotificationChannelCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import kotlin.concurrent.thread
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Telling somebody a session wants them, when they are not looking at the app.
|
||||
*
|
||||
* This is a **foreground service**, which on Android is the only way to keep a connection open
|
||||
* while the app is closed -- there has been no such thing as a long-lived background service since
|
||||
* Android 8. It is what Syncthing does for the same reason. Discord is not a counter-example: it
|
||||
* gets a push from Google's servers, which would mean this backend talking to Google about
|
||||
* somebody's coding sessions, and the whole point of the tunnel is that it does not.
|
||||
*
|
||||
* The cost Android charges for it is a notification of its own that cannot be dismissed. That is
|
||||
* made as quiet as the platform allows: [ONGOING_CHANNEL] is `IMPORTANCE_MIN`, so it makes no
|
||||
* sound, shows no status-bar icon, and sits at the bottom of the shade -- the same arrangement
|
||||
* Syncthing's "hide the persistent notification" option produces. It is not hidden outright,
|
||||
* because it cannot be and because it should not be: it is the honest indicator that something is
|
||||
* holding a connection open.
|
||||
*/
|
||||
class NotificationService : Service() {
|
||||
@Volatile private var stream: HttpURLConnection? = null
|
||||
@Volatile private var stopping = false
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val settings = loadServerSettings(this)
|
||||
if (settings == null) {
|
||||
// Nothing to connect to. Stopping rather than idling: a service
|
||||
// holding no connection still costs the ongoing notification,
|
||||
// which would then be announcing work that is not happening.
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
// Through ServiceCompat so the type is stated once and ignored on
|
||||
// the versions that predate types, rather than branching here.
|
||||
ServiceCompat.startForeground(this, ONGOING_ID, ongoingNotification(), foregroundType())
|
||||
thread(isDaemon = true, name = "ai-app-notifications") { follow(settings) }
|
||||
// Restarted if Android kills it, which is the whole point: the
|
||||
// window this covers is exactly the one where nobody is watching.
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
stopping = true
|
||||
stream?.disconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows the backend's notification stream, reconnecting until stopped.
|
||||
*
|
||||
* A dropped connection is the ordinary case here rather than an error -- a phone changes
|
||||
* networks, the tunnel comes and goes, the backend restarts -- so it retries quietly and
|
||||
* forever. Nothing is shown when it cannot connect: a notification saying "I could not tell you
|
||||
* whether anything happened" on a phone in somebody's pocket is noise about a condition they
|
||||
* cannot act on, and the session list already says what is waiting when they next look.
|
||||
*/
|
||||
private fun follow(settings: ServerSettings) {
|
||||
while (!stopping) {
|
||||
try {
|
||||
readStream(settings)
|
||||
} catch (_: IOException) {
|
||||
// Deliberate: see above.
|
||||
}
|
||||
if (stopping) return
|
||||
try {
|
||||
Thread.sleep(RECONNECT_DELAY_MS)
|
||||
} catch (_: InterruptedException) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readStream(settings: ServerSettings) {
|
||||
val connection =
|
||||
URL("${settings.baseUrl}/notifications").openConnection() as HttpURLConnection
|
||||
stream = connection
|
||||
try {
|
||||
connection.applyPinnedTls()
|
||||
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
// No read timeout, for the reason EventStream gives: between
|
||||
// notifications there is nothing to read, possibly for hours.
|
||||
connection.readTimeout = 0
|
||||
connection.setRequestProperty("Authorization", "Bearer ${settings.token}")
|
||||
connection.setRequestProperty("Accept", "text/event-stream")
|
||||
if (connection.responseCode != 200) {
|
||||
throw IOException("HTTP ${connection.responseCode} for the notification stream")
|
||||
}
|
||||
val reader = connection.inputStream.bufferedReader()
|
||||
val data = StringBuilder()
|
||||
while (!stopping) {
|
||||
val line = reader.readLine() ?: break
|
||||
when {
|
||||
line.isEmpty() -> {
|
||||
if (data.isNotEmpty()) show(parseNotification(data.toString()))
|
||||
data.clear()
|
||||
}
|
||||
line.startsWith("data:") -> data.append(line.removePrefix("data:").trim())
|
||||
else -> {} // comments (keep-alives) and ids: nothing to do
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
stream = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One notification per session, replacing that session's previous one.
|
||||
*
|
||||
* Keyed by session id rather than accumulating: two sessions wanting attention are two things
|
||||
* to know about, but one session that finished and then asked a question is one thing -- the
|
||||
* question. A stack of stale rows for the same conversation is how a notification drawer
|
||||
* becomes something to clear rather than read.
|
||||
*/
|
||||
private fun show(notification: SessionNotification) {
|
||||
// Nothing to tell somebody about the session they are reading. The transcript in front of
|
||||
// them is already saying it, and a sound over the top of it would be this app announcing
|
||||
// what the screen is showing.
|
||||
if (isOnScreen(notification.sessionId)) return
|
||||
// The app is up: it says this itself, as a banner over whatever screen they are on. See
|
||||
// [forTheScreen]. Never both -- one thing happened, and a drawer filling up behind an
|
||||
// app that already showed you each one is a drawer nobody reads.
|
||||
if (handOver(notification)) return
|
||||
val manager = NotificationManagerCompat.from(this)
|
||||
// Two different noes, and both are answers rather than faults: the runtime permission
|
||||
// refused, and notifications switched off for the app in Android's own settings. Neither
|
||||
// is reported anywhere -- the person said no, and saying it back to them through the
|
||||
// channel they closed is not available anyway.
|
||||
//
|
||||
// The permission only exists from Android 13. Asking an older version about it gets
|
||||
// "denied" for a name it does not know, which read as the person having said no -- so
|
||||
// every notification on Android 12 and below was silently dropped. Before 13 the
|
||||
// switch in Android's own settings, checked below, is the whole of the answer.
|
||||
val allowed =
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
if (!allowed || !manager.areNotificationsEnabled()) {
|
||||
return
|
||||
}
|
||||
val open =
|
||||
PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
sessionIntent(this, notification.sessionId),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val built =
|
||||
NotificationCompat.Builder(this, ALERT_CHANNEL)
|
||||
.setContentTitle(notification.title)
|
||||
.setContentText(attentionLine(notification.kind))
|
||||
.setSmallIcon(android.R.drawable.stat_notify_chat)
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.setWhen((notification.at * 1000).toLong())
|
||||
.setShowWhen(true)
|
||||
.build()
|
||||
manager.notify(notification.sessionId, ALERT_ID, built)
|
||||
}
|
||||
|
||||
/**
|
||||
* The type Android 14+ requires a foreground service to declare, and nothing before it.
|
||||
*
|
||||
* Named behind a version check rather than passed as a constant: the value is inlined at
|
||||
* compile time and would be handed to platforms that have no concept of it, which is exactly
|
||||
* the case lint's InlinedApi exists to catch. Zero is what ServiceCompat wants where types do
|
||||
* not apply.
|
||||
*/
|
||||
private fun foregroundType(): Int =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
private fun ongoingNotification(): Notification =
|
||||
NotificationCompat.Builder(this, ONGOING_CHANNEL)
|
||||
.setContentTitle("Watching for sessions that need you")
|
||||
.setSmallIcon(android.R.drawable.stat_notify_sync)
|
||||
.setOngoing(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_MIN)
|
||||
.build()
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Starts the service if there is a server to connect to, and stops it otherwise.
|
||||
*
|
||||
* Called on every launch rather than once: a service Android killed does not restart itself
|
||||
* if the process was replaced, and asking for one that is already running is free.
|
||||
*/
|
||||
fun sync(context: Context) {
|
||||
val intent = Intent(context, NotificationService::class.java)
|
||||
if (loadServerSettings(context) == null) {
|
||||
context.stopService(intent)
|
||||
return
|
||||
}
|
||||
createChannels(context)
|
||||
ContextCompat.startForegroundService(context, intent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Two channels, because they are two different things to be told.
|
||||
*
|
||||
* The alerts are what somebody turned this on for, so they get the default importance and
|
||||
* whatever sound and heads-up display the person has chosen for the app. The ongoing one is
|
||||
* the platform's tax for staying connected, so it takes the lowest importance that exists.
|
||||
* Both are created before the service starts, since posting to a channel that does not
|
||||
* exist is silently dropped.
|
||||
*/
|
||||
private fun createChannels(context: Context) {
|
||||
val manager = NotificationManagerCompat.from(context)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannelCompat.Builder(
|
||||
ALERT_CHANNEL,
|
||||
NotificationManagerCompat.IMPORTANCE_DEFAULT,
|
||||
)
|
||||
.setName("Sessions needing attention")
|
||||
.build()
|
||||
)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannelCompat.Builder(
|
||||
ONGOING_CHANNEL,
|
||||
NotificationManagerCompat.IMPORTANCE_MIN,
|
||||
)
|
||||
.setName("Staying connected")
|
||||
.build()
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The session somebody is looking at, or null when no screen is showing one.
|
||||
*
|
||||
* Process-wide state, which the rest of this app does without: Android constructs the
|
||||
* service and the composition draws the screen, so the two have no common owner a value
|
||||
* could be passed through. [showing] and [stoppedShowing] are the pair, both called from
|
||||
* the one composable that shows a session. Clearing names the session rather than setting
|
||||
* null outright, because moving from one session to another composes the new screen before
|
||||
* the old one's coroutine is cancelled -- an unconditional clear would then throw away the
|
||||
* new screen's claim and start notifying about what is on it.
|
||||
*/
|
||||
@Volatile private var onScreen: String? = null
|
||||
|
||||
private fun isOnScreen(sessionId: String) = onScreen == sessionId
|
||||
|
||||
/**
|
||||
* The way a notification reaches the app instead of Android's drawer.
|
||||
*
|
||||
* Whether there is an app to reach is the subscriber count rather than a flag of its own:
|
||||
* [SessionAlerts] collects this exactly while it is on screen, so there is nothing that
|
||||
* could be left saying the app is up after it has gone. `tryEmit` neither suspends nor
|
||||
* blocks the thread reading the stream, and the buffer is there so a handful of sessions
|
||||
* finishing together all land rather than the last one winning.
|
||||
*/
|
||||
private val toApp = MutableSharedFlow<SessionNotification>(extraBufferCapacity = 8)
|
||||
|
||||
/** Everything meant for the screen rather than the drawer; see [toApp]. */
|
||||
val forTheScreen: SharedFlow<SessionNotification> = toApp.asSharedFlow()
|
||||
|
||||
private fun handOver(notification: SessionNotification) =
|
||||
toApp.subscriptionCount.value > 0 && toApp.tryEmit(notification)
|
||||
|
||||
/** Somebody is looking at [sessionId]; nothing is posted about it until they stop. */
|
||||
fun showing(context: Context, sessionId: String) {
|
||||
onScreen = sessionId
|
||||
// Whatever was posted about it before is about to be read, so it has nothing left
|
||||
// to say -- and a row in the drawer for the conversation on screen is the same
|
||||
// duplication this whole rule is about.
|
||||
NotificationManagerCompat.from(context).cancel(sessionId, ALERT_ID)
|
||||
}
|
||||
|
||||
/** They have stopped, unless another screen has claimed it since. */
|
||||
fun stoppedShowing(sessionId: String) {
|
||||
if (onScreen == sessionId) onScreen = null
|
||||
}
|
||||
|
||||
private const val ALERT_CHANNEL = "sessions"
|
||||
private const val ONGOING_CHANNEL = "connection"
|
||||
private const val ONGOING_ID = 1
|
||||
/** Shared by every alert; the session id is the tag that separates them. */
|
||||
private const val ALERT_ID = 2
|
||||
private const val RECONNECT_DELAY_MS = 5_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The intent that opens one session, and the id it carries back out.
|
||||
*
|
||||
* The two halves are written together so neither can be changed without the other, and the scheme
|
||||
* is enrollment's `aiapp://` under a different host so that [MainActivity] has one thing to look at
|
||||
* when an intent arrives rather than two.
|
||||
*
|
||||
* The id rides in the intent's **data** rather than in an extra, which is not a style choice:
|
||||
* PendingIntent identity is `Intent.filterEquals`, and that compares the data while ignoring
|
||||
* extras. Carried as an extra, every session's notification would update one shared PendingIntent
|
||||
* and every tap would open whichever session was notified last.
|
||||
*/
|
||||
fun sessionIntent(context: Context, sessionId: String): Intent =
|
||||
Intent(context, MainActivity::class.java)
|
||||
.setAction(Intent.ACTION_VIEW)
|
||||
.setData(
|
||||
// Built rather than concatenated so an id needing escaping survives the round trip;
|
||||
// lastPathSegment below decodes what appendPath encoded.
|
||||
Uri.Builder().scheme("aiapp").authority("session").appendPath(sessionId).build()
|
||||
)
|
||||
|
||||
/** The session [sessionIntent] named, or null for any other URI -- enrollment's included. */
|
||||
fun notifiedSessionId(uri: Uri): String? =
|
||||
if (uri.scheme == "aiapp" && uri.host == "session") uri.lastPathSegment else null
|
||||
|
||||
/** One frame of `GET /notifications`. */
|
||||
data class SessionNotification(
|
||||
val sessionId: String,
|
||||
val title: String,
|
||||
/** The wire's word: "awaitingInput" or "finished". */
|
||||
val kind: String,
|
||||
val at: Double,
|
||||
)
|
||||
|
||||
/**
|
||||
* What a notification asks of the reader, in the words they see.
|
||||
*
|
||||
* What they have to do, not what the session did: "awaitingInput" is the wire's word and says
|
||||
* nothing to somebody reading a lock screen. One function because the same fact is now shown in two
|
||||
* places -- Android's drawer and the app's own banner -- and two mappings of one word drift. The
|
||||
* banner colours the line as well, which is its own decision and stays with the drawing.
|
||||
*/
|
||||
fun attentionLine(kind: String): String =
|
||||
when (kind) {
|
||||
"awaitingInput" -> "Waiting for you"
|
||||
else -> "Finished"
|
||||
}
|
||||
|
||||
fun parseNotification(json: String): SessionNotification {
|
||||
val body = JSONObject(json)
|
||||
return SessionNotification(
|
||||
sessionId = body.getString("sessionId"),
|
||||
title = body.getString("title"),
|
||||
kind = body.getString("kind"),
|
||||
at = body.optDouble("at", 0.0),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* A message another agent sent this session, closed until somebody asks.
|
||||
*
|
||||
* Closed by default, like a tool call and for the same reason: these are long, there can be several
|
||||
* in a row, and what a reader scanning the transcript needs from one is that it happened and who
|
||||
* sent it. The first line comes with the heading because a name alone does not say which message
|
||||
* this was.
|
||||
*
|
||||
* Drawn as its own kind rather than as the reader's own bubble. They did not say this, and a
|
||||
* transcript that puts it in their voice is making a claim about who asked for the work that
|
||||
* follows -- which is exactly the question a peer message is usually the answer to.
|
||||
*/
|
||||
@Composable
|
||||
fun PeerMessageRow(
|
||||
item: TranscriptItem.PeerNote,
|
||||
expanded: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
replies: ParsedReplies,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Card(modifier.fillMaxWidth().clickable(onClick = onToggle)) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Message from ${item.from}", style = MaterialTheme.typography.titleSmall)
|
||||
if (!expanded) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
item.text.lineSequence().firstOrNull { it.isNotBlank() }.orEmpty(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
// The head, not the tail: a message is identified by how it opens.
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (expanded) MarkdownText(item.text, replies, Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* What is about to be sent, directly above the box it will be sent from.
|
||||
*
|
||||
* The count on the "+" button was the whole of what said an image was attached, so the only way to
|
||||
* find out *which* image was to send it. A control belongs with the thing it acts on, and what
|
||||
* these are attached to is the message being typed -- which is why they sit here rather than
|
||||
* anywhere else on the screen.
|
||||
*
|
||||
* Scrolls sideways rather than wrapping or shrinking: the row keeps one thumbnail size whatever is
|
||||
* in it, so four attachments look like four of the same thing rather than four smaller ones.
|
||||
*/
|
||||
@Composable
|
||||
fun PendingAttachments(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
refs: List<String>,
|
||||
onRemove: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (refs.isEmpty()) return
|
||||
Row(
|
||||
modifier = modifier.horizontalScroll(rememberScrollState()).padding(bottom = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
refs.forEach { ref -> PendingThumbnail(settings, sessionId, ref) { onRemove(ref) } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One attachment, square, tap to take it back off.
|
||||
*
|
||||
* Removal is here because there is nowhere else it could be: an image picked by mistake could
|
||||
* otherwise only be dealt with by sending it. The whole thumbnail is the target rather than a
|
||||
* corner cross -- a cross small enough to sit on a 64dp square is smaller than a fingertip -- and
|
||||
* the label is what says so, since nothing about the picture does.
|
||||
*/
|
||||
@Composable
|
||||
private fun PendingThumbnail(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
ref: String,
|
||||
onRemove: () -> Unit,
|
||||
) {
|
||||
val (bitmap, failed) = rememberSessionBitmap(settings, sessionId, ref)
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
Box(
|
||||
Modifier.size(THUMBNAIL)
|
||||
.clip(shape)
|
||||
// An outline as well as a fill. Most of what gets attached here is a screenshot of a
|
||||
// dark app, and cropped to a square its middle is often near-black -- against this
|
||||
// background the tile then had no edge at all, and the only thing saying an image was
|
||||
// attached was the cross drawn on top of nothing.
|
||||
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, shape)
|
||||
// Behind the picture as well as under a missing one, so the tile is a tile before
|
||||
// anything has arrived to fill it.
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant)
|
||||
.clickable(onClick = onRemove)
|
||||
.semantics { contentDescription = "Attached image, tap to remove" },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
when (val image = bitmap) {
|
||||
// The two are told apart for the same reason the transcript's images are: one of them
|
||||
// is worth waiting for and the other never resolves.
|
||||
null ->
|
||||
Text(
|
||||
if (failed) "!" else "…",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
else ->
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.size(THUMBNAIL),
|
||||
)
|
||||
}
|
||||
// The whole square removes it, and this only says so. A cross small enough to sit in
|
||||
// the corner of a 64dp thumbnail is smaller than a fingertip, so making it the target
|
||||
// would be a control drawn at a size nobody can hit.
|
||||
//
|
||||
// The disc is sized here and the mark centred inside it, rather than the glyph being
|
||||
// aligned directly: a glyph's box is wider than the cross it draws, so aligning the box
|
||||
// to the corner hung the visible mark over the edge and put its backing somewhere the
|
||||
// eye reads as a second, misplaced square.
|
||||
Box(
|
||||
Modifier.align(Alignment.TopEnd)
|
||||
.padding(2.dp)
|
||||
.size(20.dp)
|
||||
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.75f), CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Glyph(CLOSE_GLYPH, colour = MaterialTheme.colorScheme.onSurface, size = 12.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val THUMBNAIL = 64.dp
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import com.example.wgapplink.PinnedTls
|
||||
import java.net.HttpURLConnection
|
||||
|
||||
// PINNED_CA_PEM is generated at build time from the CA on the machine doing
|
||||
// the build -- see the generatePinnedCert task in build.gradle.kts. It is
|
||||
// deliberately not a checked-in constant: the private key that signs against
|
||||
// it must never be anywhere this repo is, and an APK should pin whatever CA
|
||||
// the backend it was built for actually serves.
|
||||
//
|
||||
// The pinning itself lives in wg-app-link, since dev-updater needs exactly
|
||||
// the same thing. What stays here is the one product-specific fact -- which
|
||||
// certificate this app pins.
|
||||
private val pinned = PinnedTls(PINNED_CA_PEM)
|
||||
|
||||
/** Every request this app makes goes through this -- there is no unpinned path. */
|
||||
fun HttpURLConnection.applyPinnedTls() = pinned.applyTo(this)
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* Verbatim text, on the surface that says so: a command about to be run, what a tool printed.
|
||||
*
|
||||
* A composable rather than a modifier repeated at each site, because the inset is part of it --
|
||||
* monospace text drawn hard against the edge of a tinted block reads as a clipping fault, and three
|
||||
* copies of "clip, fill, pad" drift apart the first time one of them is adjusted.
|
||||
*
|
||||
* The colour is [rawSurface], which is also what a code block inside a reply is given; that is the
|
||||
* point of having one name for it. Markdown's blocks are painted by the renderer rather than by
|
||||
* this, since it draws its own, but they are the same colour on purpose.
|
||||
*/
|
||||
@Composable
|
||||
fun RawBlock(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||
Column(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
// Smaller than a card's radius, and deliberately: this sits *inside* one, and a
|
||||
// rounded rectangle drawn at the same radius as the rounded rectangle behind it reads
|
||||
// as a misprint rather than as nesting.
|
||||
.clip(MaterialTheme.shapes.extraSmall)
|
||||
.background(rawSurface)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import java.time.Duration
|
||||
import java.time.OffsetDateTime
|
||||
|
||||
// How long is left in a usage window. Shared by the session bar and the usage screen: the
|
||||
// arithmetic is the same in both and only the sentence around it differs, so everything here
|
||||
// returns the span or the state on its own and leaves the wording to the caller.
|
||||
|
||||
/** "1d 4h", "3h 12m", "12m" -- the span alone, with no leading or trailing words. */
|
||||
fun formatSpan(until: Duration): String =
|
||||
when {
|
||||
until.toHours() >= 24 -> "${until.toDays()}d ${until.toHours() % 24}h"
|
||||
until.toHours() > 0 -> "${until.toHours()}h ${until.toMinutes() % 60}m"
|
||||
else -> "${until.toMinutes()}m"
|
||||
}
|
||||
|
||||
/**
|
||||
* What is known about when a usage window ends.
|
||||
*
|
||||
* Three answers rather than a nullable duration, because two of them shared `null` and they are not
|
||||
* the same thing at all. A window the server sent no reset time for is one that is **not running**:
|
||||
* the five-hour window is anchored to the block it started in, so between sessions there is nothing
|
||||
* counting down and the API says so by omitting the field -- measured against a live response on
|
||||
* 2026-08-31, where the five-hour window's reset was exactly five hours after the moment work
|
||||
* resumed. A timestamp that did arrive and could not be read is the genuinely unknown case, and it
|
||||
* is the only one worth those words.
|
||||
*
|
||||
* Collapsing them put "reset time unknown" on the session bar for a machine behaving perfectly, on
|
||||
* the one row somebody reads before starting something big -- and the usage dialog, looking at the
|
||||
* same field, quietly drew nothing. Two rules for one missing value; this is the rule.
|
||||
*/
|
||||
sealed class WindowEnd {
|
||||
/** No reset time was sent, so nothing is running in this window. Not a failure to find out. */
|
||||
data object NotRunning : WindowEnd()
|
||||
|
||||
/** A timestamp arrived and could not be read. The one case that is actually unknown. */
|
||||
data object Unreadable : WindowEnd()
|
||||
|
||||
/** How long is left. Negative once the window is past, which each caller words for itself. */
|
||||
data class Ends(val until: Duration) : WindowEnd()
|
||||
}
|
||||
|
||||
/**
|
||||
* [resetsAt] as the server sent it -- absent, unreadable, or a moment -- against [now].
|
||||
*
|
||||
* [now] is a parameter rather than read here so a caller can drive it from state and have the
|
||||
* countdown recompute on its own schedule.
|
||||
*/
|
||||
fun windowEnd(resetsAt: String?, now: OffsetDateTime): WindowEnd {
|
||||
if (resetsAt == null) return WindowEnd.NotRunning
|
||||
return try {
|
||||
WindowEnd.Ends(Duration.between(now, OffsetDateTime.parse(resetsAt)))
|
||||
} catch (_: Exception) {
|
||||
WindowEnd.Unreadable
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.content.Context
|
||||
import androidx.core.content.edit
|
||||
|
||||
private const val ANCHORS = "session-scroll"
|
||||
|
||||
/**
|
||||
* Where a session's transcript was left, so reopening it lands where reading stopped.
|
||||
*
|
||||
* Named by a **sequence number** -- see [TranscriptRow.startSeq] -- rather than by an index or by
|
||||
* the row key the list draws with. An index means nothing across a reopen, since the transcript is
|
||||
* fetched newest-first and a session that has said anything since has renumbered every position.
|
||||
* The row key looks stable and is not: a tool row is named after its run, `joinPages` gives a run
|
||||
* the name of its newest half, and the newest half is whatever the newest page happened to start
|
||||
* with -- so an active session renames its tool runs every time it is reopened, and an anchor
|
||||
* naming one is never found. A seq is the server's own numbering, assigned once and never moved.
|
||||
*
|
||||
* [unit] is which unit of the row the viewport started at -- see [TranscriptUnit.ordinal] -- and
|
||||
* [offset] how far that unit was scrolled past the viewport's newest edge, in pixels. A seq alone
|
||||
* is not a place: a reply is one seq and can be forty blocks long, and a reader stopped halfway
|
||||
* down it is put back at that block, not at the reply.
|
||||
*/
|
||||
data class ScrollAnchor(val seq: Long, val offset: Int, val unit: Int = 0)
|
||||
|
||||
/**
|
||||
* On this device rather than on the backend, which is where this app otherwise keeps state so every
|
||||
* device sees it. Scroll position is the same exception a draft is: it is where the phone in
|
||||
* somebody's hand is pointed, and having one device jump because another was scrolled would be a
|
||||
* surprise rather than a convenience.
|
||||
*/
|
||||
fun loadScrollAnchor(context: Context, sessionId: String): ScrollAnchor? {
|
||||
val stored =
|
||||
context.getSharedPreferences(ANCHORS, Context.MODE_PRIVATE).getString(sessionId, null)
|
||||
?: return null
|
||||
val fields = stored.split(':')
|
||||
val seq = fields.getOrNull(0)?.toLongOrNull() ?: return null
|
||||
val offset = fields.getOrNull(1)?.toIntOrNull() ?: return null
|
||||
// Positions saved before the unit was recorded name the row's oldest unit, which is the
|
||||
// closest older place -- the same choice [unitIndexFor] makes when a unit is gone.
|
||||
return ScrollAnchor(seq, offset, fields.getOrNull(2)?.toIntOrNull() ?: 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Records where [sessionId] is being read, or forgets it when [anchor] is null.
|
||||
*
|
||||
* The path out is reading to the newest end, which is what the caller passes null for: a session
|
||||
* left at the bottom has nothing to restore and should open at the bottom, which is also the cheap
|
||||
* case. A session *deleted* while it held an anchor leaves its key behind, for the reason and at
|
||||
* the cost `Drafts.kt` describes.
|
||||
*/
|
||||
fun saveScrollAnchor(context: Context, sessionId: String, anchor: ScrollAnchor?) {
|
||||
context.getSharedPreferences(ANCHORS, Context.MODE_PRIVATE).edit {
|
||||
if (anchor == null) remove(sessionId)
|
||||
else putString(sessionId, "${anchor.seq}:${anchor.offset}:${anchor.unit}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import com.example.wgapplink.ServerStore
|
||||
|
||||
/**
|
||||
* Where the backend is and how to authenticate to it. Absent until the phone is enrolled -- by
|
||||
* scanning the server's terminal QR (an `aiapp://enroll` URI the camera app hands to MainActivity)
|
||||
* or by typing the fields into the settings screen.
|
||||
*/
|
||||
typealias ServerSettings = com.example.wgapplink.ServerSettings
|
||||
|
||||
/**
|
||||
* This app's enrollment, which is the whole of what is product-specific about it.
|
||||
*
|
||||
* Both values are load-bearing and neither may be changed casually. The scheme is what routes a
|
||||
* scanned QR here rather than to Dev Updater, and the key alias names the Android Keystore key the
|
||||
* token is already sealed under on every enrolled phone -- changing it would leave those phones
|
||||
* reading as not enrolled, with no error to explain why.
|
||||
*/
|
||||
private val store = ServerStore(scheme = "aiapp", keyAlias = "aiapp-token-key")
|
||||
|
||||
fun loadServerSettings(context: Context): ServerSettings? = store.load(context)
|
||||
|
||||
fun saveServerSettings(context: Context, settings: ServerSettings) = store.save(context, settings)
|
||||
|
||||
fun parseEnrollmentUri(uri: Uri): ServerSettings? = store.parseEnrollmentUri(uri)
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.SwipeToDismissBoxValue
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
|
||||
/**
|
||||
* A session wanting attention, said over the app rather than through Android's drawer.
|
||||
*
|
||||
* Two places can carry the same fact and only one of them is right at a time. A row in the shade is
|
||||
* for somebody looking at something else: it makes a sound, it waits however long it has to, and
|
||||
* acting on it means leaving whatever they were doing. Somebody with this app open needs none of
|
||||
* that -- they are already here, and what a tap on the notification would have done is what a tap
|
||||
* on this does. So while these are on screen the stream is delivered here instead, which is
|
||||
* arranged by the collection below and nothing else; see `NotificationService.forTheScreen`.
|
||||
*
|
||||
* A banner can go three ways, and each is somebody deciding something different: tapped, which
|
||||
* opens the session; pushed off either side; or left alone, in which case it goes by itself when
|
||||
* the bar across its foot runs out.
|
||||
*/
|
||||
@Composable
|
||||
fun SessionAlerts(onOpen: (SessionOpenRequest) -> Unit, modifier: Modifier = Modifier) {
|
||||
val queue = remember { mutableStateListOf<SessionAlert>() }
|
||||
// What tells two notifications about one session apart, and what a replaced banner gets a new
|
||||
// one of so its timer starts again rather than inheriting the remains of the last one's.
|
||||
var arrivals by remember { mutableIntStateOf(0) }
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
LaunchedEffect(lifecycleOwner) {
|
||||
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
||||
try {
|
||||
NotificationService.forTheScreen.collect { notification ->
|
||||
arrivals++
|
||||
val alert = SessionAlert(notification, arrivals)
|
||||
// One banner per session, replacing that session's own -- the same rule the
|
||||
// drawer follows, and for the same reason: a session that finished and then
|
||||
// asked a question is one thing to know about, the question. It keeps its
|
||||
// place in the queue rather than moving to the end, because the reader may
|
||||
// already be reaching for it.
|
||||
val already = queue.indexOfFirst {
|
||||
it.notification.sessionId == notification.sessionId
|
||||
}
|
||||
if (already >= 0) queue[already] = alert else queue.add(alert)
|
||||
}
|
||||
} finally {
|
||||
// Leaving the app hands the job back to the drawer, so nothing arriving while it
|
||||
// is away is lost. What would be lost is the truth of what is already up: these
|
||||
// say a session wants somebody *now*, and one still sitting here on a return
|
||||
// several minutes later is a claim nobody checked. Frozen, too -- Compose stops
|
||||
// the clock with the window, so the timer that was going to retire it has been
|
||||
// standing still the whole time.
|
||||
queue.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
// Oldest at the top, so a new one appears below the ones already being read instead of
|
||||
// shoving them down the screen mid-reach.
|
||||
Column(modifier.fillMaxWidth().padding(8.dp)) {
|
||||
queue.forEach { alert ->
|
||||
key(alert.arrival) {
|
||||
AlertBanner(
|
||||
alert = alert,
|
||||
onOpen = {
|
||||
queue.remove(alert)
|
||||
onOpen(SessionOpenRequest(alert.notification.sessionId, alert.arrival))
|
||||
},
|
||||
onGone = { queue.remove(alert) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One notification queued for the screen, with the arrival that tells it from its predecessor. */
|
||||
private data class SessionAlert(val notification: SessionNotification, val arrival: Int)
|
||||
|
||||
/**
|
||||
* One banner: what wants attention, and how long this has left to say so.
|
||||
*
|
||||
* The bar and the going away are one value rather than a bar beside a timer, because two of them
|
||||
* would be two accounts of the same countdown and only one can be the one that fires. What is drawn
|
||||
* is therefore the thing that decides, which is the only arrangement where a bar that has emptied
|
||||
* cannot be sitting under a banner that is still there.
|
||||
*/
|
||||
@Composable
|
||||
private fun AlertBanner(alert: SessionAlert, onOpen: () -> Unit, onGone: () -> Unit) {
|
||||
val swipe = rememberSwipeToDismissBoxState()
|
||||
val life = remember { Animatable(1f) }
|
||||
LaunchedEffect(Unit) {
|
||||
life.animateTo(0f, animationSpec = tween(ALERT_LIFE_MS, easing = LinearEasing))
|
||||
onGone()
|
||||
}
|
||||
// Settled is "still where it started"; anything else is a push that carried far enough for the
|
||||
// gesture to commit, which the platform decides rather than this screen.
|
||||
LaunchedEffect(swipe.currentValue) {
|
||||
if (swipe.currentValue != SwipeToDismissBoxValue.Settled) onGone()
|
||||
}
|
||||
SwipeToDismissBox(
|
||||
state = swipe,
|
||||
// Nothing behind it. Pushing one of these away means the same thing whichever way it went,
|
||||
// so a coloured ground with an icon would be drawing a distinction that isn't there.
|
||||
backgroundContent = {},
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
) {
|
||||
Card(
|
||||
onClick = onOpen,
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerHigh
|
||||
),
|
||||
// Outlined, because the step it needs to make is not one this palette can make with a
|
||||
// tint: the card under a banner on the session list is the same surface, so a banner
|
||||
// relying on colour alone reads as one more row that happens to be in the way. The
|
||||
// border is the one cue, and the elevation beside it is the platform's shadow rather
|
||||
// than a second tint -- Material draws no tonal overlay over a container stated here.
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 6.dp),
|
||||
) {
|
||||
Column(Modifier.padding(start = 12.dp, end = 12.dp, top = 12.dp, bottom = 10.dp)) {
|
||||
Text(
|
||||
alert.notification.title,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
// One line, cut at the tail: a session is identified by the start of its
|
||||
// name, and a banner that grew with the name would move the one below it.
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
attentionLine(alert.notification.kind),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
// The list's own colour for a session waiting on a person, so the banner and
|
||||
// the row behind it are saying one thing rather than two.
|
||||
color =
|
||||
if (alert.notification.kind == "awaitingInput") awaitingColor
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
LinearProgressIndicator(
|
||||
progress = { life.value },
|
||||
// Blue because it is reporting how much of something is left rather than passing
|
||||
// judgement on it -- the reason `progressColor` exists. Stated beside the track,
|
||||
// which is the card's own colour so that the spent part reads as empty rather
|
||||
// than as a second bar.
|
||||
color = progressColor,
|
||||
trackColor = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
drawStopIndicator = {},
|
||||
gapSize = 0.dp,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a banner stays if nobody touches it.
|
||||
*
|
||||
* Long enough to read a session name and a line, short enough that a stack of them clears itself
|
||||
* while somebody is still on the screen that produced them. The bar makes the number visible, so
|
||||
* this is a duration the reader can watch rather than one they have to learn.
|
||||
*/
|
||||
private const val ALERT_LIFE_MS = 6_000
|
||||
@@ -0,0 +1,191 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.isSpecified
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* One image from the session's files route: the bitmap once it arrives, and whether it never will.
|
||||
*
|
||||
* [failed] exists because the two empty states differ in kind -- still coming and never coming --
|
||||
* and a reader can act on the second; each caller supplies its own words for them.
|
||||
*/
|
||||
data class SessionBitmap(val bitmap: ImageBitmap?, val failed: Boolean)
|
||||
|
||||
/**
|
||||
* Fetches (authenticated, pinned) and decodes one transcript image, remembered per ref so scrolling
|
||||
* does not refetch.
|
||||
*
|
||||
* Shared by the transcript's images and the composer's pending attachments, because the fetch, the
|
||||
* decode and the two-state answer are one block of logic that had been written twice.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSessionBitmap(settings: ServerSettings, sessionId: String, ref: String): SessionBitmap {
|
||||
var state by remember(ref) { mutableStateOf(SessionBitmap(null, failed = false)) }
|
||||
LaunchedEffect(ref) {
|
||||
state =
|
||||
try {
|
||||
val bytes =
|
||||
withContext(Dispatchers.IO) { fetchSessionFile(settings, sessionId, ref) }
|
||||
val decoded = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
|
||||
SessionBitmap(decoded, failed = decoded == null)
|
||||
} catch (_: ApiException) {
|
||||
SessionBitmap(null, failed = true)
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
/**
|
||||
* An image in the transcript: a fixed-height thumbnail that opens full screen.
|
||||
*
|
||||
* The height is decided before the bytes arrive and never changes. An image row that grew when it
|
||||
* finished loading pushed everything below it, so a transcript being read scrolled itself while
|
||||
* somebody was looking at it -- and in a bottom-anchored list, images loading above the viewport
|
||||
* moved the text under the reader's eyes. Reserving the final height makes loading invisible, which
|
||||
* is what it should be.
|
||||
*
|
||||
* Four lines of body text, so a screenshot reads as an attachment beside the conversation rather
|
||||
* than as a page of its own. Full size is one tap away.
|
||||
*/
|
||||
@Composable
|
||||
fun SessionImage(settings: ServerSettings, sessionId: String, ref: String) {
|
||||
val (bitmap, failed) = rememberSessionBitmap(settings, sessionId, ref)
|
||||
var full by remember(ref) { mutableStateOf(false) }
|
||||
val height = thumbnailHeight()
|
||||
val heightPx = with(LocalDensity.current) { height.roundToPx() }
|
||||
Box(Modifier.fillMaxWidth().height(height), contentAlignment = Alignment.CenterStart) {
|
||||
when (val image = bitmap) {
|
||||
null ->
|
||||
Text(
|
||||
// Two states, not one: an image still arriving and an image that will never
|
||||
// arrive look nothing alike to a reader who can do something about the second.
|
||||
if (failed) "[image $ref unavailable]" else "[loading image…]",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
else ->
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = "Attached image, tap to view full screen",
|
||||
contentScale = ContentScale.Fit,
|
||||
filterQuality = enlargingFilter(image.height, heightPx),
|
||||
modifier = Modifier.fillMaxSize().clickable { full = true },
|
||||
alignment = Alignment.CenterStart,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (full) bitmap?.let { image -> ImageViewer(image) { full = false } }
|
||||
}
|
||||
|
||||
/**
|
||||
* Four lines of the body style the transcript is set in.
|
||||
*
|
||||
* Measured from the type rather than written as a dp, so it stays four lines when the text size
|
||||
* changes -- including when the reader has scaled fonts up, which is exactly when a hardcoded
|
||||
* height would be wrong.
|
||||
*/
|
||||
@Composable
|
||||
private fun thumbnailHeight(): Dp {
|
||||
val line = MaterialTheme.typography.bodyLarge.lineHeight
|
||||
val density = LocalDensity.current
|
||||
return remember(line, density) {
|
||||
with(density) { if (line.isSpecified) (line * 4).toDp() else 96.dp }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Nearest neighbour when the image is being enlarged, smooth when it is being shrunk.
|
||||
*
|
||||
* A small image blown up with interpolation turns into a blur that hides what it is -- the same
|
||||
* image with hard pixel edges stays readable. Shrinking wants the opposite, so this is a decision
|
||||
* per image rather than a preference set once.
|
||||
*/
|
||||
private fun enlargingFilter(sourceHeight: Int, drawnHeight: Int): FilterQuality =
|
||||
if (sourceHeight < drawnHeight) FilterQuality.None else FilterQuality.High
|
||||
|
||||
/**
|
||||
* The image on its own, as large as it fits, with pinch to zoom.
|
||||
*
|
||||
* A dialog rather than a screen, so the platform's back gesture returns to the transcript instead
|
||||
* of leaving the app. It opens fitted -- the whole image visible, which is the thing a reader wants
|
||||
* first -- and zoom is theirs from there.
|
||||
*/
|
||||
@Composable
|
||||
private fun ImageViewer(image: ImageBitmap, onClose: () -> Unit) {
|
||||
Dialog(
|
||||
onDismissRequest = onClose,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
var scale by remember { mutableFloatStateOf(1f) }
|
||||
var offsetX by remember { mutableFloatStateOf(0f) }
|
||||
var offsetY by remember { mutableFloatStateOf(0f) }
|
||||
Box(
|
||||
Modifier.fillMaxSize()
|
||||
.background(Color.Black)
|
||||
.clickable(onClick = onClose)
|
||||
.pointerInput(Unit) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
// Floor of 1 so the image cannot be pinched smaller than fitted, which is
|
||||
// already the whole of it; a ceiling so it cannot be lost off-screen.
|
||||
scale = (scale * zoom).coerceIn(1f, 8f)
|
||||
if (scale > 1f) {
|
||||
offsetX += pan.x
|
||||
offsetY += pan.y
|
||||
} else {
|
||||
offsetX = 0f
|
||||
offsetY = 0f
|
||||
}
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = "Attached image",
|
||||
contentScale = ContentScale.Fit,
|
||||
// Zoomed in, the reader is looking at pixels on purpose.
|
||||
filterQuality = FilterQuality.None,
|
||||
modifier =
|
||||
Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
translationX = offsetX
|
||||
translationY = offsetY
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* The sessions tab: sessions awaiting an answer sort to the top, which is the "your turn" inbox.
|
||||
*
|
||||
* No title and no Back of its own -- [MainScreen] owns the header and the tab that names this one.
|
||||
* What stays here is the button that adds a session, because that acts on this list and nothing
|
||||
* else.
|
||||
*/
|
||||
@Composable
|
||||
fun SessionListScreen(
|
||||
settings: ServerSettings,
|
||||
reloadToken: Int,
|
||||
onOpen: (SessionSummary) -> Unit,
|
||||
onSpawn: () -> Unit,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var listState by remember { mutableStateOf<LoadState<List<SessionSummary>>>(LoadState.Loading) }
|
||||
var confirmingDelete by remember { mutableStateOf<SessionSummary?>(null) }
|
||||
|
||||
// Failures that belong to one session rather than to the list, keyed by
|
||||
// its id and shown on its own card. The two scopes are decided by
|
||||
// whether the server answered: it answered and refused, so this says
|
||||
// nothing about the other rows, where a server that has stopped
|
||||
// answering leaves every row stale and is `listState`'s to report.
|
||||
//
|
||||
// Cleared on the next successful load below -- an entry outlives its
|
||||
// session otherwise, and would reappear against whatever the phone
|
||||
// fetched next.
|
||||
var deleteErrors by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
|
||||
// Which sessions have a delete in flight. A set of ids rather than a flag on the row,
|
||||
// because the rows are rebuilt from whatever the server last said and this belongs to the
|
||||
// request rather than to the session.
|
||||
var deleting by remember { mutableStateOf<Set<String>>(emptySet()) }
|
||||
|
||||
fun refresh() {
|
||||
listState = LoadState.Loading
|
||||
scope.launch {
|
||||
listState =
|
||||
try {
|
||||
val loaded =
|
||||
withContext(Dispatchers.IO) { LoadState.Loaded(fetchSessions(settings)) }
|
||||
deleteErrors = emptyMap()
|
||||
loaded
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(reloadToken) { refresh() }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
Column(Modifier.fillMaxSize().padding(16.dp)) {
|
||||
when (val state = listState) {
|
||||
is LoadState.Loading -> CircularProgressIndicator()
|
||||
// The message as Api.kt wrote it, with nothing added: it is
|
||||
// already a whole sentence naming the address and what to
|
||||
// check, so a prefix here read "Couldn't reach the server:
|
||||
// Couldn't reach the server at ...". It was also a guess --
|
||||
// a delete that the server itself refused had reached it
|
||||
// fine.
|
||||
is LoadState.Error ->
|
||||
Text(
|
||||
state.message,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
is LoadState.Loaded -> {
|
||||
if (state.value.isEmpty()) {
|
||||
Text(
|
||||
"No sessions. Tap + to spawn one.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
// Awaiting-answer first (the point of the screen), then
|
||||
// most recently active.
|
||||
val ordered =
|
||||
state.value.sortedWith(
|
||||
compareByDescending<SessionSummary> { it.status == "awaitingInput" }
|
||||
.thenByDescending { it.lastActivity }
|
||||
)
|
||||
LazyColumn {
|
||||
items(ordered, key = { it.id }) { session ->
|
||||
SessionCard(
|
||||
session = session,
|
||||
error = deleteErrors[session.id],
|
||||
deleting = session.id in deleting,
|
||||
onOpen = { onOpen(session) },
|
||||
onLongPress = { confirmingDelete = session },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FloatingActionButton(
|
||||
onClick = onSpawn,
|
||||
modifier = Modifier.align(Alignment.BottomEnd).padding(24.dp),
|
||||
) {
|
||||
Text("+", style = MaterialTheme.typography.headlineMedium)
|
||||
}
|
||||
}
|
||||
|
||||
confirmingDelete?.let { session ->
|
||||
// Reset per session, so a toggle turned on for one conversation is not still on for the
|
||||
// next one somebody opens this dialog for. Off to begin with: see [deleteSession].
|
||||
var alsoDeleteForeign by remember(session.id) { mutableStateOf(false) }
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmingDelete = null },
|
||||
title = { Text("Delete \"${session.title}\"?") },
|
||||
text = {
|
||||
// Two different acts behind one button, so it says which one this is. What
|
||||
// separates them is whether the *driver* keeps its own record of the
|
||||
// conversation -- the Claude Code CLI does, under ~/.claude/projects, whether
|
||||
// this app spawned the session or imported it; echo and llama.cpp do not, and
|
||||
// for those the app's transcript is the only copy there is.
|
||||
//
|
||||
// This used to branch on `imported`, above a comment asserting that "a session
|
||||
// started here has no copy anywhere". That was simply false for every
|
||||
// claude-cli session this app spawned, and the two warnings disagreed about
|
||||
// sessions that were equally recoverable. Getting it wrong in that direction
|
||||
// is the expensive one: "this can't be undone", said of something that can,
|
||||
// spends the credibility the sentence needs on the sessions where it is true.
|
||||
//
|
||||
// Neither branch promises a restore. The recoverable one says what is known --
|
||||
// the driver keeps its own record -- rather than that the file is still there,
|
||||
// which nothing here checked; and it names what goes either way, because this
|
||||
// app's transcript holds images, peer messages and commands that the CLI's own
|
||||
// record never had.
|
||||
Column {
|
||||
Text(
|
||||
when {
|
||||
!session.keepsOwnTranscript ->
|
||||
"Kills the process and deletes the conversation. Nothing else " +
|
||||
"keeps a copy, so this can't be undone."
|
||||
// The sentence below is the one the toggle makes false, which is why
|
||||
// it is written twice rather than appended to: leaving "should still
|
||||
// be there to import again" on screen beside a switch that removes it
|
||||
// is the reassurance being read at the moment it stops being true.
|
||||
alsoDeleteForeign ->
|
||||
"Kills the process and deletes both copies of the conversation: " +
|
||||
"this app's, and Claude Code's own transcript on the " +
|
||||
"machine. Nothing keeps another, so this can't be undone."
|
||||
else ->
|
||||
"Stops the process and deletes this app's copy of the " +
|
||||
"conversation, including any images, peer messages and " +
|
||||
"commands recorded only here. Claude Code keeps its own " +
|
||||
"transcript on the machine, so the conversation itself " +
|
||||
"should still be there to import again."
|
||||
}
|
||||
)
|
||||
// Only where there is a second copy to decide about. Absent rather than
|
||||
// disabled, because this is not a capability being withheld: for echo and
|
||||
// llama.cpp there is no other transcript, and a switch offering to delete
|
||||
// one would be asking about something that does not exist.
|
||||
if (session.keepsOwnTranscript) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
// Its own row rather than beside the paragraph: a switch is taller than
|
||||
// a line of text and re-centres whatever shares a row with it.
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"Delete Claude Code's transcript too",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Switch(
|
||||
checked = alsoDeleteForeign,
|
||||
onCheckedChange = { alsoDeleteForeign = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmingDelete = null
|
||||
// Marked here rather than after the request returns: the row has to say
|
||||
// something is happening to it from the moment it is asked for, which
|
||||
// is the whole of what this state is for.
|
||||
deleting = deleting + session.id
|
||||
deleteErrors = deleteErrors - session.id
|
||||
scope.launch {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
deleteSession(settings, session.id, alsoDeleteForeign)
|
||||
}
|
||||
// Only this row, and only what changed. Refetching the list
|
||||
// instead put every other session back through loading and
|
||||
// handed the reader an empty screen -- to report on something
|
||||
// that was never in doubt.
|
||||
val loaded = listState
|
||||
if (loaded is LoadState.Loaded) {
|
||||
listState =
|
||||
LoadState.Loaded(
|
||||
loaded.value.filterNot { it.id == session.id }
|
||||
)
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
// Kept, because it is still there: the server refused, so the
|
||||
// session it refused about is exactly as it was.
|
||||
deleteErrors =
|
||||
deleteErrors + (session.id to (e.message ?: "Delete failed"))
|
||||
} finally {
|
||||
deleting = deleting - session.id
|
||||
}
|
||||
}
|
||||
}
|
||||
) {
|
||||
// Coloured by consequence: this takes something away, and does so wherever
|
||||
// it appears -- the same rule the import screen's Delete follows.
|
||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmingDelete = null }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun SessionCard(
|
||||
session: SessionSummary,
|
||||
/** What went wrong acting on *this* session, if anything has. */
|
||||
error: String?,
|
||||
/**
|
||||
* Whether this session is being deleted right now.
|
||||
*
|
||||
* Suspended rather than removed while it is -- see [BusyItem] -- which says the row is on its
|
||||
* way out without claiming it has gone: a row removed the moment Delete is pressed is a promise
|
||||
* about a request that has not been answered yet, and putting it back when the server refuses
|
||||
* is worse than never having taken it away.
|
||||
*/
|
||||
deleting: Boolean,
|
||||
onOpen: () -> Unit,
|
||||
onLongPress: () -> Unit,
|
||||
) {
|
||||
BusyItem(label = if (deleting) "deleting" else null) {
|
||||
Card(
|
||||
// Off while the delete is in flight: a card that still opens a session it is
|
||||
// deleting is a race the reader can start by tapping. On the card rather than in
|
||||
// [BusyItem], which leaves gestures alone so the list still scrolls.
|
||||
Modifier.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
enabled = !deleting,
|
||||
onClick = onOpen,
|
||||
onLongClick = onLongPress,
|
||||
)
|
||||
) {
|
||||
Column(Modifier.padding(16.dp)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
session.title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
StatusText(session.status)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
// Machine, then what runs on it, then what it is set to: the same order
|
||||
// and separator as the session screen's header and the usage dialog, so
|
||||
// one pair of facts is not written three ways.
|
||||
listOfNotNull(
|
||||
session.setupName,
|
||||
session.provider,
|
||||
session.model?.let { modelLabel(it) },
|
||||
)
|
||||
.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
relativeTime(session.lastActivity),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
error?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// The server's own words, unprefixed, the way every other
|
||||
// failure in this app is shown.
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun StatusText(status: String) {
|
||||
val (label, color) =
|
||||
when (status) {
|
||||
"awaitingInput" -> "your turn" to awaitingColor
|
||||
"running" -> "running" to runningColor
|
||||
"compacting" -> "compacting" to commandColor
|
||||
"exited" -> "exited" to MaterialTheme.colorScheme.onSurfaceVariant
|
||||
// Said in words, because it differs in kind from the others rather than in degree:
|
||||
// the session is not idle and has not exited, nobody has been able to find out
|
||||
// which. A muted colour alone would read as one of the quiet states.
|
||||
"unknown" -> "can't tell" to MaterialTheme.colorScheme.onSurfaceVariant
|
||||
else -> status to MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (status == "running" || status == "compacting") {
|
||||
// The same colour as the word beside it: the two are one signal, and a spinner in
|
||||
// the theme's accent says the state is something other than what the label says.
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.width(14.dp).height(14.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = color,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
Text(label, style = MaterialTheme.typography.labelLarge, color = color)
|
||||
}
|
||||
}
|
||||
|
||||
fun relativeTime(epochSeconds: Double): String {
|
||||
val seconds = (System.currentTimeMillis() / 1000.0 - epochSeconds).toLong()
|
||||
return when {
|
||||
seconds < 60 -> "just now"
|
||||
seconds < 3600 -> "${seconds / 60}m ago"
|
||||
seconds < 86400 -> "${seconds / 3600}h ago"
|
||||
else -> "${seconds / 86400}d ago"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,189 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* What can be changed about one session, as opposed to about this app.
|
||||
*
|
||||
* Over the session rather than a step down from it: everything here is about the conversation
|
||||
* behind it, and a dialog keeps that conversation on screen while it is being adjusted. It was a
|
||||
* screen of its own until 2026-08-30, which put a page transition and a back stack around two
|
||||
* controls and hid the thing they act on.
|
||||
*
|
||||
* The model and the permission mode are deliberately still on the session's own bar, because those
|
||||
* are changed *while* reading a turn -- "not this model, try that one" -- and a control belongs
|
||||
* with the thing it acts on.
|
||||
*
|
||||
* Nothing here is captioned. Each control is a labelled noun with a switch or a field beside it,
|
||||
* and a paragraph under every one of them made the dialog longer than the conversation it covers.
|
||||
* Failures still get their words: those are what the reader cannot work out by looking.
|
||||
*/
|
||||
@Composable
|
||||
fun SessionSettingsDialog(
|
||||
settings: ServerSettings,
|
||||
sessionId: String,
|
||||
/**
|
||||
* What the session is called now, as the screen behind this knows it -- see the rename below.
|
||||
*/
|
||||
title: String,
|
||||
onRenamed: (String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var name by remember(sessionId) { mutableStateOf(title) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
// Null until the server has been asked. The row this dialog was opened over is a snapshot of
|
||||
// whenever the list was last fetched, so drawing the switch straight from it would show a
|
||||
// position that may have been changed since -- from here or from another device -- with
|
||||
// nothing to say so. Until the answer arrives the switch is disabled and a spinner sits beside
|
||||
// it, which is what not knowing looks like: distinguishable from off, and from a refusal.
|
||||
var notify by remember(sessionId) { mutableStateOf<Boolean?>(null) }
|
||||
var notifyError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
LaunchedEffect(sessionId) {
|
||||
notify =
|
||||
try {
|
||||
withContext(Dispatchers.IO) { fetchSession(settings, sessionId).notify }
|
||||
} catch (e: ApiException) {
|
||||
// Left unknown rather than falling back to the stale row: the switch stays
|
||||
// disabled, instead of offering a position nothing confirmed.
|
||||
notifyError = e.message
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
// Moved optimistically so the switch answers the finger that moved it, and put back if the
|
||||
// request is refused -- a switch that waits for a round trip reads as broken on a slow
|
||||
// tunnel, and one that stays moved after a refusal lies.
|
||||
fun setNotify(wanted: Boolean) {
|
||||
val was = notify
|
||||
notify = wanted
|
||||
notifyError = null
|
||||
scope.launch {
|
||||
try {
|
||||
withContext(Dispatchers.IO) { setSessionNotify(settings, sessionId, wanted) }
|
||||
} catch (e: ApiException) {
|
||||
notify = was
|
||||
notifyError = e.message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to do when the name has not changed, so the button says so rather than sending a
|
||||
// request whose success would look exactly like the failure of having typed nothing.
|
||||
val changed = name.trim().isNotEmpty() && name.trim() != title
|
||||
|
||||
fun save() {
|
||||
if (!changed || saving) return
|
||||
val chosen = name.trim()
|
||||
saving = true
|
||||
error = null
|
||||
scope.launch {
|
||||
try {
|
||||
withContext(Dispatchers.IO) { renameSession(settings, sessionId, chosen) }
|
||||
onRenamed(chosen)
|
||||
} catch (e: ApiException) {
|
||||
// Reported here, where it happened, because this dialog is the only place that
|
||||
// knows a rename was attempted -- the session behind it shows nothing about it.
|
||||
error = e.message
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Session settings") },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Name") },
|
||||
singleLine = true,
|
||||
enabled = !saving,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
// The keyboard's own action does what the button does: a one-field form
|
||||
// where the return key does nothing is a form people press return at anyway.
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { save() }),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Glyph(BELL_GLYPH, colour = MaterialTheme.colorScheme.onSurface)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Notifications", modifier = Modifier.weight(1f))
|
||||
if (notify == null && notifyError == null) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.width(16.dp).height(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Switch(
|
||||
checked = notify == true,
|
||||
onCheckedChange = { setNotify(it) },
|
||||
enabled = notify != null,
|
||||
)
|
||||
}
|
||||
// Beside the switch that failed, not with the rename's error: they are two
|
||||
// requests and a reader has to be able to tell which one the server refused.
|
||||
notifyError?.let {
|
||||
Text(
|
||||
it,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
error?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
it,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
// Disabled rather than absent while there is nothing to save: a button that comes and
|
||||
// goes makes its own presence the signal, and its absence cannot say why.
|
||||
confirmButton = {
|
||||
TextButton(onClick = { save() }, enabled = changed && !saving) {
|
||||
Text(if (saving) "Saving..." else "Save")
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Close") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import java.time.Duration
|
||||
import java.time.OffsetDateTime
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** What one machine's rate limits came back as, or why they didn't. */
|
||||
sealed class SessionUsage {
|
||||
/** Nothing has come back yet. Distinct from every answer, including an empty one. */
|
||||
data object Waiting : SessionUsage()
|
||||
|
||||
/** Every window the machine reported, in the order it reported them. */
|
||||
data class Known(val windows: List<UsageWindow>) : SessionUsage()
|
||||
|
||||
/**
|
||||
* This machine meters nothing, so there is no window to show.
|
||||
*
|
||||
* Separate from [Unavailable], and the distinction is the whole point: a session on `echo` or
|
||||
* on a local llama.cpp has no paid quota at all, which is a fact about how it was set up and
|
||||
* not a failure to find something out. The backend never asks such a machine, so it returns no
|
||||
* snapshot for it -- and reading that silence as "couldn't find out" is exactly the mistake of
|
||||
* answering with the nearest available word. Drawn as nothing, because there is nothing.
|
||||
*/
|
||||
data object NotMetered : SessionUsage()
|
||||
|
||||
/**
|
||||
* The question could not be answered, and why.
|
||||
*
|
||||
* Its own state because "we couldn't find out" and "none of it is used" are the pair that must
|
||||
* never share an appearance: a bar sitting at zero because a machine is unreachable reads as
|
||||
* plenty of headroom, which is the opposite of the truth.
|
||||
*/
|
||||
data class Unavailable(val why: String) : SessionUsage()
|
||||
}
|
||||
|
||||
/** How often to ask again. The backend caches, so this re-reads its cache rather than the API. */
|
||||
private const val REFRESH_MS = 60_000L
|
||||
|
||||
/**
|
||||
* One machine's rate limits, polled.
|
||||
*
|
||||
* Hoisted out of [SessionUsageBar] because two things on a session's screen show this same answer
|
||||
* -- the bar, and the colour of the button that opens the usage dialog. Fetching it twice would
|
||||
* cost two round trips to say one thing, and the two copies would disagree for up to a minute at a
|
||||
* time, which is the interface contradicting itself about a number somebody is deciding on.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSessionUsage(settings: ServerSettings, setup: String): SessionUsage {
|
||||
var usage by remember(setup) { mutableStateOf<SessionUsage>(SessionUsage.Waiting) }
|
||||
LaunchedEffect(setup) {
|
||||
while (true) {
|
||||
usage =
|
||||
try {
|
||||
usageFor(withContext(Dispatchers.IO) { fetchUsage(settings) }, setup)
|
||||
} catch (e: ApiException) {
|
||||
SessionUsage.Unavailable(e.message ?: "couldn't reach the backend")
|
||||
}
|
||||
delay(REFRESH_MS)
|
||||
}
|
||||
}
|
||||
return usage
|
||||
}
|
||||
|
||||
/**
|
||||
* The colour for a control that reports on [usage] as a whole: the worst window's.
|
||||
*
|
||||
* Worst rather than the five-hour one, because the button it colours opens *all* of them, and a
|
||||
* blue icon over a weekly quota at 97% would be the interface answering a question nobody asked.
|
||||
* Taken over however many windows came back rather than the three Claude sends today -- the backend
|
||||
* deliberately passes windows it does not recognise straight through, so a fourth one is a thing
|
||||
* that happens rather than a thing to notice later.
|
||||
*
|
||||
* Every state that is not a measurement takes the ordinary control colour instead. That is the
|
||||
* point where colour stops being able to help: blue is the low end of a scale here, so colouring an
|
||||
* unknown blue would say "measured, and fine" about a machine nobody could reach. The dialog behind
|
||||
* the button is where those say, in words, which one they are.
|
||||
*/
|
||||
@Composable
|
||||
fun usageGlyphColour(usage: SessionUsage): Color =
|
||||
when (usage) {
|
||||
is SessionUsage.Known ->
|
||||
usage.windows.maxOfOrNull { it.percent }?.let { quotaColor(it) }
|
||||
?: MaterialTheme.colorScheme.primary
|
||||
else -> MaterialTheme.colorScheme.primary
|
||||
}
|
||||
|
||||
/**
|
||||
* The five-hour window for the machine this session runs on, under the session's own header.
|
||||
*
|
||||
* Here rather than only in the usage dialog because it is the number that decides whether to keep
|
||||
* going, and it was a screen away from the place that decision gets made. It reports on this
|
||||
* session's machine alone -- the dialog is still where every machine is compared.
|
||||
*
|
||||
* What it shows is the paid service's own metering, fetched from the machine that holds the
|
||||
* account. It is never derived from what this app has watched go past: the transcript's token
|
||||
* counts are a different quantity, measured differently, and a bar shaped like a quota gauge built
|
||||
* out of them would be a guess wearing a measurement's clothes.
|
||||
*/
|
||||
@Composable
|
||||
fun SessionUsageBar(usage: SessionUsage, modifier: Modifier = Modifier) {
|
||||
DebugStats.count("usage bar recomposed")
|
||||
// The countdown moves even when the numbers do not, so it is driven by a clock of its own
|
||||
// rather than recomputed at draw time: a percentage that comes back unchanged is an equal
|
||||
// value, Compose skips the recomposition, and a "left" that only ticked when the quota
|
||||
// happened to move would sit at a stale figure for hours.
|
||||
var now by remember { mutableStateOf(OffsetDateTime.now()) }
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
delay(REFRESH_MS)
|
||||
now = OffsetDateTime.now()
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing at all for a machine that meters nothing: a row saying "unknown" there would
|
||||
// report a problem about a setup somebody chose, on every screen, forever.
|
||||
if (usage is SessionUsage.NotMetered) {
|
||||
return
|
||||
}
|
||||
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp),
|
||||
) {
|
||||
// Words, not a colour and not an empty bar: every one of these is a different kind of
|
||||
// answer from "this much is used", and only words carry a difference in kind.
|
||||
when (val state = usage) {
|
||||
SessionUsage.NotMetered -> Unit
|
||||
is SessionUsage.Unavailable -> UsageNote("5-hour usage unknown -- ${state.why}")
|
||||
SessionUsage.Waiting -> UsageNote("5-hour usage: checking")
|
||||
is SessionUsage.Known -> {
|
||||
val window = state.windows.firstOrNull { it.kind == "session" }
|
||||
if (window == null) {
|
||||
UsageNote("5-hour usage unknown -- no five-hour window reported")
|
||||
} else {
|
||||
LinearProgressIndicator(
|
||||
progress = { (window.percent / 100.0).toFloat().coerceIn(0f, 1f) },
|
||||
// The same step at the same percentages as the dialog's bars: this is the
|
||||
// same measurement, and a reader who learned the colour there has to be
|
||||
// able to read it here without checking which screen they are on.
|
||||
color = quotaColor(window.percent),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
fiveHourLabel(window, now),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Anything this row says instead of drawing a bar, so all of them look the same. */
|
||||
@Composable
|
||||
private fun UsageNote(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* "42% -- 2h 15m left": how much is gone, then how long what is left has to last.
|
||||
*
|
||||
* The percentage on its own does not answer the question it gets asked, which is whether to start
|
||||
* something now; 80% with twenty minutes to go and 80% with four hours to go are opposite answers.
|
||||
*
|
||||
* The window's end has two missing cases and they are worded differently on purpose; see
|
||||
* [WindowEnd]. A window that is not running gets the percentage and nothing else, because there is
|
||||
* no countdown to report and inventing one would be the same fault as inventing the number.
|
||||
*/
|
||||
private fun fiveHourLabel(window: UsageWindow, now: OffsetDateTime): String {
|
||||
val percent = "${window.percent.toInt()}%"
|
||||
return when (val end = windowEnd(window.resetsAt, now)) {
|
||||
// Between blocks the five-hour window has no reset time, and saying so is a fact about
|
||||
// nothing: there is no window to run out. The percentage is the whole answer.
|
||||
WindowEnd.NotRunning -> percent
|
||||
WindowEnd.Unreadable -> "$percent · reset time unreadable"
|
||||
is WindowEnd.Ends ->
|
||||
// Under a minute, including past the end: the number would round to "0m left", which
|
||||
// reads as a measurement rather than as the window having run out.
|
||||
if (end.until < Duration.ofMinutes(1)) "$percent · refresh soon"
|
||||
else "$percent · ${formatSpan(end.until)} left"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One machine's snapshot, out of every machine's.
|
||||
*
|
||||
* Every way of having *failed* to get numbers is [SessionUsage.Unavailable] with the reason in it:
|
||||
* a machine nobody logged into, one that could not be reached, a snapshot that came back empty.
|
||||
* None of them may look like zero, and none may look like [SessionUsage.NotMetered], which is the
|
||||
* machine having no quota rather than the question going unanswered.
|
||||
*/
|
||||
fun usageFor(snapshots: List<UsageSnapshot>, setup: String): SessionUsage {
|
||||
// No snapshot at all means the backend never asked, which it only does for a machine with
|
||||
// nothing metered on it. That is a different answer from having asked and failed.
|
||||
val mine = snapshots.firstOrNull { it.setup == setup } ?: return SessionUsage.NotMetered
|
||||
if (mine.state != "ok") {
|
||||
return SessionUsage.Unavailable(mine.detail ?: mine.state)
|
||||
}
|
||||
return SessionUsage.Known(mine.windows)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import com.example.wgapplink.EnrollmentScanActivity
|
||||
import com.google.zxing.client.android.Intents
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanIntentResult
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
|
||||
/**
|
||||
* Server address and token. The normal path is the "Scan QR code" button below, which decodes the
|
||||
* server's terminal QR itself; these fields are the fallback for typing the same three values by
|
||||
* hand. [onBack] is null on first run, when there is nothing to go back to.
|
||||
*/
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
existing: ServerSettings?,
|
||||
onSaved: (ServerSettings) -> Unit,
|
||||
onBack: (() -> Unit)?,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var host by remember { mutableStateOf(existing?.host ?: "10.66.0.1") }
|
||||
var port by remember { mutableStateOf((existing?.port ?: 8443).toString()) }
|
||||
// Never pre-filled from the stored token: this screen shouldn't be a
|
||||
// way to read the credential back off the device.
|
||||
var token by remember { mutableStateOf("") }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val scanLauncher =
|
||||
rememberLauncherForActivityResult(ScanContract()) { result: ScanIntentResult ->
|
||||
// Null contents means the user backed out of the scanner -- not an
|
||||
// error, so nothing to report.
|
||||
val contents = result.contents ?: return@rememberLauncherForActivityResult
|
||||
val settings = parseEnrollmentUri(contents.toUri())
|
||||
if (settings == null) {
|
||||
error = "Not a valid enrollment code"
|
||||
} else {
|
||||
saveServerSettings(context, settings)
|
||||
onSaved(settings)
|
||||
}
|
||||
}
|
||||
|
||||
val requestCamera =
|
||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
scanLauncher.launch(enrollmentScanOptions())
|
||||
} else {
|
||||
error =
|
||||
"Scanning needs the camera. Grant it in the system settings, " +
|
||||
"or type the host, port and token in below."
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(16.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
// Leading, where a back arrow points at what it returns to. Trailing it would put a
|
||||
// left-pointing arrow at the right edge, aimed across the title it sits beside.
|
||||
//
|
||||
// Absent rather than disabled on first run, which is the one place this app lets a
|
||||
// control come and go: there is no screen underneath yet, so a Back here would not be
|
||||
// a capability being withheld but a promise it could not keep.
|
||||
if (onBack != null) {
|
||||
GlyphButton(BACK_GLYPH, "Back", onBack)
|
||||
Spacer(Modifier.width(GLYPH_BUTTON_MARGIN))
|
||||
}
|
||||
Text(
|
||||
"Server",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"The easy way: run ai-server on the backend and scan the QR it prints. " +
|
||||
"Or type the same values here.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
// Hold the camera permission before the scanner starts.
|
||||
// Letting its activity ask on our behalf is what the
|
||||
// library does by default, and it opens the camera without
|
||||
// waiting for the answer: the first-ever scan comes up as
|
||||
// a live preview with "Sorry, the Android camera
|
||||
// encountered a problem" over it, and works on the second
|
||||
// try. Nothing is wrong with the camera, so nothing should
|
||||
// say there is.
|
||||
if (
|
||||
context.checkSelfPermission(Manifest.permission.CAMERA) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
scanLauncher.launch(enrollmentScanOptions())
|
||||
} else {
|
||||
requestCamera.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("Scan QR code")
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = host,
|
||||
onValueChange = { host = it },
|
||||
label = { Text("Host") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = port,
|
||||
onValueChange = { port = it },
|
||||
label = { Text("Port") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = token,
|
||||
onValueChange = { token = it },
|
||||
label = { Text(if (existing != null) "Token (unchanged if left blank)" else "Token") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
|
||||
error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
val portNumber = port.trim().toIntOrNull()
|
||||
val effectiveToken = token.trim().ifEmpty { existing?.token ?: "" }
|
||||
when {
|
||||
host.isBlank() -> error = "Host is required"
|
||||
portNumber == null || portNumber !in 1..65535 -> error = "Port must be 1-65535"
|
||||
effectiveToken.isEmpty() ->
|
||||
error = "Token is required -- scan the server's QR or paste it"
|
||||
else -> {
|
||||
val settings = ServerSettings(host.trim(), portNumber, effectiveToken)
|
||||
saveServerSettings(context, settings)
|
||||
onSaved(settings)
|
||||
}
|
||||
}
|
||||
}
|
||||
) {
|
||||
Text("Save")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How the enrollment QR is scanned, in one place because two callers reach it -- straight from the
|
||||
* button when the camera permission is already held, and from the permission result when it has
|
||||
* just been granted.
|
||||
*
|
||||
* MIXED_SCAN is the load-bearing part: ZXing otherwise looks only for a dark code on a light
|
||||
* ground, and ai-server's QR is block characters in the terminal's foreground colour, so on a
|
||||
* dark-themed terminal it comes out as a photographic negative the scanner silently never matches.
|
||||
* Which way round it renders is the terminal's business, not something this app should depend on.
|
||||
* The mixed decoder alternates normal and inverted frames, costing half the frame rate at each
|
||||
* polarity and nothing else.
|
||||
*/
|
||||
private fun enrollmentScanOptions(): ScanOptions =
|
||||
ScanOptions()
|
||||
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
.setCaptureActivity(EnrollmentScanActivity::class.java)
|
||||
// Follow the phone, not the library's landscape pin.
|
||||
.setOrientationLocked(false)
|
||||
.addExtra(Intents.Scan.SCAN_TYPE, Intents.Scan.MIXED_SCAN)
|
||||
@@ -0,0 +1,395 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* The machines this backend can run things on.
|
||||
*
|
||||
* Note what this screen cannot do: name a program. Providers are what the server found when it
|
||||
* asked the machine, so adding one is "here is how to reach it" and never "here is what to run" --
|
||||
* which is what keeps the enrolled token from being able to introduce commands.
|
||||
*/
|
||||
@Composable
|
||||
fun SetupsScreen(settings: ServerSettings, reloadToken: Int) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf<LoadState<List<Setup>>>(LoadState.Loading) }
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
var renaming by remember { mutableStateOf<Setup?>(null) }
|
||||
var confirmingDelete by remember { mutableStateOf<Setup?>(null) }
|
||||
var busy by remember { mutableStateOf<String?>(null) }
|
||||
var actionError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
suspend fun reload() {
|
||||
state =
|
||||
try {
|
||||
withContext(Dispatchers.IO) { LoadState.Loaded(fetchSetups(settings)) }
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(reloadToken) { reload() }
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(16.dp)) {
|
||||
// The heading and Back are the tab row's now; adding a machine is this tab's own work
|
||||
// and stays with the list it adds to.
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
TextButton(onClick = { adding = true }) { Text("Add machine") }
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
actionError?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
busy?.let {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(Modifier.height(16.dp).padding(end = 8.dp))
|
||||
Text(it, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
when (val current = state) {
|
||||
is LoadState.Loading -> CircularProgressIndicator()
|
||||
is LoadState.Error -> Text(current.message, color = MaterialTheme.colorScheme.error)
|
||||
is LoadState.Loaded ->
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(current.value, key = { it.id }) { setup ->
|
||||
SetupCard(
|
||||
setup = setup,
|
||||
onRename = { renaming = setup },
|
||||
onRediscover = {
|
||||
scope.launch {
|
||||
busy = "Asking ${setup.name} what it has…"
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
updateSetup(
|
||||
settings,
|
||||
setup.id,
|
||||
rediscover = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
busy = null
|
||||
reload()
|
||||
}
|
||||
},
|
||||
onDelete = { confirmingDelete = setup },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (adding) {
|
||||
AddSetupDialog(
|
||||
onDismiss = { adding = false },
|
||||
onAdd = { name, ssh ->
|
||||
adding = false
|
||||
scope.launch {
|
||||
busy = "Asking $name what it has…"
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) { addSetup(settings, name, ssh) }
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
busy = null
|
||||
reload()
|
||||
}
|
||||
},
|
||||
onTest = { ssh -> withContext(Dispatchers.IO) { probeSetup(settings, ssh) } },
|
||||
)
|
||||
}
|
||||
|
||||
renaming?.let { setup ->
|
||||
RenameDialog(
|
||||
setup = setup,
|
||||
onDismiss = { renaming = null },
|
||||
onRename = { name ->
|
||||
renaming = null
|
||||
scope.launch {
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
updateSetup(settings, setup.id, name = name)
|
||||
}
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
reload()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
confirmingDelete?.let { setup ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmingDelete = null },
|
||||
title = { Text("Remove \"${setup.name}\"?") },
|
||||
text = {
|
||||
Text(
|
||||
"The machine is left alone -- this only stops this app offering it. " +
|
||||
"Sessions still running on it must be deleted first."
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmingDelete = null
|
||||
scope.launch {
|
||||
actionError =
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) { deleteSetup(settings, setup.id) }
|
||||
}
|
||||
.exceptionOrNull()
|
||||
?.message
|
||||
reload()
|
||||
}
|
||||
}
|
||||
) {
|
||||
Text("Remove")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmingDelete = null }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SetupCard(
|
||||
setup: Setup,
|
||||
onRename: () -> Unit,
|
||||
onRediscover: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
) {
|
||||
Card(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text(setup.name, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
// Not "this machine": the seeded setup is *called* that,
|
||||
// and the card read "this machine / this machine". The
|
||||
// line has to say something the name cannot also be.
|
||||
setup.address ?: "runs where the backend does",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
if (setup.providers.isEmpty()) {
|
||||
"Nothing found on it. Install something and rediscover."
|
||||
} else {
|
||||
setup.providers.joinToString(" · ") { it.name }
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = onRename) { Text("Rename") }
|
||||
TextButton(onClick = onRediscover) { Text("Rediscover") }
|
||||
Spacer(Modifier.weight(1f))
|
||||
TextButton(onClick = onDelete) { Text("Remove") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddSetupDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onAdd: (String, SshDetails?) -> Unit,
|
||||
onTest: suspend (SshDetails?) -> List<Provider>,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var name by remember { mutableStateOf("") }
|
||||
var address by remember { mutableStateOf("") }
|
||||
var identity by remember { mutableStateOf("") }
|
||||
var tested by remember { mutableStateOf<String?>(null) }
|
||||
var testing by remember { mutableStateOf(false) }
|
||||
|
||||
fun details(): SshDetails? =
|
||||
address
|
||||
.trim()
|
||||
.takeIf { it.isNotEmpty() }
|
||||
?.let { typed ->
|
||||
val (host, typedPort) = splitHostAndPort(typed)
|
||||
SshDetails(
|
||||
address = host,
|
||||
port = typedPort,
|
||||
identityFile = identity.trim().ifEmpty { null },
|
||||
)
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Add a machine") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"Leave the address blank for the machine the backend runs on. " +
|
||||
"What it can run is discovered, not typed.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Name") },
|
||||
singleLine = true,
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = address,
|
||||
onValueChange = { address = it },
|
||||
// Just the shape. What a blank one means is said once, in the text above
|
||||
// this form -- repeating it here wrapped the label onto a second line and
|
||||
// made this field taller than the two beside it for no information.
|
||||
label = { Text("user@host[:port]") },
|
||||
singleLine = true,
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = identity,
|
||||
onValueChange = { identity = it },
|
||||
label = { Text("Key path on the backend") },
|
||||
singleLine = true,
|
||||
)
|
||||
tested?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(it, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = name.isNotBlank(), onClick = { onAdd(name.trim(), details()) }) {
|
||||
Text("Add")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
Row {
|
||||
// Tried before saving, so a wrong address or an
|
||||
// unauthorised key is caught while this form is still on
|
||||
// screen rather than at the first spawn.
|
||||
TextButton(
|
||||
enabled = !testing,
|
||||
onClick = {
|
||||
testing = true
|
||||
tested = "Asking…"
|
||||
scope.launch {
|
||||
tested =
|
||||
runCatching { onTest(details()) }
|
||||
.fold(
|
||||
onSuccess = { found ->
|
||||
if (found.isEmpty()) {
|
||||
"Reached it, but found nothing it can run."
|
||||
} else {
|
||||
"Found ${found.joinToString(", ") { it.name }}"
|
||||
}
|
||||
},
|
||||
onFailure = { it.message ?: "Couldn't reach it" },
|
||||
)
|
||||
testing = false
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text("Test")
|
||||
}
|
||||
TextButton(onClick = onDismiss) { Text("Cancel") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RenameDialog(setup: Setup, onDismiss: () -> Unit, onRename: (String) -> Unit) {
|
||||
var name by remember { mutableStateOf(setup.name) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Rename") },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Name") },
|
||||
singleLine = true,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"Sessions already running on it keep working -- they refer to the machine, " +
|
||||
"not to what it is called.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = name.isNotBlank(), onClick = { onRename(name.trim()) }) {
|
||||
Text("Rename")
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits `user@host:port` into its two halves, with the port left null when none was typed.
|
||||
*
|
||||
* One field rather than two because that is how an address is written and read everywhere else --
|
||||
* and because a port that is almost always 22 does not deserve a box of its own on a phone
|
||||
* keyboard. Null rather than 22: the backend already decides the default, and writing 22 here would
|
||||
* put a second answer to that question in a second place.
|
||||
*
|
||||
* A colon only means "port" when it can. A bracketed IPv6 literal is unwrapped as ssh writes it,
|
||||
* `[::1]:22`; a bare `::1` keeps every colon, because an address with several is an address, not an
|
||||
* address and a port. So the rule is: brackets, or exactly one colon followed by digits.
|
||||
*/
|
||||
private fun splitHostAndPort(typed: String): Pair<String, Int?> {
|
||||
if (typed.startsWith("[")) {
|
||||
val close = typed.indexOf(']')
|
||||
if (close > 0) {
|
||||
val host = typed.substring(1, close)
|
||||
val rest = typed.substring(close + 1)
|
||||
val port = rest.removePrefix(":").toIntOrNull().takeIf { rest.startsWith(":") }
|
||||
return host to port
|
||||
}
|
||||
}
|
||||
if (typed.count { it == ':' } == 1) {
|
||||
val host = typed.substringBeforeLast(':')
|
||||
val port = typed.substringAfterLast(':').toIntOrNull()
|
||||
if (port != null && host.isNotEmpty()) return host to port
|
||||
}
|
||||
return typed to null
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* The spawn screen: what to run, where to run it, and the per-kind fields.
|
||||
*
|
||||
* Providers and hosts both come from the server, so adding either to its config.ron shows up here
|
||||
* with no app rebuild -- and because they are independent, any provider can be sent to any host.
|
||||
*/
|
||||
@Composable
|
||||
fun SpawnScreen(
|
||||
settings: ServerSettings,
|
||||
onSpawned: (SessionSummary) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
// What the form is made of, and whether we have it yet. A failure here
|
||||
// is not the same as a server with nothing to offer, so it must not
|
||||
// reach the pickers as empty lists -- see LoadState.
|
||||
var options by remember { mutableStateOf<LoadState<List<Setup>>>(LoadState.Loading) }
|
||||
|
||||
// Setup first, then one of its providers. Choosing a setup can
|
||||
// invalidate the provider, so the provider is stored by name and
|
||||
// resolved against the current setup rather than held as an object
|
||||
// that could outlive the list it came from.
|
||||
var setupName by remember { mutableStateOf<String?>(null) }
|
||||
var providerName by remember { mutableStateOf<String?>(null) }
|
||||
var title by remember { mutableStateOf("") }
|
||||
var model by remember { mutableStateOf("") }
|
||||
var cwd by remember { mutableStateOf("") }
|
||||
// "auto" rather than "manual": on a phone every ask is a round trip to
|
||||
// a question card, and answering "allow Bash?" dozens of times per task
|
||||
// is what this app exists to avoid. Manual stays one tap away for a
|
||||
// session that warrants it.
|
||||
var permissionMode by remember { mutableStateOf("auto") }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
// Only the spawn's own failure. The fetch's lives in `options`: this
|
||||
// one leaves a filled-in form worth keeping, and that one leaves
|
||||
// nothing to fill in.
|
||||
var spawnError by remember { mutableStateOf<String?>(null) }
|
||||
// Downloaded models, for a llama provider to choose between. Fetched
|
||||
// beside the setups but kept separate: a Claude session needs none, so
|
||||
// failing to list them must not stop the screen rendering.
|
||||
var models by remember { mutableStateOf<List<LocalModel>>(emptyList()) }
|
||||
var modelKey by remember { mutableStateOf<String?>(null) }
|
||||
var contextSize by remember { mutableStateOf("") }
|
||||
var temperature by remember { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
options =
|
||||
try {
|
||||
val fetched = withContext(Dispatchers.IO) { fetchSetups(settings) }
|
||||
val first = fetched.firstOrNull()
|
||||
setupName = first?.name
|
||||
providerName = first?.providers?.firstOrNull()?.name
|
||||
LoadState.Loaded(fetched)
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
models =
|
||||
runCatching { withContext(Dispatchers.IO) { fetchModels(settings).local } }
|
||||
.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"New session",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onBack) { Text("Cancel") }
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
// Nothing below is fillable until the options are here, and a
|
||||
// failure to fetch them leaves no form worth showing -- so this
|
||||
// reports and stops, rather than offering empty pickers under an
|
||||
// error message.
|
||||
val setups =
|
||||
when (val state = options) {
|
||||
is LoadState.Loading -> {
|
||||
CircularProgressIndicator()
|
||||
return@Column
|
||||
}
|
||||
is LoadState.Error -> {
|
||||
Text(state.message, color = MaterialTheme.colorScheme.error)
|
||||
return@Column
|
||||
}
|
||||
is LoadState.Loaded -> state.value
|
||||
}
|
||||
val setup = setups.firstOrNull { it.name == setupName }
|
||||
val current = setup?.providers?.firstOrNull { it.name == providerName }
|
||||
// Only the Claude CLI has models, a working directory and
|
||||
// permission modes; keying the extra fields on the kind rather
|
||||
// than the provider name keeps a second Claude provider from
|
||||
// needing anything here.
|
||||
val isClaude = current?.kind == "claude_cli"
|
||||
val isLlama = current?.kind == "llama_cpp"
|
||||
|
||||
// The machine first, because it decides what can be run at all.
|
||||
ChipGroup(
|
||||
label = "Setup",
|
||||
options = setups.map { it.name },
|
||||
selected = setupName,
|
||||
onSelect = { name ->
|
||||
setupName = name
|
||||
// The provider list changes with the machine, so a name
|
||||
// carried over from the previous one would be a selection
|
||||
// that isn't in the picker. Take that machine's first.
|
||||
providerName =
|
||||
setups.firstOrNull { it.name == name }?.providers?.firstOrNull()?.name
|
||||
},
|
||||
)
|
||||
setup?.address?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
// The address belongs to the setup above it, not to the
|
||||
// provider label below; without this they read as one block.
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
// Only what this machine actually has. A setup with none says so
|
||||
// rather than showing an empty row that reads as a failure.
|
||||
if (setup != null && setup.providers.isEmpty()) {
|
||||
Text(
|
||||
"\"${setup.name}\" has no providers configured.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
ChipGroup(
|
||||
label = "Provider",
|
||||
options = setup?.providers?.map { it.name }.orEmpty(),
|
||||
selected = providerName,
|
||||
onSelect = { providerName = it },
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = title,
|
||||
onValueChange = { title = it },
|
||||
label = { Text("Title") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
if (isLlama) {
|
||||
// A llama session names one of the models this backend has
|
||||
// downloaded, so the choice is that list rather than free
|
||||
// text -- there is nothing sensible to type here, and a name
|
||||
// that is not on disk is a session that cannot start.
|
||||
if (models.isEmpty()) {
|
||||
Text(
|
||||
"No models downloaded yet. Get one from the Models screen first.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
ChipGroup(
|
||||
label = "Model",
|
||||
// The file, not the whole key: the repository is the
|
||||
// same for every quantisation of a model, so the file
|
||||
// name is what tells two of them apart.
|
||||
options = models.map { it.file },
|
||||
selected = models.firstOrNull { it.key == modelKey }?.file,
|
||||
onSelect = { file -> modelKey = models.first { it.file == file }.key },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = contextSize,
|
||||
onValueChange = { contextSize = it },
|
||||
label = { Text("Context size (blank = the model's default)") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = temperature,
|
||||
onValueChange = { temperature = it },
|
||||
label = { Text("Temperature (blank = llama.cpp's default)") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
if (isClaude) {
|
||||
if (current.models.isNotEmpty()) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
ChipGroup(
|
||||
label = "Model",
|
||||
options = current.models,
|
||||
selected = model.ifEmpty { null },
|
||||
onSelect = { chosen -> model = if (model == chosen) "" else chosen },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = model,
|
||||
onValueChange = { model = it },
|
||||
label = { Text("Model (blank = the CLI's default)") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = cwd,
|
||||
onValueChange = { cwd = it },
|
||||
label = { Text("Working directory") },
|
||||
placeholder = { Text("/home/…") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
ChipGroup(
|
||||
label = "Permissions",
|
||||
options = PERMISSION_MODES,
|
||||
selected = permissionMode,
|
||||
onSelect = { permissionMode = it },
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
|
||||
// Beside the button that produced it.
|
||||
spawnError?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
val chosen = current ?: return@Button
|
||||
busy = true
|
||||
scope.launch {
|
||||
try {
|
||||
val spawned =
|
||||
withContext(Dispatchers.IO) {
|
||||
spawnSession(
|
||||
settings,
|
||||
// The id, not the label: labels are
|
||||
// editable and the server resolves by
|
||||
// id.
|
||||
// Non-null here: `chosen` came from
|
||||
// `setup`'s own provider list, so
|
||||
// reaching this point proves there was
|
||||
// a setup to take it from.
|
||||
setup = setup.id,
|
||||
provider = chosen.name,
|
||||
title = title.trim(),
|
||||
model =
|
||||
if (isLlama) modelKey else model.trim().takeIf { isClaude },
|
||||
cwd = cwd.trim().takeIf { isClaude },
|
||||
permissionMode = permissionMode.takeIf { isClaude },
|
||||
// Sent only when set, so blank means
|
||||
// "whatever llama.cpp does by default"
|
||||
// rather than a zero.
|
||||
params =
|
||||
buildMap {
|
||||
if (isLlama) {
|
||||
contextSize
|
||||
.trim()
|
||||
.takeIf { it.isNotEmpty() }
|
||||
?.let { put("contextSize", it) }
|
||||
temperature
|
||||
.trim()
|
||||
.takeIf { it.isNotEmpty() }
|
||||
?.let { put("temperature", it) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
onSpawned(spawned)
|
||||
} catch (e: ApiException) {
|
||||
spawnError = e.message
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = !busy && current != null && !(isLlama && modelKey == null),
|
||||
) {
|
||||
Text(if (busy) "Spawning..." else "Spawn")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A labeled row of choices that wraps onto as many lines as it needs.
|
||||
*
|
||||
* FlowRow rather than Row: a plain Row gives every chip an equal share of a single line, so once
|
||||
* the options don't fit, the text inside each one wraps to one character per line instead of the
|
||||
* row wrapping.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun ChipGroup(
|
||||
label: String,
|
||||
options: List<String>,
|
||||
selected: String?,
|
||||
onSelect: (String) -> Unit,
|
||||
) {
|
||||
Text(label, style = MaterialTheme.typography.labelLarge)
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
options.forEach { option ->
|
||||
FilterChip(
|
||||
selected = selected == option,
|
||||
onClick = { onSelect(option) },
|
||||
label = { Text(option) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.material3.ButtonColors
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import dev.snipme.highlights.model.SyntaxTheme
|
||||
|
||||
/**
|
||||
* Catppuccin Mocha, as published in `catppuccin/palette`.
|
||||
*
|
||||
* Named rather than used as literals at the point of need, so the mapping below reads as the
|
||||
* decision it is -- "a card is Surface 0" -- and so a value can be checked against the upstream
|
||||
* palette without reading the layout that uses it.
|
||||
*/
|
||||
private object Mocha {
|
||||
val Rosewater = Color(0xFFF5E0DC)
|
||||
val Mauve = Color(0xFFCBA6F7)
|
||||
val Red = Color(0xFFF38BA8)
|
||||
val Peach = Color(0xFFFAB387)
|
||||
val Yellow = Color(0xFFF9E2AF)
|
||||
val Green = Color(0xFFA6E3A1)
|
||||
val Teal = Color(0xFF94E2D5)
|
||||
val Sky = Color(0xFF89DCEB)
|
||||
val Blue = Color(0xFF89B4FA)
|
||||
val Lavender = Color(0xFFB4BEFE)
|
||||
val Text = Color(0xFFCDD6F4)
|
||||
val Subtext0 = Color(0xFFA6ADC8)
|
||||
val Overlay0 = Color(0xFF6C7086)
|
||||
val Surface2 = Color(0xFF585B70)
|
||||
val Surface1 = Color(0xFF45475A)
|
||||
val Surface0 = Color(0xFF313244)
|
||||
val Base = Color(0xFF1E1E2E)
|
||||
val Mantle = Color(0xFF181825)
|
||||
val Crust = Color(0xFF11111B)
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's colour scheme: Catppuccin Mocha mapped onto Material's roles.
|
||||
*
|
||||
* Copied from dev-updater rather than shared, which is a deliberate line: wg-app-link is the *link*
|
||||
* -- the tunnel, the pinned CA, enrollment -- and a palette is not that. The two apps looking alike
|
||||
* is a preference, not a contract, and the moment one wants a different accent the shared version
|
||||
* becomes a thing to fight rather than a thing to use.
|
||||
*
|
||||
* The mapping that matters is the surface ladder. Mocha names its darks in order -- Crust, Mantle,
|
||||
* Base, Surface 0, Surface 1 -- and Material asks for the same thing under different names, so the
|
||||
* page is Base, a component's outlined card stays Base beside it, and a project's card is Surface
|
||||
* 0: one visible step up, which is the whole of what the nesting has to say.
|
||||
*
|
||||
* Accents on this palette are light, so anything filled with one takes Crust for its text rather
|
||||
* than the near-white the roles default to.
|
||||
*/
|
||||
val AiAppColors =
|
||||
darkColorScheme(
|
||||
primary = Mocha.Mauve,
|
||||
onPrimary = Mocha.Crust,
|
||||
primaryContainer = Mocha.Surface1,
|
||||
onPrimaryContainer = Mocha.Mauve,
|
||||
secondary = Mocha.Lavender,
|
||||
onSecondary = Mocha.Crust,
|
||||
secondaryContainer = Mocha.Surface1,
|
||||
onSecondaryContainer = Mocha.Lavender,
|
||||
tertiary = Mocha.Rosewater,
|
||||
onTertiary = Mocha.Crust,
|
||||
background = Mocha.Base,
|
||||
onBackground = Mocha.Text,
|
||||
surface = Mocha.Base,
|
||||
onSurface = Mocha.Text,
|
||||
surfaceVariant = Mocha.Surface0,
|
||||
onSurfaceVariant = Mocha.Subtext0,
|
||||
surfaceContainerLowest = Mocha.Crust,
|
||||
surfaceContainerLow = Mocha.Mantle,
|
||||
surfaceContainer = Mocha.Base,
|
||||
surfaceContainerHigh = Mocha.Surface0,
|
||||
surfaceContainerHighest = Mocha.Surface0,
|
||||
inverseSurface = Mocha.Text,
|
||||
inverseOnSurface = Mocha.Base,
|
||||
inversePrimary = Mocha.Mauve,
|
||||
outline = Mocha.Overlay0,
|
||||
outlineVariant = Mocha.Surface2,
|
||||
error = Mocha.Red,
|
||||
onError = Mocha.Crust,
|
||||
errorContainer = Mocha.Surface1,
|
||||
onErrorContainer = Mocha.Red,
|
||||
scrim = Mocha.Crust,
|
||||
)
|
||||
|
||||
/**
|
||||
* What a session is doing, said in colour.
|
||||
*
|
||||
* Here rather than beside each screen that shows a status. These were separate literals in two
|
||||
* other files -- an amber, a green and a red picked off Material's defaults -- so the same state
|
||||
* was a slightly different colour depending which screen you looked at, and none of them belonged
|
||||
* to this palette at all. A colour that carries meaning is part of the scheme, not a value typed
|
||||
* where it happened to be needed.
|
||||
*/
|
||||
val runningColor: Color
|
||||
@Composable get() = Mocha.Green
|
||||
|
||||
/**
|
||||
* "This went wrong on its own": a session that fell over.
|
||||
*
|
||||
* The scheme's error colour, and deliberately not "the same red as a destructive button" even
|
||||
* though it is the same red. They are the same red for different reasons, and a state is not an
|
||||
* action -- nothing here is a button.
|
||||
*/
|
||||
val failedColor: Color
|
||||
@Composable get() = MaterialTheme.colorScheme.error
|
||||
|
||||
/**
|
||||
* About the session rather than about the task: a command, and the compaction one of them starts.
|
||||
*
|
||||
* Its own colour because it is its own kind of work. Everything else a session does is progress
|
||||
* through what was asked of it; this is the session acting on itself -- rewriting what it
|
||||
* remembers, taking a new name -- and none of it appears in the transcript as an answer to
|
||||
* anything. A reader who has learned that blue means "not stuck, but not replying to you either"
|
||||
* has learned the thing that distinguishes it from a session that has hung.
|
||||
*/
|
||||
val commandColor: Color
|
||||
@Composable get() = Mocha.Blue
|
||||
|
||||
/**
|
||||
* A clear: the conversation taken out of what the session is given.
|
||||
*
|
||||
* Red because of what it does, not because anything went wrong -- somebody asked for this, and a
|
||||
* deliberate choice is not a problem to report. It is the same red as [failedColor] and [stopColor]
|
||||
* for a third reason, which is worth naming rather than collapsing: this is neither a fault nor a
|
||||
* button, it is the mark left where something was taken away. The reader never has to tell the
|
||||
* three apart, because no two of them can appear as the same kind of thing.
|
||||
*/
|
||||
val clearedColor: Color
|
||||
@Composable get() = Mocha.Red
|
||||
|
||||
/** Waiting on a person: a question, a permission, a turn that is theirs. */
|
||||
val awaitingColor: Color
|
||||
@Composable get() = Mocha.Peach
|
||||
|
||||
/** Approaching a limit -- still fine, worth seeing. */
|
||||
val warningColor: Color
|
||||
@Composable get() = Mocha.Yellow
|
||||
|
||||
/**
|
||||
* The fill of a progress bar that is only reporting how far along something is.
|
||||
*
|
||||
* Blue because a bar like this reports a quantity rather than a verdict, and the scheme's primary
|
||||
* made it the loudest thing on a screen the reader opened to do something else. A download, or a
|
||||
* compaction, has no limit to be near: it finishes. Only a bar measuring a *quota* escalates, and
|
||||
* that one is [quotaColor].
|
||||
*/
|
||||
val progressColor: Color
|
||||
@Composable get() = Mocha.Blue
|
||||
|
||||
/**
|
||||
* The fill of a bar measuring how much of a quota is gone: blue, then yellow, then red.
|
||||
*
|
||||
* One function rather than the same `when` written beside each bar, because the whole point of
|
||||
* colouring by consequence is that the reader learns the step once -- two bars showing the same 80%
|
||||
* in different colours teaches nothing except that the colour cannot be trusted. It reads as a
|
||||
* difference in degree, which is all colour can carry: the states that differ in *kind* from this
|
||||
* -- a window nobody could read, a machine that meters nothing -- are said in words elsewhere,
|
||||
* because a reader has no way to tell those from an ordinary low number by colour alone.
|
||||
*
|
||||
* [percent] is the API's own 0-100 rather than a fraction, so callers pass what the server sent
|
||||
* without each converting it first and one of them getting it wrong by a factor of a hundred.
|
||||
*/
|
||||
@Composable
|
||||
fun quotaColor(percent: Double): Color =
|
||||
when {
|
||||
percent >= OVER_LIMIT_PERCENT -> overLimitColor
|
||||
percent >= WARNING_PERCENT -> warningColor
|
||||
else -> progressColor
|
||||
}
|
||||
|
||||
/** Close enough to the limit to be worth seeing before starting something big. */
|
||||
private const val WARNING_PERCENT = 75.0
|
||||
|
||||
/** Close enough that the next turn may be the one that is refused. */
|
||||
private const val OVER_LIMIT_PERCENT = 90.0
|
||||
|
||||
/**
|
||||
* The surface verbatim text sits on: a command, a tool's output, a code block in a reply.
|
||||
*
|
||||
* The darkest value in the palette rather than a step up from the page, and that is the whole point
|
||||
* -- everything else on this screen is somebody's prose, and this is what a machine was handed and
|
||||
* what it said back, character for character. Crust sits *below* Base, so the same colour reads as
|
||||
* one clear step down both on the page, where a reply is drawn, and on a card, where a tool call
|
||||
* is; a tint chosen upwards has to be picked twice and still collides with the card it lands on.
|
||||
* The renderer's default code background was `surfaceVariant`, which is exactly a card's own fill
|
||||
* -- so a code block inside a tool call had no background at all.
|
||||
*
|
||||
* One colour for all three, so "this is verbatim" is learnable once.
|
||||
*/
|
||||
val rawSurface: Color
|
||||
@Composable get() = Mocha.Crust
|
||||
|
||||
/**
|
||||
* Catppuccin Mocha as a syntax theme, for the highlighter used on a tool call's input.
|
||||
*
|
||||
* Here with the rest of the palette rather than beside the code that highlights: a library's own
|
||||
* theme would otherwise be the one surface in the app whose colours came from somewhere else, and
|
||||
* the accents below are the same ones every other coloured thing already uses.
|
||||
*/
|
||||
fun catppuccinSyntax(): SyntaxTheme =
|
||||
SyntaxTheme(
|
||||
key = "catppuccin-mocha",
|
||||
code = Mocha.Text.toArgb(),
|
||||
keyword = Mocha.Mauve.toArgb(),
|
||||
string = Mocha.Green.toArgb(),
|
||||
literal = Mocha.Peach.toArgb(),
|
||||
comment = Mocha.Overlay0.toArgb(),
|
||||
metadata = Mocha.Yellow.toArgb(),
|
||||
multilineComment = Mocha.Overlay0.toArgb(),
|
||||
punctuation = Mocha.Subtext0.toArgb(),
|
||||
mark = Mocha.Sky.toArgb(),
|
||||
)
|
||||
|
||||
/**
|
||||
* A link. Blue is what a link is on every Catppuccin surface, and the one colour to leave alone.
|
||||
*/
|
||||
val linkColor: Color
|
||||
@Composable get() = Mocha.Blue
|
||||
|
||||
/** Past a limit. The scheme's error colour, for the reason [failedColor] gives. */
|
||||
val overLimitColor: Color
|
||||
@Composable get() = MaterialTheme.colorScheme.error
|
||||
|
||||
/**
|
||||
* The composer's buttons, coloured by what pressing one does rather than by where it sits.
|
||||
*
|
||||
* Green makes something happen now, blue makes it happen later, orange takes back what is in
|
||||
* flight, red ends the process. The near-collisions with the states above are deliberate and worth
|
||||
* naming rather than collapsing: [runningColor] is green because a session is working,
|
||||
* [failedColor] is red because one fell over, [awaitingColor] is the same orange because a session
|
||||
* is waiting on somebody -- those are *states*, and these are *actions*. A reader never has to tell
|
||||
* them apart, because nothing here is a state and nothing there is pressable.
|
||||
*/
|
||||
val sendColor: Color
|
||||
@Composable get() = Mocha.Green
|
||||
|
||||
/** Sending while a turn runs: the message waits rather than starting one. See [sendColor]. */
|
||||
val queueColor: Color
|
||||
@Composable get() = Mocha.Blue
|
||||
|
||||
/**
|
||||
* Interrupting the running turn: the work stops and the session stays.
|
||||
*
|
||||
* Orange rather than red because of how much it takes: only what is in flight. The process is still
|
||||
* there holding the conversation, and the next message starts a turn as though nothing had
|
||||
* happened. Red is spent on [stopColor], which is the same button in the same place when what it
|
||||
* would end is the session's process.
|
||||
*/
|
||||
val pauseColor: Color
|
||||
@Composable get() = Mocha.Peach
|
||||
|
||||
/** Ending the session's process -- the one button here that takes something away. */
|
||||
val stopColor: Color
|
||||
@Composable get() = Mocha.Red
|
||||
|
||||
/**
|
||||
* Starting the process again, on the conversation it left.
|
||||
*
|
||||
* The same green as [sendColor] on purpose: both mean "this happens now", and they are never the
|
||||
* same button -- the process button only offers to start when there is nothing running to stop.
|
||||
*/
|
||||
val startColor: Color
|
||||
@Composable get() = Mocha.Green
|
||||
|
||||
/**
|
||||
* A filled button in one of the action colours above.
|
||||
*
|
||||
* The content colour is stated here beside the fill rather than inherited. A semantic colour has to
|
||||
* carry its own contrast: these fills are fixed whatever the surface under them does, so the theme
|
||||
* will not change to rescue a foreground that stops being readable on one of them. Crust is what
|
||||
* every accent on this palette takes, which is the same reason `onPrimary` is Crust above.
|
||||
*/
|
||||
@Composable
|
||||
fun actionButtonColors(fill: Color): ButtonColors =
|
||||
ButtonDefaults.buttonColors(containerColor = fill, contentColor = Mocha.Crust)
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import dev.snipme.highlights.Highlights
|
||||
import dev.snipme.highlights.model.BoldHighlight
|
||||
import dev.snipme.highlights.model.ColorHighlight
|
||||
import dev.snipme.highlights.model.SyntaxLanguage
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* A tool call's input, read rather than dumped.
|
||||
*
|
||||
* Every tool's input arrives as JSON, and showing it raw makes the reader parse `{"command":"…",
|
||||
* "timeout":120000}` themselves to find the one line they care about. So the fields that carry the
|
||||
* meaning are pulled out -- the command a shell will run, what it is for, how long it may take --
|
||||
* and anything left over is still shown, because dropping a field would be claiming the tool has no
|
||||
* other input when it might.
|
||||
*/
|
||||
data class ToolInput(
|
||||
/** The thing that will actually be run or read, if this tool has one. */
|
||||
val subject: String?,
|
||||
/** The language [subject] is written in, for highlighting. */
|
||||
val language: SyntaxLanguage?,
|
||||
/** The tool's own one-line summary, when it wrote one. */
|
||||
val description: String?,
|
||||
/**
|
||||
* How long the call may take, as the tool expressed it. Shown apart because it is a limit on
|
||||
* the call rather than part of what the call does.
|
||||
*/
|
||||
val timeout: String?,
|
||||
/** Everything else, as `name: value` lines. Never dropped. */
|
||||
val rest: List<String>,
|
||||
) {
|
||||
/** The one line to show when there is only room for one: what this call is for. */
|
||||
val title: String?
|
||||
get() = description ?: subject
|
||||
}
|
||||
|
||||
/**
|
||||
* Which field of which tool is the subject.
|
||||
*
|
||||
* A table rather than a chain of `if`s: adding a tool is a row, and the shape stops any of them
|
||||
* from being the special case that gets its own code path. Unknown tools fall through to "no
|
||||
* subject, everything is rest", which is what the card always did.
|
||||
*/
|
||||
private val SUBJECTS: Map<String, Pair<String, SyntaxLanguage?>> =
|
||||
mapOf(
|
||||
"Bash" to ("command" to SyntaxLanguage.SHELL),
|
||||
"Read" to ("file_path" to null),
|
||||
"Write" to ("file_path" to null),
|
||||
"Edit" to ("file_path" to null),
|
||||
"Glob" to ("pattern" to null),
|
||||
"Grep" to ("pattern" to null),
|
||||
"WebFetch" to ("url" to null),
|
||||
)
|
||||
|
||||
/** Fields that are the tool's own prose about itself rather than input to it. */
|
||||
private val DESCRIPTIONS = listOf("description", "prompt")
|
||||
|
||||
fun parseToolInput(tool: String, input: String): ToolInput {
|
||||
val json =
|
||||
try {
|
||||
JSONObject(input)
|
||||
} catch (_: org.json.JSONException) {
|
||||
// Not an object: older transcripts and some tools send a bare
|
||||
// string. It is still the input, so it is still shown.
|
||||
return ToolInput(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
input.takeIf { it.isNotBlank() }?.let { listOf(it) }.orEmpty(),
|
||||
)
|
||||
}
|
||||
val (subjectKey, language) = SUBJECTS[tool] ?: (null to null)
|
||||
val subject = subjectKey?.let { json.optString(it) }?.takeIf { it.isNotBlank() }
|
||||
val description = DESCRIPTIONS.firstNotNullOfOrNull {
|
||||
json.optString(it).takeIf { v -> v.isNotBlank() }
|
||||
}
|
||||
val timeout = json.optString("timeout").takeIf { it.isNotBlank() }
|
||||
val rest =
|
||||
json
|
||||
.keys()
|
||||
.asSequence()
|
||||
.filter { it != subjectKey || subject == null }
|
||||
.filter { it !in DESCRIPTIONS || description == null }
|
||||
.filter { it != "timeout" || timeout == null }
|
||||
.sorted()
|
||||
.map { key -> "$key: ${json.get(key)}" }
|
||||
.toList()
|
||||
return ToolInput(subject, language, description, timeout, rest)
|
||||
}
|
||||
|
||||
/**
|
||||
* A tool call's input: its subject highlighted, then whatever else it carried.
|
||||
*
|
||||
* On the dark surface every verbatim thing in the app sits on -- see [RawBlock]. Drawn as nothing
|
||||
* at all when the call carried neither, rather than as an empty block: a tinted rectangle with
|
||||
* nothing in it is a rendering fault, and it is the shape a tool with no input actually has.
|
||||
*
|
||||
* The description is *not* here. It is the tool's own prose about what it is doing, so it belongs
|
||||
* with the reader's text rather than inside the machine's; [ToolCard] draws it above this.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolInputView(tool: String, input: String, modifier: Modifier = Modifier) {
|
||||
val parsed = remember(tool, input) { parseToolInput(tool, input) }
|
||||
if (parsed.subject == null && parsed.rest.isEmpty()) return
|
||||
RawBlock(modifier) {
|
||||
parsed.subject?.let { subject ->
|
||||
// Not wrapped: a wrapped command hides where its arguments end,
|
||||
// and the long one is the one being read closely.
|
||||
Text(
|
||||
highlighted(subject, parsed.language),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
softWrap = false,
|
||||
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
)
|
||||
}
|
||||
parsed.rest.forEach {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [code] with its keywords and strings coloured, or plain if there is no language for it.
|
||||
*
|
||||
* The lexing is dev.snipme:highlights. The colours are this app's, mapped in [catppuccinSyntax] --
|
||||
* a library's default theme would be the one place in the app whose palette came from somewhere
|
||||
* else.
|
||||
*/
|
||||
@Composable
|
||||
private fun highlighted(code: String, language: SyntaxLanguage?): AnnotatedString {
|
||||
val theme = catppuccinSyntax()
|
||||
val plain = MaterialTheme.colorScheme.onSurface
|
||||
return remember(code, language, theme, plain) {
|
||||
if (language == null) return@remember AnnotatedString(code)
|
||||
val marks =
|
||||
Highlights.Builder(code = code, language = language, theme = theme)
|
||||
.build()
|
||||
.getHighlights()
|
||||
buildAnnotatedString {
|
||||
append(code)
|
||||
marks.forEach { mark ->
|
||||
when (mark) {
|
||||
is ColorHighlight ->
|
||||
addStyle(
|
||||
SpanStyle(
|
||||
color =
|
||||
androidx.compose.ui.graphics.Color(
|
||||
mark.rgb or 0xFF000000.toInt()
|
||||
)
|
||||
),
|
||||
mark.location.start,
|
||||
mark.location.end,
|
||||
)
|
||||
is BoldHighlight ->
|
||||
addStyle(
|
||||
SpanStyle(fontWeight = FontWeight.Bold),
|
||||
mark.location.start,
|
||||
mark.location.end,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CornerBasedShape
|
||||
import androidx.compose.foundation.shape.CornerSize
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* One row as the transcript draws it: a run of consecutive tool calls, or anything else.
|
||||
*
|
||||
* Grouping is decided here rather than when events are folded, because it is a display decision:
|
||||
* the transcript's own order is what paging and the event stream depend on, and one screen's idea
|
||||
* of "these belong together" must not reach back into it.
|
||||
*
|
||||
* Immutable, and said so, because Compose cannot tell.
|
||||
*
|
||||
* A row is a value: it is rebuilt from the transcript rather than edited, and two rows describing
|
||||
* the same events are equal. Compose infers stability from a class's fields, and a `List` field --
|
||||
* which several of these carry -- makes it assume the worst, so every composable taking one
|
||||
* recomposed whenever anything above it did. A page of history landing recomposed all 148 loaded
|
||||
* rows including the markdown inside them, measured as 701 compositions for 148 rows in one scroll,
|
||||
* and that is what a page landing costs on top of the fetch itself.
|
||||
*
|
||||
* The promise this makes is real and has to stay true: nothing here is mutated after it is built.
|
||||
*/
|
||||
@Immutable
|
||||
sealed class TranscriptRow {
|
||||
/**
|
||||
* This row's identity in the list, which must survive everything that can happen to the row.
|
||||
*
|
||||
* The list is keyed by this so that inserting a new message at one end, or a page of history at
|
||||
* the other, moves the rows and not the reader. That makes it the load-bearing value on this
|
||||
* screen: when a key changes, the list loses its anchor and the transcript steps under whoever
|
||||
* is reading it.
|
||||
*
|
||||
* A tool row therefore keys on [TranscriptItem.ToolRun.runId] rather than on a sequence number,
|
||||
* and it is the *same* value whether the run is drawn as one card or as a group. A lone call
|
||||
* that gains a neighbour becomes a group without changing identity, which is the case a
|
||||
* seq-based key got wrong: the row the reader was looking at was replaced rather than updated.
|
||||
* Everything else keys on the seq of the event behind it, which never moves.
|
||||
*/
|
||||
abstract val key: Any
|
||||
|
||||
/**
|
||||
* Where this row starts in the transcript: the sequence number of the oldest event behind it.
|
||||
*
|
||||
* Separate from [key], and deliberately so. [key] is the list's identity and is a display
|
||||
* decision -- a tool row is named after its run, and a run takes its name from whichever call
|
||||
* was first when it was folded, which changes as pages arrive. A seq is the server's own
|
||||
* numbering: it is assigned once, never moves, and means the same thing to every device. So
|
||||
* anything that has to point at a place in the conversation and still find it later -- a saved
|
||||
* scroll position is the one -- points with this, and anything that has to identify a row
|
||||
* within one composition uses [key].
|
||||
*/
|
||||
abstract val startSeq: Long
|
||||
|
||||
data class Single(val item: TranscriptItem) : TranscriptRow() {
|
||||
override val key: Any
|
||||
get() = (item as? TranscriptItem.ToolRun)?.runId ?: item.seq
|
||||
|
||||
override val startSeq: Long
|
||||
get() = item.seq
|
||||
}
|
||||
|
||||
/** Two or more calls with nothing between them; drawn as one collapsed card. */
|
||||
data class Tools(val calls: List<TranscriptItem.ToolRun>) : TranscriptRow() {
|
||||
/** The run's own name, which every call in it already carries. */
|
||||
val id: String
|
||||
get() = calls.first().runId
|
||||
|
||||
override val key: Any
|
||||
get() = id
|
||||
|
||||
override val startSeq: Long
|
||||
get() = calls.first().seq
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs of adjacent tool calls become one row; everything else passes through.
|
||||
*
|
||||
* A single call is left alone: "Called 1 tool" hides a card to say the same thing in more words,
|
||||
* and the run this exists for is the burst of five greps nobody wants to scroll past.
|
||||
*/
|
||||
fun groupToolRuns(items: List<TranscriptItem>): List<TranscriptRow> =
|
||||
DebugStats.timed("grouped tool runs") { groupRuns(items) }
|
||||
|
||||
private fun groupRuns(items: List<TranscriptItem>): List<TranscriptRow> {
|
||||
val rows = mutableListOf<TranscriptRow>()
|
||||
var run = mutableListOf<TranscriptItem.ToolRun>()
|
||||
|
||||
fun flush() {
|
||||
when (run.size) {
|
||||
0 -> {}
|
||||
1 -> rows += TranscriptRow.Single(run.first())
|
||||
else -> rows += TranscriptRow.Tools(run.toList())
|
||||
}
|
||||
run = mutableListOf()
|
||||
}
|
||||
|
||||
items.forEach { item ->
|
||||
// Grouped by the run each call says it belongs to, not by adjacency worked out here.
|
||||
// Adjacency is the same answer most of the time and a worse one at the edges: a call
|
||||
// arriving next to an existing run, or a page of history arriving in front of one, both
|
||||
// change which call is *first*, and a group named after its first member is a different
|
||||
// group every time that happens.
|
||||
if (item is TranscriptItem.ToolRun && (run.isEmpty() || run.first().runId == item.runId)) {
|
||||
run += item
|
||||
} else {
|
||||
flush()
|
||||
if (item is TranscriptItem.ToolRun) run += item else rows += TranscriptRow.Single(item)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Several calls under one heading, closed until somebody asks.
|
||||
*
|
||||
* What says the calls belong together is the surface behind them, which is the one cue rather than
|
||||
* two half-cues -- rounded to the same corner every other card in the app has, so a group reads as
|
||||
* one object rather than as a square patch behind round things. The calls sit on it inset by
|
||||
* [GROUP_INSET], which is the container's own padding rather than an indent: they are the same rows
|
||||
* they would be on their own, and a rounded corner drawn hard against a rounded corner reads as a
|
||||
* notch.
|
||||
*
|
||||
* Inside, the calls are a connected stack. Facing corners are square and the outer ones are not, so
|
||||
* the run reads as one thing broken into its parts; [GROUP_GAP] keeps the parts legible without
|
||||
* separating them. See [connectedShape].
|
||||
*
|
||||
* It closes from either end. A long group's header scrolls off while its last call is still on
|
||||
* screen, and the reader who wants it shut is looking at the bottom, not hunting for the top. The
|
||||
* bar at the foot is the same height as the heading at the top, so the surface the calls sit on is
|
||||
* as thick below them as above.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolGroup(
|
||||
group: TranscriptRow.Tools,
|
||||
expanded: Boolean,
|
||||
/**
|
||||
* Where it was pressed is the row's business rather than the control's -- a group has a control
|
||||
* at each end, and only the row knows where its own ends are, so the row records the touch
|
||||
* itself and this just says that one happened.
|
||||
*/
|
||||
onToggle: () -> Unit,
|
||||
isToolExpanded: (String) -> Boolean,
|
||||
onToolToggle: (String) -> Unit,
|
||||
onAnswer: (questionId: String, answers: List<String>) -> Unit,
|
||||
image: @Composable (String) -> Unit,
|
||||
) {
|
||||
val heading = "Called ${group.calls.size} tools"
|
||||
if (!expanded) {
|
||||
Card(Modifier.fillMaxWidth().clickable(onClick = onToggle)) {
|
||||
Text(
|
||||
heading,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
modifier = Modifier.padding(GROUP_INSET_LARGE),
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
Column(
|
||||
Modifier.fillMaxWidth()
|
||||
.clip(MaterialTheme.shapes.medium)
|
||||
.background(MaterialTheme.colorScheme.surfaceContainerLow)
|
||||
) {
|
||||
val barHeight = groupBarHeight()
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(barHeight).clickable(onClick = onToggle),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
heading,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
modifier = Modifier.padding(horizontal = GROUP_INSET_LARGE),
|
||||
)
|
||||
}
|
||||
Column(
|
||||
Modifier.padding(horizontal = GROUP_INSET),
|
||||
verticalArrangement = Arrangement.spacedBy(GROUP_GAP),
|
||||
) {
|
||||
group.calls.forEachIndexed { index, call ->
|
||||
ToolCard(
|
||||
tool = call,
|
||||
expanded = isToolExpanded(call.id),
|
||||
onToggle = { onToolToggle(call.id) },
|
||||
onAnswer = onAnswer,
|
||||
image = image,
|
||||
shape = connectedShape(index, group.calls.size),
|
||||
)
|
||||
}
|
||||
}
|
||||
// Shutting it from here anchors the other end: the reader is at the bottom of a long
|
||||
// group, and what they are looking at is what follows it.
|
||||
CollapseBar(barHeight, onToggle)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The height of a group's heading, and so of the bar at its foot.
|
||||
*
|
||||
* Derived from the type the heading is set in rather than written down, because the two have to
|
||||
* match and a pair of numbers chosen to look equal stops being equal the moment either the style or
|
||||
* the density changes. Taking the line height also means the heading cannot be clipped by it.
|
||||
*/
|
||||
@Composable
|
||||
private fun groupBarHeight(): Dp {
|
||||
val line = MaterialTheme.typography.titleSmall.lineHeight
|
||||
return with(LocalDensity.current) { line.toDp() } + GROUP_INSET_LARGE * 2
|
||||
}
|
||||
|
||||
/**
|
||||
* The bottom half of a group's toggle: an arrow back up to its heading.
|
||||
*
|
||||
* Given the heading's height rather than padded to something that looks close, so the surface the
|
||||
* calls sit on is the same thickness at both ends. See [groupBarHeight].
|
||||
*/
|
||||
@Composable
|
||||
private fun CollapseBar(height: Dp, onToggle: () -> Unit) {
|
||||
val colour = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(height).clickable(onClick = onToggle).semantics {
|
||||
contentDescription = "Collapse these tool calls"
|
||||
},
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Chevron(pointingUp = true, colour = colour)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape of one card in a stack of [count]: square where it faces a neighbour, rounded where it
|
||||
* does not.
|
||||
*
|
||||
* Written once and given an index rather than branched at each end, because a stack has three cases
|
||||
* that are one rule -- and the middle one is the case a hand-written first/last pair gets wrong
|
||||
* when a run turns out to have three calls in it.
|
||||
*/
|
||||
@Composable
|
||||
private fun connectedShape(index: Int, count: Int): CornerBasedShape {
|
||||
val shape = MaterialTheme.shapes.medium
|
||||
val square = CornerSize(0.dp)
|
||||
return shape.copy(
|
||||
topStart = if (index == 0) shape.topStart else square,
|
||||
topEnd = if (index == 0) shape.topEnd else square,
|
||||
bottomStart = if (index == count - 1) shape.bottomStart else square,
|
||||
bottomEnd = if (index == count - 1) shape.bottomEnd else square,
|
||||
)
|
||||
}
|
||||
|
||||
/** The padding inside a card, and so the height a bar of one line of text comes to. */
|
||||
private val GROUP_INSET_LARGE = 12.dp
|
||||
|
||||
/** How far the stack of calls is held off the edge of the surface it sits on. */
|
||||
private val GROUP_INSET = 4.dp
|
||||
|
||||
/** Enough to read the join as a join rather than as one tall card. */
|
||||
private val GROUP_GAP = 2.dp
|
||||
|
||||
/**
|
||||
* One tool call.
|
||||
*
|
||||
* Closed, it is a single line: the tool's name and what the call is for. The command itself is not
|
||||
* on it, because a wrapped command turns one row into four and a run of them into a wall -- and the
|
||||
* name plus the intent is what somebody scanning the transcript is reading for.
|
||||
*
|
||||
* Open, it shows the command, whatever else the input carried, and the output. The timeout sits at
|
||||
* the top right: it is a limit on the call rather than part of what the call does, and it is worth
|
||||
* seeing beside the command it constrains rather than buried in the fields below it.
|
||||
*
|
||||
* A call waiting on permission is shown open whatever the reader last chose, since the command is
|
||||
* the thing being decided and a row saying only "Bash" cannot be decided on.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolCard(
|
||||
tool: TranscriptItem.ToolRun,
|
||||
expanded: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
onAnswer: (questionId: String, answers: List<String>) -> Unit,
|
||||
image: @Composable (String) -> Unit = {},
|
||||
/** Square where this card faces another in a group; see [connectedShape]. */
|
||||
shape: Shape = CardDefaults.shape,
|
||||
) {
|
||||
val parsed = remember(tool.tool, tool.input) { parseToolInput(tool.tool, tool.input) }
|
||||
val deciding = tool.asks.any { it.answers.isEmpty() }
|
||||
val open = expanded || deciding
|
||||
Card(Modifier.fillMaxWidth().clickable(onClick = onToggle), shape = shape) {
|
||||
Column(Modifier.padding(GROUP_INSET_LARGE)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(tool.tool, style = MaterialTheme.typography.titleSmall)
|
||||
if (open) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
parsed.timeout?.let {
|
||||
Text(
|
||||
"timeout $it",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
parsed.title?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(start = 8.dp),
|
||||
)
|
||||
} ?: Spacer(Modifier.weight(1f))
|
||||
}
|
||||
// A spinner says the machine is working. While this call is waiting on an
|
||||
// answer the machine is doing nothing at all -- the turn is stopped on the
|
||||
// person reading it -- so it says whose move it is instead, in the colour this
|
||||
// app uses everywhere for that.
|
||||
if (deciding) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"your turn",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = awaitingColor,
|
||||
)
|
||||
} else if (!tool.done) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.width(16.dp).height(16.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (open) {
|
||||
parsed.description?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
// Everything AskUserQuestion carries is the questions, and those are drawn
|
||||
// below as something answerable; dumping the same JSON above them would be the
|
||||
// decision stated twice, once unreadably.
|
||||
if (tool.tool != ASK_USER_QUESTION) {
|
||||
ToolInputView(tool.tool, tool.input, Modifier.padding(top = 4.dp))
|
||||
}
|
||||
if (tool.output.isNotEmpty()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text("Output", style = MaterialTheme.typography.labelSmall)
|
||||
// What the tool printed, on the surface everything verbatim gets and in the
|
||||
// face it was written for: this is column-aligned far more often than it is
|
||||
// prose -- a directory listing, a diff, a table of numbers -- and a
|
||||
// proportional font silently destroys the alignment that carried the meaning.
|
||||
RawBlock(Modifier.padding(top = 2.dp)) {
|
||||
Text(
|
||||
tool.output,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Shown open or closed. A call that produced a picture is one
|
||||
// whose result *is* the picture, and a row that hides it says
|
||||
// less than the one line it replaced -- unlike a command, which
|
||||
// is what the closed line already summarises.
|
||||
tool.images.forEach { ref -> image(ref) }
|
||||
if (tool.asks.isNotEmpty()) {
|
||||
if (tool.tool == ASK_USER_QUESTION) {
|
||||
AskUserQuestionBody(tool.asks, onAnswer)
|
||||
} else {
|
||||
tool.asks.forEach { ask ->
|
||||
PermissionAsk(ask) { answers -> onAnswer(ask.id, answers) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The permission ask on the call it is about.
|
||||
*
|
||||
* Only the question, not the prompt's second half: the backend sends the tool's input with it so
|
||||
* the ask can stand alone, and here it does not have to -- the card above is showing exactly that.
|
||||
*/
|
||||
@Composable
|
||||
private fun PermissionAsk(ask: TranscriptItem.QuestionCard, onAnswer: (List<String>) -> Unit) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
ask.prompt.substringBefore('\n'),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = awaitingColor,
|
||||
)
|
||||
if (ask.answers.isNotEmpty()) {
|
||||
Text(
|
||||
"Answered: ${ask.answers.joinToString(", ")}",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
AnswerOptions(ask.options, onAnswer)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tool whose input is a question rather than a command; see [AskUserQuestionBody].
|
||||
*
|
||||
* Also what [runIdFor] breaks a run of calls on, so the row a reader answered is never folded
|
||||
* inside a collapsed group.
|
||||
*/
|
||||
const val ASK_USER_QUESTION = "AskUserQuestion"
|
||||
@@ -0,0 +1,439 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* What the transcript renders: the event stream folded into displayable rows (see [foldEvent]). The
|
||||
* stream is the only data source -- opening a session screen replays from seq 0, and a reconnect
|
||||
* resumes from the last seq seen, so there is no separate history fetch to drift from it.
|
||||
*/
|
||||
@Immutable
|
||||
sealed class TranscriptItem {
|
||||
/**
|
||||
* The transcript sequence number this row started at, and its identity on screen.
|
||||
*
|
||||
* The list is drawn newest-first, so every new message is an insertion at index 0 and every
|
||||
* page of history is an insertion at the far end. Without an identity that survives both, the
|
||||
* list is addressed by position: whatever somebody had scrolled to keeps its index while the
|
||||
* content underneath it slides, which reads as the view scrolling on its own.
|
||||
*
|
||||
* A seq is the right identity because it is what the transcript itself is ordered by, it never
|
||||
* changes, and it is already carried by every event. A row built from several events -- a
|
||||
* streaming message, a tool call and its result -- keeps the seq of the first, so it holds
|
||||
* still while the rest of it arrives.
|
||||
*/
|
||||
abstract val seq: Long
|
||||
|
||||
data class UserMsg(
|
||||
override val seq: Long,
|
||||
val text: String,
|
||||
/** Refs of what was attached, drawn inside the bubble. */
|
||||
val images: List<String> = emptyList(),
|
||||
) : TranscriptItem()
|
||||
|
||||
data class AssistantMsg(override val seq: Long, val text: String) : TranscriptItem()
|
||||
|
||||
data class ToolRun(
|
||||
override val seq: Long,
|
||||
val id: String,
|
||||
/**
|
||||
* The run of adjacent calls this one belongs to, named once when the call is folded in and
|
||||
* never recomputed.
|
||||
*
|
||||
* Carried rather than derived because a run can gain members at *either* end -- a new call
|
||||
* arriving beside it, or a page of history arriving in front of it -- so no function of its
|
||||
* current members is stable. It is the first call's id at the moment the run started, which
|
||||
* is a name rather than a description: [joinPages] hands it to older calls that turn out to
|
||||
* belong to the same run, instead of renaming the run they joined.
|
||||
*/
|
||||
val runId: String,
|
||||
val tool: String,
|
||||
val input: String,
|
||||
val output: String,
|
||||
val done: Boolean,
|
||||
/**
|
||||
* The questions this call is waiting on, in the order they were asked.
|
||||
*
|
||||
* On the call's own row rather than beside it: an ask used to arrive as a second card
|
||||
* repeating the input verbatim, so the reader saw the same command twice and had to work
|
||||
* out that it was one event. The backend says which call a question is about, so this is a
|
||||
* fact rather than a match on the input.
|
||||
*
|
||||
* A list because AskUserQuestion asks up to four at once, and they are one decision to make
|
||||
* -- a permission is the case of exactly one, not a different shape.
|
||||
*/
|
||||
val asks: List<QuestionCard> = emptyList(),
|
||||
/**
|
||||
* Images this call's result carried, drawn under it.
|
||||
*
|
||||
* Beside it they had to be paired by position, and position is the thing a page boundary
|
||||
* breaks -- a screenshot loaded on one page and its call on the next read as unrelated.
|
||||
*/
|
||||
val images: List<String> = emptyList(),
|
||||
) : TranscriptItem()
|
||||
|
||||
data class QuestionCard(
|
||||
override val seq: Long,
|
||||
val id: String,
|
||||
val prompt: String,
|
||||
/** A few words naming what this is about, when the asker offered one. */
|
||||
val header: String?,
|
||||
val options: List<QuestionOption>,
|
||||
/** Whether several options may be chosen at once. */
|
||||
val multiSelect: Boolean,
|
||||
/** What was chosen, once something was; empty until then. */
|
||||
val answers: List<String>,
|
||||
) : TranscriptItem()
|
||||
|
||||
data class ErrorMsg(override val seq: Long, val message: String) : TranscriptItem()
|
||||
|
||||
/** An image by server-side ref, fetched from the session's files route. */
|
||||
data class ImageItem(override val seq: Long, val ref: String) : TranscriptItem()
|
||||
|
||||
/**
|
||||
* A message another agent sent this session.
|
||||
*
|
||||
* Its own row rather than a [UserMsg]: see [PeerMessageRow] for why the voice matters.
|
||||
*/
|
||||
data class PeerNote(override val seq: Long, val from: String, val text: String) :
|
||||
TranscriptItem()
|
||||
|
||||
/**
|
||||
* A command the session ran on itself -- `/compact`, `/rename`.
|
||||
*
|
||||
* Kept in the transcript rather than only shown while it waits, because it explains what
|
||||
* follows: a conversation that suddenly has half the context, or a session with a new name.
|
||||
*/
|
||||
data class CommandRow(override val seq: Long, val text: String) : TranscriptItem()
|
||||
|
||||
/** Placeholder row for events this build can't render (newer kinds). */
|
||||
data class Note(override val seq: Long, val text: String) : TranscriptItem()
|
||||
|
||||
/**
|
||||
* A clear that happened: everything above it left the session's context and stayed on screen.
|
||||
*
|
||||
* Carries only its position, because that is all it means.
|
||||
*/
|
||||
data class ClearedNote(override val seq: Long) : TranscriptItem()
|
||||
|
||||
/**
|
||||
* A compaction that happened, and what it recovered.
|
||||
*
|
||||
* In the transcript rather than only in the status line, because the status is gone the moment
|
||||
* it finishes and this is the part worth keeping: it is the explanation for a gap in the
|
||||
* conversation, and for a minute or two in which the session was busy with nothing to show.
|
||||
*
|
||||
* The wire also says what triggered it, and this deliberately does not carry that: the row says
|
||||
* the two sizes and nothing else (see [compactionSummary]), so keeping the trigger here would
|
||||
* be a field nothing can read.
|
||||
*/
|
||||
data class CompactedNote(
|
||||
override val seq: Long,
|
||||
val preTokens: Long?,
|
||||
val postTokens: Long?,
|
||||
) : TranscriptItem()
|
||||
}
|
||||
|
||||
/**
|
||||
* The run a call joins: the one it lands next to, or a new one named after itself.
|
||||
*
|
||||
* Only ever consulted when the call is first folded in. That is what makes the name stable -- a run
|
||||
* keeps whatever it was called when it started, however many calls arrive at either end of it
|
||||
* afterwards.
|
||||
*
|
||||
* A question to the reader is in a run of its own, which is what puts it on the transcript as a row
|
||||
* rather than inside a collapsed "Called 6 tools" card. Two things follow from being alone: it is
|
||||
* always visible, since a run of one is drawn as itself rather than as a group; and the calls
|
||||
* around it fall into a group before it and a group after it, so where the reader was asked
|
||||
* something is legible in the shape of the transcript without opening anything. It ends the run
|
||||
* before it as well as starting a fresh one after -- the moment somebody was asked is a boundary in
|
||||
* the work, not a gap in the middle of one run.
|
||||
*/
|
||||
private fun runIdFor(items: List<TranscriptItem>, id: String, tool: String): String {
|
||||
val previous = items.lastOrNull() as? TranscriptItem.ToolRun ?: return id
|
||||
if (tool == ASK_USER_QUESTION || previous.tool == ASK_USER_QUESTION) return id
|
||||
return previous.runId
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a page of older items in front of the ones already loaded, healing whatever the page
|
||||
* boundary cut in two.
|
||||
*
|
||||
* Two things straddle a boundary: a tool call separated from its result, and a message separated
|
||||
* from the rest of itself. Both were one thing before the transcript was cut into pages, and both
|
||||
* have to be one thing again -- a reply drawn as two messages is the same defect as a call drawn
|
||||
* twice, arriving from the same cause.
|
||||
*
|
||||
* A boundary lands wherever it lands, and roughly half the time that is between a call and its
|
||||
* result. The newer page then holds a `ToolEnd` whose start it never saw, which [foldEvent] draws
|
||||
* as a row of its own -- correctly, because a call that renders as nothing is indistinguishable
|
||||
* from one that never happened. When the older page arrives it brings the real `ToolStart`, and
|
||||
* concatenating the two lists left *both*: the same call twice, once as a proper card and once as a
|
||||
* nameless placeholder. Visible as a run of four calls reporting "Called 5 tools", and worse than
|
||||
* the miscount -- the extra row is at the join, so it also moves everything the reader was looking
|
||||
* at.
|
||||
*
|
||||
* Merged by the call's own id rather than by position, because position is exactly what a page
|
||||
* boundary destroys. The older row wins on what a start knows (the tool's name, its input) and the
|
||||
* newer on what an end knows (the output, and whether it finished), which is the only way round
|
||||
* that loses nothing.
|
||||
*/
|
||||
fun joinPages(earlier: List<TranscriptItem>, later: List<TranscriptItem>): List<TranscriptItem> {
|
||||
val (older, newer) = healSplitMessage(earlier, later)
|
||||
val startedEarlier =
|
||||
older.filterIsInstance<TranscriptItem.ToolRun>().mapTo(mutableSetOf()) { it.id }
|
||||
if (startedEarlier.isEmpty()) return older + newer
|
||||
val endedLater =
|
||||
newer
|
||||
.filterIsInstance<TranscriptItem.ToolRun>()
|
||||
.associateBy { it.id }
|
||||
.filterKeys { it in startedEarlier }
|
||||
if (endedLater.isEmpty()) return older + newer
|
||||
val healed = older.map { row ->
|
||||
val half = (row as? TranscriptItem.ToolRun)?.let { endedLater[it.id] }
|
||||
if (row is TranscriptItem.ToolRun && half != null) {
|
||||
row.copy(
|
||||
output = half.output,
|
||||
done = half.done,
|
||||
// Kept from both halves: a question or an image can be attached to either,
|
||||
// depending on which side of the boundary its event fell.
|
||||
asks = row.asks + half.asks,
|
||||
images = row.images + half.images,
|
||||
)
|
||||
} else {
|
||||
row
|
||||
}
|
||||
}
|
||||
val kept = newer.filterNot { it is TranscriptItem.ToolRun && it.id in endedLater }
|
||||
return adoptRun(healed, kept) + kept
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejoins a message the page boundary cut, and hands back the two pages to concatenate.
|
||||
*
|
||||
* [foldEvent] never leaves two assistant messages next to each other inside one page -- deltas
|
||||
* accumulate into the message before them -- so two meeting at a join are always the two halves of
|
||||
* one reply, and leaving them apart drew a single answer as two, with a paragraph break through the
|
||||
* middle of a sentence.
|
||||
*
|
||||
* The newer half keeps its identity, for the reason [adoptRun] gives: it is the row already on
|
||||
* screen, and renaming that is how the list loses its anchor. It grows by what the older half
|
||||
* brings, which is safe here and nowhere else -- the join is at the oldest end of what is loaded,
|
||||
* so the growth extends off the top of the screen, away from the row the list anchors to.
|
||||
*/
|
||||
private fun healSplitMessage(
|
||||
earlier: List<TranscriptItem>,
|
||||
later: List<TranscriptItem>,
|
||||
): Pair<List<TranscriptItem>, List<TranscriptItem>> {
|
||||
val head = earlier.lastOrNull()
|
||||
val tail = later.firstOrNull()
|
||||
if (head !is TranscriptItem.AssistantMsg || tail !is TranscriptItem.AssistantMsg) {
|
||||
return earlier to later
|
||||
}
|
||||
return earlier.dropLast(1) to (listOf(tail.copy(text = head.text + tail.text)) + later.drop(1))
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the older calls at the join the name of the run they are joining.
|
||||
*
|
||||
* The two pages were folded separately, so a run split by the boundary came back as two runs with
|
||||
* two names. Naming the joined run after the *older* half would be the obvious way round and is the
|
||||
* wrong one: the newer half is the part already on screen, and renaming it is renaming the row the
|
||||
* reader is looking at, which is how a list loses its anchor and steps under them. So the arriving
|
||||
* calls take the name of the ones already there, and nothing visible changes identity.
|
||||
*/
|
||||
private fun adoptRun(
|
||||
earlier: List<TranscriptItem>,
|
||||
later: List<TranscriptItem>,
|
||||
): List<TranscriptItem> {
|
||||
val first = later.firstOrNull() as? TranscriptItem.ToolRun ?: return earlier
|
||||
// A question is in a run of its own on both sides of the join, the same as it would be had
|
||||
// the two pages been folded as one -- see `runIdFor`. Without this the heal would merge a
|
||||
// group straight through the row the reader was asked something on.
|
||||
if (first.tool == ASK_USER_QUESTION) return earlier
|
||||
val joining = first.runId
|
||||
val tail = earlier.takeLastWhile {
|
||||
it is TranscriptItem.ToolRun && it.tool != ASK_USER_QUESTION
|
||||
}
|
||||
if (tail.isEmpty()) return earlier
|
||||
return earlier.dropLast(tail.size) +
|
||||
tail.map { (it as TranscriptItem.ToolRun).copy(runId = joining) }
|
||||
}
|
||||
|
||||
fun foldEvent(items: List<TranscriptItem>, entry: SeqEvent): List<TranscriptItem> =
|
||||
when (val event = entry.event) {
|
||||
is SessionEvent.UserMessage ->
|
||||
items + TranscriptItem.UserMsg(entry.seq, event.text, event.images)
|
||||
is SessionEvent.AssistantText -> {
|
||||
// Deltas accumulate into the message they're streaming, which keeps the seq of the
|
||||
// first of them: a row whose identity changed with every delta would be a new row on
|
||||
// every frame, and the list would jump for the whole of a streamed answer.
|
||||
val last = items.lastOrNull()
|
||||
if (last is TranscriptItem.AssistantMsg) {
|
||||
items.dropLast(1) + last.copy(text = last.text + event.delta)
|
||||
} else {
|
||||
items + TranscriptItem.AssistantMsg(entry.seq, event.delta)
|
||||
}
|
||||
}
|
||||
is SessionEvent.ToolStart ->
|
||||
items +
|
||||
TranscriptItem.ToolRun(
|
||||
entry.seq,
|
||||
event.id,
|
||||
runIdFor(items, event.id, event.tool),
|
||||
event.tool,
|
||||
event.input,
|
||||
"",
|
||||
done = false,
|
||||
)
|
||||
is SessionEvent.ToolUpdate -> updateTool(items, event.id) { it.copy(output = event.output) }
|
||||
is SessionEvent.ToolEnd ->
|
||||
// Created when its start is not here, rather than dropped. A
|
||||
// fold that only ever *updates* loses the whole call when the
|
||||
// start fell outside the loaded window, and a tool call that
|
||||
// renders as nothing is indistinguishable from one that never
|
||||
// happened. The name is unknown from an end alone; loading the
|
||||
// page before this one replaces the row with the real thing.
|
||||
if (items.any { it is TranscriptItem.ToolRun && it.id == event.id }) {
|
||||
updateTool(items, event.id) { it.copy(output = event.output, done = true) }
|
||||
} else {
|
||||
items +
|
||||
TranscriptItem.ToolRun(
|
||||
entry.seq,
|
||||
event.id,
|
||||
// The name is not known from an end alone, so a call that was an ask
|
||||
// cannot be recognised as one here; loading the page before this
|
||||
// replaces the row with the real thing, which is when it splits out.
|
||||
runIdFor(items, event.id, "tool"),
|
||||
"tool",
|
||||
"",
|
||||
event.output,
|
||||
done = true,
|
||||
)
|
||||
}
|
||||
is SessionEvent.Question -> {
|
||||
val card =
|
||||
TranscriptItem.QuestionCard(
|
||||
entry.seq,
|
||||
event.id,
|
||||
event.prompt,
|
||||
event.header,
|
||||
event.options,
|
||||
event.multiSelect,
|
||||
emptyList(),
|
||||
)
|
||||
// A question with no tool behind it -- AskUserQuestion, or an ask
|
||||
// whose call fell outside the loaded window -- is a card of its
|
||||
// own, which is what every question was before this.
|
||||
if (
|
||||
event.about != null &&
|
||||
items.any { it is TranscriptItem.ToolRun && it.id == event.about }
|
||||
) {
|
||||
updateTool(items, event.about) { it.copy(asks = it.asks + card) }
|
||||
} else {
|
||||
items + card
|
||||
}
|
||||
}
|
||||
is SessionEvent.Answered ->
|
||||
// Resolved wherever it is drawn: a card of its own, or a tool
|
||||
// row's ask. Missing the second left an Allow/Deny pair live on
|
||||
// a question already answered from another device.
|
||||
items.map {
|
||||
when {
|
||||
it is TranscriptItem.QuestionCard && it.id == event.id ->
|
||||
it.copy(answers = event.answers)
|
||||
it is TranscriptItem.ToolRun && it.asks.any { ask -> ask.id == event.id } ->
|
||||
it.copy(
|
||||
asks =
|
||||
it.asks.map { ask ->
|
||||
if (ask.id == event.id) ask.copy(answers = event.answers)
|
||||
else ask
|
||||
}
|
||||
)
|
||||
else -> it
|
||||
}
|
||||
}
|
||||
is SessionEvent.PeerMessage ->
|
||||
items + TranscriptItem.PeerNote(entry.seq, event.from, event.text)
|
||||
is SessionEvent.CommandSent -> items + TranscriptItem.CommandRow(entry.seq, event.text)
|
||||
// Screen-level state, not transcript rows -- see SessionScreen.
|
||||
is SessionEvent.CommandQueued -> items
|
||||
// No row of its own: a message that is still waiting is drawn as a pending bubble below
|
||||
// the transcript, and becomes an ordinary one where the session read it.
|
||||
is SessionEvent.MessageQueued -> items
|
||||
is SessionEvent.Settings -> items
|
||||
is SessionEvent.Status -> items
|
||||
is SessionEvent.Error -> items + TranscriptItem.ErrorMsg(entry.seq, event.message)
|
||||
is SessionEvent.Image ->
|
||||
// Under the call that produced it when there is one, and a row of
|
||||
// its own when there is not -- a person's own attachment belongs
|
||||
// to no call, and neither does one whose call fell outside the
|
||||
// loaded window.
|
||||
if (
|
||||
event.about != null &&
|
||||
items.any { it is TranscriptItem.ToolRun && it.id == event.about }
|
||||
) {
|
||||
updateTool(items, event.about) { it.copy(images = it.images + event.ref) }
|
||||
} else {
|
||||
items + TranscriptItem.ImageItem(entry.seq, event.ref)
|
||||
}
|
||||
is SessionEvent.Cleared -> items + TranscriptItem.ClearedNote(entry.seq)
|
||||
is SessionEvent.Compacted ->
|
||||
items + TranscriptItem.CompactedNote(entry.seq, event.preTokens, event.postTokens)
|
||||
is SessionEvent.Unknown -> items + TranscriptItem.Note(entry.seq, "[${event.type}]")
|
||||
// Screen-level state, not transcript rows -- see SessionScreen.
|
||||
is SessionEvent.UsageDelta -> items
|
||||
}
|
||||
|
||||
private fun updateTool(
|
||||
items: List<TranscriptItem>,
|
||||
id: String,
|
||||
change: (TranscriptItem.ToolRun) -> TranscriptItem.ToolRun,
|
||||
): List<TranscriptItem> = items.map {
|
||||
if (it is TranscriptItem.ToolRun && it.id == id) change(it) else it
|
||||
}
|
||||
|
||||
/**
|
||||
* Where markdown is parsed ahead of being drawn: two threads, never all of them.
|
||||
*
|
||||
* The default dispatcher sizes itself to the machine, which is right for work somebody is waiting
|
||||
* on and wrong for work nobody is. A page of history is hundreds of parses arriving at once, and
|
||||
* taking every core for them leaves the thread that draws the frame queueing behind one -- measured
|
||||
* on a Pixel 9 Pro XL as 21ms of `waited` at the 90th percentile, which is the frame failing to
|
||||
* *start* rather than taking too long once it had.
|
||||
*/
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
private val parsingThreads = Dispatchers.Default.limitedParallelism(2)
|
||||
|
||||
/**
|
||||
* Parses the replies among [rows], off whatever thread is drawing.
|
||||
*
|
||||
* Called where a page of transcript is folded rather than where a row is composed, which is the
|
||||
* whole point: the work happens seconds before the reader reaches the rows it was done for. See
|
||||
* [ParsedReplies].
|
||||
*
|
||||
* What is warmed mirrors what the rows draw, unit by unit -- prose split into its blocks, a memory
|
||||
* note whole -- because a string warmed under a key no row ever looks up is a miss that nothing
|
||||
* reports; see [transcriptUnits], which is the flatten this has to agree with. It reads the same
|
||||
* [ParsedReplies.partsOf] and [ParsedReplies.blocksOf] caches the flatten does, so a message is
|
||||
* scanned once however many pages hand it back through here, while the whole loaded transcript
|
||||
* crosses this on every page.
|
||||
*/
|
||||
suspend fun warm(replies: ParsedReplies, rows: List<TranscriptItem>) {
|
||||
withContext(parsingThreads) {
|
||||
val texts =
|
||||
rows
|
||||
.filterIsInstance<TranscriptItem.AssistantMsg>()
|
||||
.flatMap { replies.partsOf(it.text) }
|
||||
.flatMap { part ->
|
||||
when (part) {
|
||||
is MessagePart.Prose -> replies.blocksOf(part.text)
|
||||
// Drawn as one MarkdownText, so its whole text is the key looked up.
|
||||
is MessagePart.Remembered -> listOf(part.text)
|
||||
}
|
||||
}
|
||||
if (texts.isNotEmpty()) replies.warm(texts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* The transcript: a lazy list of [TranscriptUnit]s, laid out in reverse.
|
||||
*
|
||||
* Reverse layout is what makes the two insertions this list gets free rather than corrected. Item
|
||||
* zero is the newest content and sits at the bottom, so a message arriving extends the end the
|
||||
* viewport is pinned to and following it is not an effect -- and a page of older history lands at
|
||||
* indices past everything visible, which moves nothing on screen. The keyboard is the same case
|
||||
* from the other side: the viewport shrinks and the anchored item stays against its bottom edge. A
|
||||
* conversation shorter than the screen stacks from the bottom, hanging from the composer.
|
||||
*
|
||||
* The lazy list is also the whole of the windowing. Only what is near the viewport is composed and
|
||||
* alive, so the per-frame cost is bounded by the screen rather than by how much is loaded -- the
|
||||
* property a plain column here had to approximate with retained ranges and stand-in spacers, each
|
||||
* of which was a way to flicker. An item the framework composes is drawn the same frame it is
|
||||
* placed, and an item off screen is not a node at all.
|
||||
*
|
||||
* What keeps a unit's arrival cheap enough to happen mid-fling: a unit is at most one block of a
|
||||
* reply, and its parse is already made by [warm] before the fold that introduces it -- so entering
|
||||
* composition costs laying out one paragraph, not parsing a message.
|
||||
*/
|
||||
@Composable
|
||||
fun TranscriptList(
|
||||
units: List<TranscriptUnit>,
|
||||
state: LazyListState,
|
||||
moreHistory: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
below: @Composable () -> Unit,
|
||||
unit: @Composable (TranscriptUnit) -> Unit,
|
||||
) {
|
||||
LazyColumn(
|
||||
state = state,
|
||||
reverseLayout = true,
|
||||
contentPadding = TRANSCRIPT_PADDING,
|
||||
modifier =
|
||||
// Timed in two halves because the frame's draw phase is where Compose's measurement
|
||||
// lands, and "draw is high while nothing is being recorded" does not say which half;
|
||||
// see [drawAccounting]. Measure includes composing the items that scrolled in.
|
||||
modifier
|
||||
.layout { measurable, constraints ->
|
||||
val started = System.nanoTime()
|
||||
val placeable = measurable.measure(constraints)
|
||||
DebugStats.record("measure: the whole transcript", System.nanoTime() - started)
|
||||
layout(placeable.width, placeable.height) {
|
||||
val placing = System.nanoTime()
|
||||
placeable.place(0, 0)
|
||||
DebugStats.record(
|
||||
"place: the whole transcript",
|
||||
System.nanoTime() - placing,
|
||||
)
|
||||
}
|
||||
}
|
||||
.drawWithContent {
|
||||
val started = System.nanoTime()
|
||||
drawContent()
|
||||
DebugStats.record("draw: the whole transcript", System.nanoTime() - started)
|
||||
},
|
||||
) {
|
||||
// The bottom of the screen: what is waiting to be read sits under the newest message.
|
||||
item(key = "below", contentType = "below") { below() }
|
||||
items(count = units.size, key = { units[it].key }, contentType = { units[it]::class }) {
|
||||
val u = units[it]
|
||||
DebugStats.count("unit composed")
|
||||
Box(Modifier.fillMaxWidth().padding(top = u.gap)) { unit(u) }
|
||||
}
|
||||
// Standing in for everything not fetched yet. Only here while there is more -- its
|
||||
// appearance at the top edge is also roughly when the next page is asked for, so what it
|
||||
// reports is a fetch in flight rather than an end reached.
|
||||
if (moreHistory) {
|
||||
item(key = "history", contentType = "history") {
|
||||
Box(Modifier.fillMaxWidth().padding(vertical = 24.dp)) {
|
||||
CircularProgressIndicator(
|
||||
Modifier.align(Alignment.Center).size(HISTORY_SPINNER)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The gap between rows, and the room around the whole conversation. */
|
||||
val TRANSCRIPT_SPACING: Dp = 8.dp
|
||||
|
||||
val TRANSCRIPT_PADDING: PaddingValues = PaddingValues(16.dp)
|
||||
|
||||
/** Smaller than the whole-screen loading spinner: it stands in for a page, not for everything. */
|
||||
private val HISTORY_SPINNER = 24.dp
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* One item of the transcript list: a whole row, or one block of a settled reply.
|
||||
*
|
||||
* The unit of laziness is deliberately smaller than a message. A lazy list pays to compose an item
|
||||
* at the moment it scrolls into view, and that cost is proportional to the item -- a reply can be
|
||||
* twenty-five screens of markdown, which as one item is a hundred-millisecond frame exactly when
|
||||
* the list is moving fastest. A *block* is a paragraph, a fence, a table: bounded, so the worst
|
||||
* frame is bounded. This is the piece that was missing when a lazy list was last tried here; the
|
||||
* block splitting existed only inside the row, where the list could not see it.
|
||||
*
|
||||
* Everything else about the row model is unchanged: rows come from [groupToolRuns], and a unit
|
||||
* points back at its row. The list draws units; anchors and paging still speak seq.
|
||||
*/
|
||||
@Immutable
|
||||
sealed class TranscriptUnit {
|
||||
/** The list identity; must survive pages landing at either end. See [TranscriptRow.key]. */
|
||||
abstract val key: Any
|
||||
|
||||
/** Where this unit's row starts in the transcript -- the anchor identity, never the key. */
|
||||
abstract val seq: Long
|
||||
|
||||
/**
|
||||
* This unit's position within its row, counted from the row's oldest end.
|
||||
*
|
||||
* What a saved scroll position carries besides the seq: a reply split into forty blocks needs
|
||||
* more than "somewhere in this row" to put a reader back where they stopped.
|
||||
*/
|
||||
abstract val ordinal: Int
|
||||
|
||||
/** The gap drawn above this unit -- between rows, or between blocks of one reply. */
|
||||
abstract val gap: Dp
|
||||
|
||||
/** A row drawn as itself: a bubble, a tool card, a group -- or the reply still arriving. */
|
||||
data class Whole(val row: TranscriptRow, override val gap: Dp) : TranscriptUnit() {
|
||||
override val key: Any
|
||||
get() = row.key
|
||||
|
||||
override val seq: Long
|
||||
get() = row.startSeq
|
||||
|
||||
override val ordinal: Int
|
||||
get() = 0
|
||||
}
|
||||
|
||||
/** One markdown block of a settled reply. */
|
||||
data class Block(
|
||||
override val seq: Long,
|
||||
override val ordinal: Int,
|
||||
val text: String,
|
||||
override val gap: Dp,
|
||||
) : TranscriptUnit() {
|
||||
override val key: Any
|
||||
get() = "b$seq:$ordinal"
|
||||
}
|
||||
|
||||
/** One memory note of a settled reply; see [MemoryNote]. */
|
||||
data class Memory(
|
||||
override val seq: Long,
|
||||
override val ordinal: Int,
|
||||
val part: MessagePart.Remembered,
|
||||
override val gap: Dp,
|
||||
) : TranscriptUnit() {
|
||||
override val key: Any
|
||||
get() = "m$seq:$ordinal"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows flattened into list units, newest first -- index zero is the item at the bottom of the
|
||||
* screen, which is what a reversed lazy list calls the start.
|
||||
*
|
||||
* Every settled reply is cut into its blocks ([markdownBlocks], via the caches on [replies] so a
|
||||
* message is only ever split once). The reply still arriving -- the last row -- stays whole: its
|
||||
* text changes with every delta, and splitting it here would parse the whole message per delta on
|
||||
* whichever thread is composing. [AssistantMessage]'s own streaming path already parses deltas off
|
||||
* the main thread and gives the live message a layer per block.
|
||||
*
|
||||
* Runs per fold, so it must stay proportional to what is loaded with no parsing in it on the warm
|
||||
* path: [ParsedReplies.partsOf] and [ParsedReplies.blocksOf] are lookups for any text [warm] has
|
||||
* seen, and a miss -- the one message that just finished streaming -- costs its split exactly once.
|
||||
*/
|
||||
fun transcriptUnits(rows: List<TranscriptRow>, replies: ParsedReplies): List<TranscriptUnit> {
|
||||
val units = ArrayList<TranscriptUnit>(rows.size)
|
||||
rows.forEachIndexed { index, row ->
|
||||
val rowGap = if (index == 0) 0.dp else TRANSCRIPT_SPACING
|
||||
val item = (row as? TranscriptRow.Single)?.item
|
||||
if (item is TranscriptItem.AssistantMsg && index != rows.lastIndex) {
|
||||
var ordinal = 0
|
||||
fun gap() = if (ordinal == 0) rowGap else BLOCK_SPACING
|
||||
replies.partsOf(item.text).forEach { part ->
|
||||
when (part) {
|
||||
is MessagePart.Prose ->
|
||||
replies.blocksOf(part.text).forEach { block ->
|
||||
units += TranscriptUnit.Block(row.startSeq, ordinal, block, gap())
|
||||
ordinal++
|
||||
}
|
||||
is MessagePart.Remembered -> {
|
||||
units += TranscriptUnit.Memory(row.startSeq, ordinal, part, gap())
|
||||
ordinal++
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
units += TranscriptUnit.Whole(row, rowGap)
|
||||
}
|
||||
}
|
||||
units.reverse()
|
||||
return units
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the unit named by a saved position sits in [units], or null if its row is not loaded.
|
||||
*
|
||||
* The row is found by [seq] and the unit within it by [ordinal], settling for the nearest older
|
||||
* unit when the exact one is gone -- a reply regrouped by a page boundary can split into a
|
||||
* different number of blocks than it had when the position was saved, and "a little above where
|
||||
* they stopped" loses less than the newest end does.
|
||||
*/
|
||||
fun unitIndexFor(units: List<TranscriptUnit>, seq: Long, ordinal: Int): Int? {
|
||||
var best: Int? = null
|
||||
var bestOrdinal = -1
|
||||
units.forEachIndexed { index, unit ->
|
||||
if (unit.seq == seq && unit.ordinal <= ordinal && unit.ordinal > bestOrdinal) {
|
||||
best = index
|
||||
bestOrdinal = unit.ordinal
|
||||
}
|
||||
}
|
||||
return best ?: units.indexOfFirst { it.seq == seq }.takeIf { it >= 0 }
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import java.time.OffsetDateTime
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Window bars for the account's rate limits, with reset times.
|
||||
*
|
||||
* A dialog rather than a screen. Usage is something you check *against* what you were reading --
|
||||
* "can I start this" is asked with the transcript still on screen -- and pushing a whole screen for
|
||||
* it took the session away to answer a question about the session. It also has no navigation of its
|
||||
* own: there is nothing here to open, so the only thing its Back could ever have meant was "put
|
||||
* this away", which is what dismissing does. The system back gesture dismisses it, since a `Dialog`
|
||||
* handles that itself.
|
||||
*/
|
||||
@Composable
|
||||
fun UsageDialog(settings: ServerSettings, onDismiss: () -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf<LoadState<List<UsageSnapshot>>>(LoadState.Loading) }
|
||||
|
||||
fun refresh() {
|
||||
state = LoadState.Loading
|
||||
scope.launch {
|
||||
state =
|
||||
try {
|
||||
withContext(Dispatchers.IO) { LoadState.Loaded(fetchUsage(settings)) }
|
||||
} catch (e: ApiException) {
|
||||
LoadState.failed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { refresh() }
|
||||
|
||||
// A plain Dialog rather than an AlertDialog, for the spacing alone. AlertDialog fixes the
|
||||
// gaps between its title, its content and its buttons at sizes meant for a sentence of prose
|
||||
// and a decision; this is a dense read-out, and those gaps left a band of empty dialog above
|
||||
// Close that was taller than a bar. Everything else here is what AlertDialog would have
|
||||
// drawn -- the same container colour, the same corner -- so nothing about it looks foreign.
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = MaterialTheme.shapes.extraLarge,
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
) {
|
||||
Column(Modifier.padding(horizontal = 24.dp, vertical = 16.dp)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
// Deliberately not subtitled with the provider this was opened from. These
|
||||
// numbers belong to an account on a particular machine, reported by whichever
|
||||
// paid service answered there -- naming the session's provider here made an
|
||||
// echo session's screen read "echo" above a line reading "claude", which is a
|
||||
// claim about echo that nothing measured. Each machine names itself and the
|
||||
// service it came from, which is the true scope.
|
||||
Text(
|
||||
"Usage",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
GlyphButton(REFRESH_GLYPH, "Refresh usage", { refresh() })
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
// Scrolls rather than being trimmed: a machine can report any number of windows
|
||||
// and there can be any number of machines, and a dialog is the one place where
|
||||
// running out of room is silent. `fill = false` so a short read-out keeps a short
|
||||
// dialog instead of stretching to the window.
|
||||
Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) {
|
||||
UsageBody(state)
|
||||
}
|
||||
TextButton(onClick = onDismiss, modifier = Modifier.align(Alignment.End)) {
|
||||
Text("Close")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What came back, or why nothing did. Split out so the dialog above reads as its own shape. */
|
||||
@Composable
|
||||
private fun UsageBody(state: LoadState<List<UsageSnapshot>>) {
|
||||
Column {
|
||||
when (val current = state) {
|
||||
is LoadState.Loading -> CircularProgressIndicator()
|
||||
is LoadState.Error -> Text(current.message, color = MaterialTheme.colorScheme.error)
|
||||
is LoadState.Loaded ->
|
||||
if (current.value.isEmpty()) {
|
||||
// Not an error and not a blank screen: no machine offers a paid service,
|
||||
// so there is genuinely nothing to report and saying so is the answer.
|
||||
Text(
|
||||
"No machine here runs anything with usage limits.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
// No card around each machine. A card is a step up the surface ladder, and
|
||||
// inside a dialog -- itself a raised surface -- the step barely renders while
|
||||
// costing 16dp of padding on every side. What separates one machine from the
|
||||
// next is the line naming it, which is enough for a list this short.
|
||||
current.value.forEachIndexed { index, snapshot ->
|
||||
if (index > 0) {
|
||||
Spacer(Modifier.height(20.dp))
|
||||
}
|
||||
// Machine and service on one line: which account these numbers belong to
|
||||
// is decided by both together, and stacked as a heading over a subtitle
|
||||
// they read as a section of their own rather than as the label they are.
|
||||
// Small and quiet, because the numbers below are what somebody opened
|
||||
// this to see.
|
||||
Text(
|
||||
"${snapshot.setupName.ifEmpty { snapshot.setup }} · ${snapshot.provider}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SnapshotState(snapshot)
|
||||
snapshot.windows.forEachIndexed { windowIndex, window ->
|
||||
// Between the bars, not after the last one: a trailing gap here is
|
||||
// what put a band of empty dialog above the Close button.
|
||||
if (windowIndex > 0) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
WindowBar(window)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Anything other than numbers: why this machine has none.
|
||||
*
|
||||
* The distinction the old single message could not draw. A machine nobody has logged in on is
|
||||
* working exactly as somebody set it up, so it reads as a plain statement -- marking it would be
|
||||
* the interface nagging about a decision already made, and would dilute the marks that do mean
|
||||
* something. Only the two faults are coloured as faults.
|
||||
*/
|
||||
@Composable
|
||||
private fun SnapshotState(snapshot: UsageSnapshot) {
|
||||
when (snapshot.state) {
|
||||
"ok" -> {}
|
||||
"notLoggedIn" ->
|
||||
Text(
|
||||
"No Claude account on this machine.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
// Reached but refused, versus never reached at all: different things to go and do,
|
||||
// so they say different things rather than sharing one "unavailable".
|
||||
"failed" ->
|
||||
Text(
|
||||
snapshot.detail ?: "Couldn't read the limits from this machine.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = failedColor,
|
||||
)
|
||||
else ->
|
||||
Text(
|
||||
snapshot.detail ?: "Couldn't reach this machine.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = failedColor,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WindowBar(window: UsageWindow) {
|
||||
Column {
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
window.label + if (window.active) " (active)" else "",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text("${window.percent.toInt()}%", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
LinearProgressIndicator(
|
||||
progress = { (window.percent / 100.0).toFloat().coerceIn(0f, 1f) },
|
||||
color = quotaColor(window.percent),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
resetLine(window)?.let {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "resets in 3h 12m" -- close enough for deciding whether to start a big task -- or nothing.
|
||||
*
|
||||
* Null for a window that is not running, which is the case this row has always drawn as nothing and
|
||||
* is right to: there is no end to report. What it used to get wrong is the other missing case, a
|
||||
* timestamp that arrived and could not be read: that was printed raw, so a parse failure appeared
|
||||
* as an ISO string in the middle of a sentence written for a person. Both cases are named in
|
||||
* [WindowEnd], and the session bar words them the same way.
|
||||
*/
|
||||
private fun resetLine(window: UsageWindow): String? =
|
||||
when (val end = windowEnd(window.resetsAt, OffsetDateTime.now())) {
|
||||
WindowEnd.NotRunning -> null
|
||||
WindowEnd.Unreadable -> "reset time unreadable"
|
||||
is WindowEnd.Ends ->
|
||||
if (end.until.isNegative) "resets soon" else "resets in ${formatSpan(end.until)}"
|
||||
}
|
||||
Reference in new issue
Block a user