feat(agent): compact composer, plan go or revise, usage limits, diffs and send now (#2531)

* fix(runtime): the userland resolver survives a crash mid-write

* feat(agent): compact composer, plan go or revise, usage limits, diffs and send now
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-12 12:21:36 -05:00
1 parent 76f0c51235
commit dacfee64ab
11 files changed
+874 -166

No files matched your search

@@ -74,7 +74,11 @@ object AgentChats {
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
entry.usage?.let { put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens) }
if (entry.planned) put("planned", true)
entry.usage?.let {
put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens)
if (it.context > 0) put("ctx", it.context).put("win", it.window)
}
}
}.toString()
@@ -105,7 +109,8 @@ object AgentChats {
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
o.has("finished") -> Entry.Finished(
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out")) else null,
if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out"), o.optLong("ctx"), o.optLong("win")) else null,
o.optBoolean("planned"),
)
else -> null
}
@@ -31,6 +31,8 @@ interface AgentHarness {
fun parse(line: String): AgentEvent?
/** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */
fun prepare(rootfs: File) {}
/** Context and plan limits the CLI keeps on disk rather than printing, read once a turn of [conversation] is done. */
fun usage(rootfs: File, conversation: String?): AgentEvent? = null
data class Model(val id: String, val label: String)
@@ -50,6 +52,9 @@ data class AgentEvent(
val thinking: String? = null,
/** Tokens the conversation's context holds after this step. */
val context: Long? = null,
/** Tokens the model's context can hold. */
val window: Long? = null,
val limits: List<AgentHost.Limit>? = null,
val usage: AgentHost.Usage? = null,
)
@@ -139,10 +144,12 @@ object ClaudeCode : AgentHarness {
}
AgentEvent(conversation, results)
}
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
// A resumed session first answers background tasks the last run left behind; that result is not the turn's.
"result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent(
conversation,
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
window = window(o.optJSONObject("modelUsage")),
usage = AgentHost.Usage(
o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0),
o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0,
@@ -153,6 +160,24 @@ object ClaudeCode : AgentHarness {
}
}
private val WINDOW_MINUTES = mapOf("five_hour" to 300, "seven_day" to 10_080)
@VisibleForTesting
internal fun limits(info: JSONObject?): List<AgentHost.Limit>? {
val windows = info?.optJSONObject("unifiedWindows") ?: return null
return WINDOW_MINUTES.mapNotNull { (key, minutes) ->
val w = windows.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(minutes, (w.optDouble("utilization", 0.0) * 100).toInt(), w.optLong("resetsAt"))
}.takeIf { it.isNotEmpty() }
}
/** The context window of the model that did most of the turn; subagents may run a smaller one. */
private fun window(models: JSONObject?): Long? {
models ?: return null
return models.keys().asSequence().mapNotNull { models.optJSONObject(it) }
.maxByOrNull { it.optDouble("costUSD", 0.0) }?.optLong("contextWindow")?.takeIf { it > 0 }
}
private fun resultText(content: Any?): String = when (content) {
is String -> content
is JSONArray -> (0 until content.length()).mapNotNull { i ->
@@ -180,8 +205,8 @@ object ClaudeCode : AgentHarness {
input ?: return ""
return when {
tool == "Bash" -> input.optString("command")
tool == "Edit" -> "${input.optString("file_path")}\n\n- ${input.optString("old_string").replace("\n", "\n- ")}\n\n+ ${input.optString("new_string").replace("\n", "\n+ ")}"
tool == "Write" -> "${input.optString("file_path")}\n\n${input.optString("content")}"
tool == "Edit" -> input.optString("file_path") + "\n" + lineDiff(input.optString("old_string"), input.optString("new_string"))
tool == "Write" -> input.optString("file_path") + "\n" + lineDiff("", input.optString("content"))
tool == "TodoWrite" -> todos(input.optJSONArray("todos"))
else -> input.toString(2)
}
@@ -287,6 +312,33 @@ object Codex : AgentHarness {
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
}
private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\""
/** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */
override fun usage(rootfs: File, conversation: String?): AgentEvent? {
conversation ?: return null
val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") }
.maxByOrNull { it.lastModified() } ?: return null
val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null
return tokenCount(last)
}
@VisibleForTesting
internal fun tokenCount(line: String): AgentEvent? {
val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null
val info = payload.optJSONObject("info")
val rates = payload.optJSONObject("rate_limits")
val limits = listOf("primary", "secondary").mapNotNull { key ->
val w = rates?.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at"))
}
return AgentEvent(
context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 },
window = info?.optLong("model_context_window")?.takeIf { it > 0 },
limits = limits.takeIf { it.isNotEmpty() },
)
}
private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
val items = item.optJSONArray("items") ?: JSONArray()
val text = (0 until items.length()).mapNotNull { i ->
@@ -305,6 +357,28 @@ object Codex : AgentHarness {
@VisibleForTesting
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
private const val DIFF_CONTEXT = 2
/**
* [old] against [new], one line per changed or nearby line, each led by ' ', '-' or '+'. Edits
* replace a short span, so the lines both share at the start and end are cut to [DIFF_CONTEXT].
*/
@VisibleForTesting
internal fun lineDiff(old: String, new: String): String {
val a = if (old.isEmpty()) emptyList() else old.removeSuffix("\n").lines()
val b = if (new.isEmpty()) emptyList() else new.removeSuffix("\n").lines()
var head = 0
while (head < a.size && head < b.size && a[head] == b[head]) head++
var tail = 0
while (tail < a.size - head && tail < b.size - head && a[a.size - 1 - tail] == b[b.size - 1 - tail]) tail++
return buildList {
a.subList(maxOf(0, head - DIFF_CONTEXT), head).forEach { add(" $it") }
a.subList(head, a.size - tail).forEach { add("-$it") }
b.subList(head, b.size - tail).forEach { add("+$it") }
a.subList(a.size - tail, minOf(a.size, a.size - tail + DIFF_CONTEXT)).forEach { add(" $it") }
}.joinToString("\n")
}
private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL)
/** Codex runs each command as `/bin/bash -lc '<command>'`; the command is what the user wants to read. */
@@ -32,10 +32,18 @@ object AgentHost {
/** A tool call; [output] stays null until its result arrives. */
data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null) : Entry
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry
}
data class Usage(val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long)
/** [context] of [window] tokens is what the conversation held when the turn ended. */
data class Usage(
val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long,
val context: Long = 0, val window: Long = 0,
)
/** A plan usage limit over a rolling window of [minutes]; [resetsAt] is in epoch seconds. */
data class Limit(val minutes: Int, val usedPercent: Int, val resetsAt: Long)
/** A message typed while the agent was working, sent when the turn ends. */
data class Queued(val text: String, val files: List<String>)
@@ -103,6 +111,12 @@ object AgentHost {
/** Tokens in the conversation's context after its last step. */
var context by mutableLongStateOf(0L)
private set
/** Tokens the model's context can hold; 0 until a turn has told. */
var window by mutableLongStateOf(0L)
private set
/** The account's plan limits as [harness] last reported them. */
var limits by mutableStateOf<List<Limit>>(emptyList())
private set
var lab by mutableStateOf<LabProgress?>(null)
private set
@@ -119,6 +133,7 @@ object AgentHost {
/** The running Lab build was asked for by the current turn, so stopping the turn stops it. */
private var labFromTurn = false
private var conversation: String? = null
private var turnPlanned = false
private var loaded = false
private var appContext: Context? = null
@@ -136,6 +151,7 @@ object AgentHost {
model = prefs(app).getString(modelKey(harness), null)
effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts }
plan = prefs(app).getBoolean(PLAN_KEY, false)
limits = decodeLimits(prefs(app).getString(limitsKey(harness), null))
available = LinuxRuntime.hasRootfs(app)
installed = harness.files.all { guestFileExists(app, it) }
if (!installed) state = State.MISSING else if (state == State.MISSING) state = State.IDLE
@@ -158,7 +174,9 @@ object AgentHost {
conversation = loaded.conversation
entries.clear()
entries.addAll(loaded.entries)
context = 0
val last = loaded.entries.lastOrNull { it is Entry.Finished && (it.usage?.context ?: 0) > 0 } as? Entry.Finished
context = last?.usage?.context ?: 0
window = last?.usage?.window ?: 0
}
/** Opens a kept conversation, switching to the CLI it belongs to. */
@@ -263,11 +281,15 @@ object AgentHost {
AgentHostService.start(app)
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
val command = current.turn(prompt, conversation, AgentHarness.Options(model, plan && current.plans, BRIEF, effort))
turnPlanned = plan && current.plans
val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort))
val workdir = workspace(app)
var threadConversation = conversation
Thread({
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
runCatching { AgentSetup.installHelpers(app) }
// Without a session nothing else keeps the userland's resolver current.
runCatching { com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent(app, LinuxRuntime.rootDir(app)).publish() }
val child = try {
guest(app, command, workdir).start()
} catch (e: Exception) {
@@ -288,8 +310,12 @@ object AgentHost {
runCatching {
child.inputStream.bufferedReader().forEachLine { line ->
runCatching { raw?.apply { write(line); newLine(); flush() } }
val event = current.parse(line) ?: return@forEachLine
if (event.entries.any { it is Entry.Finished }) ended = true
val parsed = current.parse(line) ?: return@forEachLine
parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished }
if (done) ended = true
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
?.let { parsed.copy(context = it.context ?: parsed.context, window = it.window ?: parsed.window, limits = it.limits ?: parsed.limits) } ?: parsed
main.post { if (turn === started) apply(app, event) }
}
}
@@ -323,6 +349,16 @@ object AgentHost {
queue.remove(item)
}
/** Sends [item] now: the running turn stops where it is, and the rest of the queue waits for the next one. */
fun sendNow(context: Context, item: Queued) {
val app = context.applicationContext
if (!queue.remove(item)) return
val rest = queue.toList()
stop(app)
queue.addAll(rest)
send(app, item.text, item.files)
}
/** Starts a new conversation; the current one stays in the history. */
fun forget(context: Context) {
stop(context)
@@ -331,6 +367,7 @@ object AgentHost {
chat = null
conversation = null
this.context = 0
window = 0
prefs(context).edit().remove(CHAT_KEY).apply()
state = if (installed) State.IDLE else State.MISSING
}
@@ -380,6 +417,11 @@ object AgentHost {
event.text?.let { live += it }
event.thinking?.let { liveThinking += it }
event.context?.let { context = it }
event.window?.let { window = it }
event.limits?.let { reported ->
limits = (limits.filter { old -> reported.none { it.minutes == old.minutes } } + reported).sortedBy { it.minutes }
prefs(app).edit().putString(limitsKey(harness), encodeLimits(limits)).apply()
}
for (entry in event.entries) when (entry) {
is Entry.Finished -> finish(app, entry.error, usage = event.usage)
else -> {
@@ -397,7 +439,8 @@ object AgentHost {
if (!stopped) labFromTurn = false
live = ""
liveThinking = ""
record(app, Entry.Finished(error, stopped, usage))
val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
state = State.IDLE
unseen = true
failed = error != null
@@ -555,6 +598,18 @@ object AgentHost {
private const val RETRY_MS = 3_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@VisibleForTesting
internal fun encodeLimits(list: List<Limit>) = org.json.JSONArray(list.map {
org.json.JSONObject().put("minutes", it.minutes).put("used", it.usedPercent).put("resets", it.resetsAt)
}).toString()
@VisibleForTesting
internal fun decodeLimits(text: String?): List<Limit> = runCatching {
val a = org.json.JSONArray(text ?: return emptyList())
(0 until a.length()).map { a.getJSONObject(it) }.map { Limit(it.optInt("minutes"), it.optInt("used"), it.optLong("resets")) }
}.getOrDefault(emptyList())
private fun effortKey(harness: AgentHarness) = "effort_${harness.id}"
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
@@ -157,9 +157,7 @@ class LinuxNetworkLinkComponent(
synchronized(lock) {
try {
file.parentFile?.mkdirs()
val staged = File(file.path + ".staged")
staged.writeText(describe(properties, capabilities))
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
replace(file, describe(properties, capabilities))
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network link", e)
}
@@ -241,9 +239,7 @@ class LinuxNetworkLinkComponent(
}
try {
val file = File(rootDir, "etc/droiddeck-network.json")
val staged = File(file.path + ".staged")
staged.writeText(state.toString())
if (!staged.renameTo(file)) throw IOException("Could not replace network state")
replace(file, state.toString())
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network state", e)
}
@@ -272,6 +268,19 @@ class LinuxNetworkLinkComponent(
return Pair(servers.sortedWith(order), gateways.sortedWith(order))
}
/**
* Writes [text] to [file] through a staged copy. The copy is synced before the rename, or a
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
*/
private fun replace(file: File, text: String) {
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
private fun writeResolver(properties: LinkProperties?) {
val own = properties?.dnsServers.orEmpty()
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
@@ -286,9 +295,7 @@ class LinuxNetworkLinkComponent(
}
try {
val etc = File(rootDir, "etc")
val staged = File(etc, "resolv.conf.staged")
staged.writeText(text)
if (!staged.renameTo(File(etc, "resolv.conf"))) throw IOException("Could not replace resolv.conf")
replace(File(etc, "resolv.conf"), text)
val hosts = File(etc, "hosts")
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
@@ -29,6 +29,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -39,6 +40,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
@@ -57,7 +59,7 @@ import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
@Composable
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false) {
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, onRevise: () -> Unit = {}) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
when (entry) {
@@ -72,12 +74,66 @@ internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false) {
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running)
is Entry.Result -> Unit
is Entry.Finished -> if (last && AgentHost.answerless(AgentHost.entries)) AgentNoReply() else AgentTurnEnd(entry)
is Entry.Finished -> when {
last && AgentHost.answerless(AgentHost.entries) -> AgentNoReply()
last && entry.planned -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AgentTurnEnd(entry, changes)
AgentPlanActions(onRevise)
}
else -> AgentTurnEnd(entry, changes)
}
}
}
/** A plan turn changed nothing; Go carries the plan out with plan mode off, Revise asks for another. */
@Composable
private fun AgentTurnEnd(entry: Entry.Finished) {
private fun AgentPlanActions(onRevise: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val go = stringResource(R.string.agent_plan_go_message)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
PrimaryButton(stringResource(R.string.agent_plan_go), compact = true, modifier = Modifier.testTag("agent-plan-go")) {
AgentHost.choosePlan(context, false)
AgentHost.send(context, go)
}
SecondaryButton(stringResource(R.string.agent_plan_revise), compact = true, modifier = Modifier.testTag("agent-plan-revise")) {
AgentHost.choosePlan(context, true)
onRevise()
}
Text(stringResource(R.string.agent_plan_untouched), fontSize = 12.sp, color = pal.onSurfaceVariant)
}
}
/** What a turn's edits added up to: files touched and lines added and removed. */
internal data class Changes(val files: Int, val added: Int, val removed: Int)
/** The edits of the turn that ends at [end], or null when it changed no file. */
internal fun turnChanges(entries: List<Entry>, end: Int): Changes? {
val start = entries.subList(0, end).indexOfLast { it is Entry.Asked }
// Plan mode saves its plan as a file of its own, which is not a change to anything.
val edits = entries.subList(start + 1, end).filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }
.filter { !it.path.contains("/.claude/plans/") }
if (edits.isEmpty()) return null
return Changes(edits.map { it.path }.distinct().size, edits.sumOf { it.added }, edits.sumOf { it.removed })
}
internal class Diff(val path: String, val lines: List<String>) {
val added = lines.count { it.startsWith("+") }
val removed = lines.count { it.startsWith("-") }
}
/** The diff an Edit or Write carries: its path, then lines led by ' ', '-' or '+'. */
internal fun diffOf(entry: Entry.Used): Diff? {
if (entry.tool != "Edit" && entry.tool != "Write") return null
val lines = entry.input.lines()
val body = lines.drop(1).filter { it.isNotEmpty() }
if (lines.first().isBlank() || body.isEmpty() || body.any { it[0] != ' ' && it[0] != '-' && it[0] != '+' }) return null
if (body.none { it[0] != ' ' }) return null
return Diff(lines.first(), body)
}
@Composable
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val text = when {
@@ -90,10 +146,19 @@ private fun AgentTurnEnd(entry: Entry.Finished) {
if (u.inputTokens > 0 || u.outputTokens > 0) add(stringResource(R.string.agent_tokens, tokens(u.inputTokens), tokens(u.outputTokens)))
}.joinToString(" · ")
}
} ?: return
if (text.isEmpty()) return
Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp))
}
if (text.isNullOrEmpty() && changes == null) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
if (changes != null) Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
) {
Text(pluralStringResource(R.plurals.agent_files_changed, changes.files, changes.files), fontSize = 12.sp, color = pal.onSurfaceVariant)
Text("+${changes.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good)
Text("−${changes.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error)
}
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant)
}
}
@Composable
@@ -105,7 +170,11 @@ private fun AgentNoReply() {
}
}
internal fun tokens(n: Long) = if (n >= 1000) "${n / 1000}k" else n.toString()
internal fun tokens(n: Long) = when {
n >= 1_000_000 -> if (n % 1_000_000 == 0L) "${n / 1_000_000}M" else String.format(java.util.Locale.US, "%.1fM", n / 1_000_000.0)
n >= 1000 -> "${n / 1000}k"
else -> n.toString()
}
@Composable
internal fun AgentThought(text: String, live: Boolean) {
@@ -149,12 +218,13 @@ private fun AgentTodos(list: String) {
}
}
/** A tool call: one line with its status, opening to the full input and output. */
/** A tool call: one line with its status, opening to the full input and output, or to the diff of an edit. */
@Composable
private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) }
val diff = remember(entry.input) { diffOf(entry) }
Column(
Modifier.fillMaxWidth().padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).animateContentSize(),
) {
@@ -171,11 +241,19 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
}
}
Text(entry.tool, fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, modifier = Modifier.padding(start = 8.dp))
Text(entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
Text(diff?.path?.substringAfterLast('/') ?: entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(start = 8.dp))
if (diff != null) {
Text("+${diff.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good, modifier = Modifier.padding(start = 8.dp))
Text("\u2212${diff.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error, modifier = Modifier.padding(start = 6.dp, end = 4.dp))
}
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (open && diff != null) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (diff.path.contains('/')) Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
if (entry.failed && !entry.output.isNullOrBlank()) CodeBox(stringResource(R.string.agent_tool_output), entry.output, colors.error)
} else if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (entry.input.isNotBlank()) CodeBox(stringResource(R.string.agent_tool_input), entry.input, colors.onSurface)
when {
entry.output == null && running -> Text(stringResource(R.string.agent_tool_running), fontSize = 12.sp, color = pal.onSurfaceVariant)
@@ -187,6 +265,30 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
}
}
@Composable
private fun DiffBox(diff: Diff) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
Modifier.fillMaxWidth().heightIn(max = 360.dp).clip(Shape12).background(colors.surface)
.verticalScroll(rememberScrollState()).padding(vertical = 6.dp),
) {
for (line in diff.lines) {
val tint = when (line[0]) {
'+' -> pal.good
'-' -> colors.error
else -> null
}
Text(
line[0] + " " + line.substring(1),
fontSize = 12.sp, fontFamily = FontFamily.Monospace, lineHeight = 17.sp,
color = tint ?: pal.onSurfaceVariant,
modifier = Modifier.fillMaxWidth().background(tint?.copy(alpha = 0.12f) ?: Color.Transparent).padding(horizontal = 10.dp),
)
}
}
}
@Composable
private fun CodeBox(label: String, text: String, color: Color) {
val pal = LocalPalette.current
@@ -2,13 +2,21 @@ package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.ContextWrapper
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -18,13 +26,13 @@ import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
@@ -34,12 +42,15 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Memory
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Stop
import androidx.compose.material3.CircularProgressIndicator
@@ -51,23 +62,38 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.window.DialogWindowProvider
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
@@ -76,22 +102,33 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogWindowProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
import kotlinx.coroutines.launch
internal enum class AgentPanel { NONE, MODEL, HISTORY, PROCESSES }
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
private const val COMPOSER_SLIDE_MS = 350L
/**
* The chat with the composer at the bottom. The composer is the full editor only while it is
* being typed in; reading shrinks it to one line, and scrolling back through older messages
* hides it behind a small pill. [startTyping] opens an empty conversation ready to type.
*/
@Composable
internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true) {
internal fun AgentPage(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true,
) {
val context = LocalContext.current
val view = LocalView.current
DisposableEffect(view, visible) {
@@ -114,58 +151,115 @@ internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, v
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
Column(modifier.fillMaxSize().imePadding()) {
AgentHeader(panel, { panel = if (panel == it) AgentPanel.NONE else it }, onSetup = { setup = true })
val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) }
val focusManager = LocalFocusManager.current
val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it }
// The keyboard leaves too little height for a panel and the editor together, so typing closes the panel.
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE }
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.typing) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open()
true
},
) {
when (panel) {
AgentPanel.HISTORY -> AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE }
AgentPanel.PROCESSES -> AgentProcessList(Modifier.weight(1f))
AgentPanel.HISTORY -> {
AgentPanelBar(stringResource(R.string.agent_history)) { panel = AgentPanel.NONE }
AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE }
}
AgentPanel.PROCESSES -> {
AgentPanelBar(stringResource(R.string.agent_processes)) { panel = AgentPanel.NONE }
AgentProcessList(Modifier.weight(1f))
}
else -> {
Column(Modifier.weight(1f).clipToBounds()) {
if (panel == AgentPanel.MODEL) AgentModelPicker()
AgentConversation(Modifier.weight(1f))
AgentStatus()
val list = rememberLazyListState()
val scope = rememberCoroutineScope()
// Only dragging back through older messages hides the composer; showing it again shrinks the list, which must not hide it once more.
var readingBack by remember { mutableStateOf(false) }
LaunchedEffect(list) { snapshotFlow { list.canScrollForward }.collect { if (!it) readingBack = false } }
val dragBack = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (source == NestedScrollSource.Drag && available.y > 1f && list.canScrollBackward) readingBack = true
return Offset.Zero
}
}
}
val toLatest: () -> Unit = {
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.typing && readingBack && AgentHost.entries.isNotEmpty()
var wasHidden by remember { mutableStateOf(false) }
LaunchedEffect(hidden) {
if (hidden) wasHidden = true
else if (wasHidden) {
wasHidden = false
// The composer takes its height back as it slides in; the latest message stays above it.
kotlinx.coroutines.delay(COMPOSER_SLIDE_MS)
list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2)
}
}
Box(Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack)) {
AgentConversation(
Modifier.fillMaxSize().pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
if (composer.typing) focusManager.clearFocus()
}
},
list, onRevise = { composer.open() },
)
androidx.compose.animation.AnimatedVisibility(
hidden, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
) {
AgentJumpPill(toLatest)
}
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, inputModifier, panel, togglePanel) { setup = true }
}
AgentComposer(draft, inputModifier) { panel = it }
}
}
}
}
@Composable
private fun AgentHeader(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.rail_agent), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }.padding(vertical = 2.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant)
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), selected = panel == AgentPanel.HISTORY, tag = "agent-history") { onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), selected = panel == AgentPanel.PROCESSES, tag = "agent-processes") { onPanel(AgentPanel.PROCESSES) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), tag = "agent-new") {
AgentHost.forget(context)
if (panel != AgentPanel.NONE) onPanel(panel)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, tag = "agent-settings", onClick = onSetup)
/** Whether the composer is the full editor; [open] also puts the cursor in it. */
@Stable
private class ComposerState(typing: Boolean) {
var typing by mutableStateOf(typing)
var focusRequests by mutableIntStateOf(0)
private set
/** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */
var opening = false
fun open() {
typing = true
opening = true
focusRequests++
}
}
@Composable
internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, onClick: () -> Unit) {
private fun AgentPanelBar(title: String, onClose: () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) {
Text(title, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f))
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 36.dp, tag = "agent-panel-close", onClick = onClose)
}
}
@Composable
internal fun HeaderAction(
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit,
) {
val pal = LocalPalette.current
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 8.dp).size(44.dp).clip(Shape12)
modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.clickable(enabled = enabled, onClick = onClick)
.then(if (tag != null) Modifier.testTag(tag) else Modifier),
@@ -174,18 +268,21 @@ internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = t
selected -> pal.primary
enabled -> pal.onBackground
else -> pal.onSurfaceVariant.copy(alpha = 0.5f)
}, modifier = Modifier.size(22.dp))
}, modifier = Modifier.size(if (size < 44.dp) 19.dp else 22.dp))
}
}
@Composable
private fun AgentConversation(modifier: Modifier) {
private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise: () -> Unit) {
val pal = LocalPalette.current
val list = rememberLazyListState()
val working = AgentHost.state == AgentHost.State.WORKING
val atBottom by remember { derivedStateOf { !list.canScrollForward } }
val items = AgentHost.entries.size + (if (working) 1 else 0)
LaunchedEffect(items) { if (items > 0) list.animateScrollToItem(items - 1) }
LaunchedEffect(items) {
if (items == 0) return@LaunchedEffect
list.animateScrollToItem(items - 1)
list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
@@ -201,12 +298,31 @@ private fun AgentConversation(modifier: Modifier) {
LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(AgentHost.entries.size) { i ->
val entry = AgentHost.entries[i]
AgentEntry(entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex)
AgentEntry(
entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex,
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null, onRevise = onRevise,
)
}
if (working) item { AgentLive() }
}
}
/** Where the composer was, while it is hidden for reading back: what the agent is doing, and the way to the latest message. */
@Composable
private fun AgentJumpPill(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.clip(CircleShape).background(colors.surface).border(1.dp, pal.line, CircleShape)
.clickable(onClick = onClick).padding(horizontal = 14.dp, vertical = 8.dp).testTag("agent-latest"),
) {
if (AgentHost.state == AgentHost.State.WORKING) CircularProgressIndicator(Modifier.size(13.dp), strokeWidth = 2.dp, color = pal.primary)
Text(stringResource(if (AgentHost.state == AgentHost.State.WORKING) R.string.agent_working_short else R.string.agent_latest), fontSize = 13.sp, color = pal.onSurfaceVariant)
Icon(Icons.Outlined.ArrowDownward, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
/** The reply being written, and what the agent is doing right now. */
@Composable
private fun AgentLive() {
@@ -235,65 +351,41 @@ internal fun clock(seconds: Long): String {
}
}
/** Above the composer: a Lab build's progress, the todo item in progress, and queued messages. */
@Composable
private fun AgentStatus() {
private fun AgentLabCard() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val lab = AgentHost.lab
if (lab != null) {
var armed by remember(lab.pid) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(top = 10.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(
stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " · " + labStage(lab),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground,
)
val facts = buildList {
if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}")
add(clock(lab.elapsedSeconds.toLong()))
if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong())))
}
Text(facts.joinToString(" · "), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) {
if (armed) AgentHost.cancelLabBuild(context) else armed = true
}
}
if (lab.running) {
LinearProgressIndicator(
progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape),
val lab = AgentHost.lab ?: return
var armed by remember(lab.pid) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(
stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " · " + labStage(lab),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground,
)
if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
val facts = buildList {
if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}")
add(clock(lab.elapsedSeconds.toLong()))
if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong())))
}
Text(facts.joinToString(" · "), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) {
if (armed) AgentHost.cancelLabBuild(context) else armed = true
}
}
}
val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() }
if (AgentHost.state == AgentHost.State.WORKING && !todos.isNullOrEmpty()) {
val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") }
val done = todos.count { it.startsWith("[x]") }
if (doing != null) Text(
"${doing.drop(4)} · $done/${todos.size}", fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 8.dp, start = 4.dp),
)
}
for (queued in AgentHost.queue) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(start = 12.dp),
) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clickable { AgentHost.unqueue(queued) }) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (lab.running) {
LinearProgressIndicator(
progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape),
)
if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
}
}
}
@@ -308,13 +400,99 @@ private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab.
else -> stringResource(R.string.agent_lab_stage_starting)
}
private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null
/** The todo item in progress and how many are done, while the agent works through a list. */
private fun currentTodo(): String? {
if (AgentHost.state != AgentHost.State.WORKING) return null
val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() }.orEmpty()
val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") } ?: return null
return "${todos.count { it.startsWith("[x]") }}/${todos.size} · ${doing.drop(4)}"
}
/** A Lab build, the todo item in progress and queued messages, one chip each. */
@Composable
private fun AgentComposer(draftState: MutableState<String>, inputModifier: Modifier, onPanel: (AgentPanel) -> Unit) {
private fun AgentActivity(labOpen: Boolean, onLab: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
AgentHost.lab?.let { lab ->
AgentChip(selected = labOpen, warn = lab.failed, tag = "agent-lab-chip", onClick = onLab) {
Icon(Icons.Outlined.Build, null, tint = if (lab.failed) AttentionAmber else pal.onSurfaceVariant, modifier = Modifier.size(14.dp))
Text(labStage(lab), fontSize = 12.5.sp, color = if (lab.failed) AttentionAmber else pal.onSurfaceVariant, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 160.dp))
}
}
currentTodo()?.let { todo ->
AgentChip {
Text(todo, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 220.dp))
}
}
for (queued in AgentHost.queue) AgentChip(warn = true) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 12.5.sp, color = AttentionAmber, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 180.dp))
Text(
stringResource(R.string.agent_send_now), fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.onPrimary,
modifier = Modifier.clip(Shape12).background(pal.primary).clickable { AgentHost.sendNow(context, queued) }
.padding(horizontal = 8.dp, vertical = 3.dp).testTag("agent-send-now"),
)
Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant,
modifier = Modifier.size(22.dp).clip(CircleShape).clickable { AgentHost.unqueue(queued) }.padding(3.dp))
}
}
@Composable
private fun AgentChip(selected: Boolean = false, warn: Boolean = false, tag: String? = null, onClick: (() -> Unit)? = null, content: @Composable () -> Unit) {
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.height(30.dp).clip(Shape12)
.background(if (warn) AttentionAmber.copy(alpha = 0.14f) else if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
.then(if (tag != null) Modifier.testTag(tag) else Modifier)
.padding(horizontal = 9.dp),
) { content() }
}
/** How full the context is, or failing that the plan limit nearest its end; amber when little is left. */
@Composable
private fun ContextRing(tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
val percent = usagePercent() ?: return
val warn = percent >= 80
val tint = if (warn) AttentionAmber else pal.primary
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.height(30.dp).clip(Shape12).clickable(onClick = onClick).padding(horizontal = 6.dp).testTag(tag),
) {
val track = pal.line
Canvas(Modifier.size(16.dp)) {
val stroke = Stroke(width = 2.5.dp.toPx(), cap = StrokeCap.Round)
drawArc(track, 0f, 360f, false, style = stroke)
drawArc(tint, -90f, 360f * percent / 100f, false, style = stroke)
}
Text("$percent%", fontSize = 12.5.sp, color = if (warn) AttentionAmber else pal.onSurfaceVariant)
}
}
/** The context's fill, unless a plan limit is nearly reached: that is the wall the user meets first. */
internal fun usagePercent(): Int? {
val limit = AgentHost.limits.maxOfOrNull { liveUsed(it) }
val context = if (AgentHost.window > 0 && AgentHost.context > 0) (AgentHost.context * 100 / AgentHost.window).toInt().coerceIn(0, 100) else null
return if (limit != null && (limit >= 90 || context == null)) maxOf(limit, context ?: 0) else context
}
/** A limit whose window has passed since it was reported is back to nothing used. */
internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.resetsAt * 1000 < System.currentTimeMillis()) 0 else limit.usedPercent
@Composable
private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit,
) {
val context = LocalContext.current
var draft by draftState
val working = AgentHost.state == AgentHost.State.WORKING
var labOpen by rememberSaveable { mutableStateOf(false) }
if (AgentHost.lab == null) labOpen = false
var hadFocus by remember { mutableStateOf(false) }
val send = send@{
val text = draft.trim()
when (text.substringBefore(' ')) {
@@ -332,11 +510,84 @@ private fun AgentComposer(draftState: MutableState<String>, inputModifier: Modif
}
draft = ""
}
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
// Leaving the composer for the conversation, by touch or D-pad, is reading.
Column(
Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp).onFocusChanged {
if (it.hasFocus) hadFocus = true
else if (hadFocus) {
hadFocus = false
if (composer.typing && !composer.opening) composer.typing = false
}
},
) {
if (labOpen) AgentLabCard()
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(top = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(top = 8.dp)) { AgentUsage() }
else -> Unit
}
if (composer.typing) {
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, inputModifier, panel, onPanel, onSetup, send)
} else AgentReadingBar(composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }) { onPanel(AgentPanel.USAGE) }
}
}
/** The composer while reading: one line holding what is going on, opened by a press or by Y. */
@Composable
private fun AgentReadingBar(
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
var focused by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16)
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable { composer.open() }.testTag("agent-composer-bar")
.padding(start = 14.dp, end = 4.dp),
) {
Text(
draft.ifBlank { stringResource(if (working) R.string.agent_hint_working else R.string.agent_message) }, fontSize = 15.sp,
color = if (draft.isBlank()) pal.onSurfaceVariant else colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = !hasActivity()).widthIn(min = 72.dp),
)
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).padding(start = 8.dp).horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen, onLab) }
ContextRing("agent-usage-bar", onUsage)
if (working) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 4.dp).size(36.dp).clip(CircleShape).background(pal.error.copy(alpha = 0.22f))
.clickable { AgentHost.stop(context) }.testTag("agent-stop"),
) { Icon(Icons.Outlined.Stop, stringResource(R.string.agent_stop), tint = colors.error, modifier = Modifier.size(20.dp)) }
}
}
/** The full editor: model and usage on top, the text with attach, stop and send under them. */
@Composable
private fun AgentEditor(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
onSetup: () -> Unit, send: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var draft by draftState
val working = AgentHost.state == AgentHost.State.WORKING
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
if (matches.isNotEmpty()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) {
for (command in matches) Text(
command, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = pal.primary,
@@ -346,42 +597,77 @@ private fun AgentComposer(draftState: MutableState<String>, inputModifier: Modif
}
if (AgentAttachments.pending.isNotEmpty()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) {
for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) }
}
var focused by remember { mutableStateOf(false) }
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = if (keyboardOpen) 4.dp else 16.dp).clip(Shape16).background(colors.surface)
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
var menu by rememberSaveable { mutableStateOf(false) }
val field = remember { FocusRequester() }
LaunchedEffect(composer.focusRequests) { if (composer.focusRequests > 0) runCatching { field.requestFocus() } }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 11.dp, bottom = 11.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
BasicTextField(
draft, { draft = it },
Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
minLines = 1,
maxLines = 8,
)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) {
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f, fill = false).height(30.dp).clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }
.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
if (menu) {
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 32.dp, tag = "agent-history") { menu = false; onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 32.dp, tag = "agent-processes") { menu = false; onPanel(AgentPanel.PROCESSES) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 32.dp, tag = "agent-new") {
menu = false
AgentHost.forget(context)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 32.dp, tag = "agent-settings") {
menu = false
onSetup()
}
}
HeaderAction(if (menu) Icons.Outlined.Close else Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), size = 32.dp, tag = "agent-menu") { menu = !menu }
}
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
Row(verticalAlignment = Alignment.Bottom) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
BasicTextField(
draft, { draft = it },
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
if (it.isFocused) composer.opening = false
}.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
minLines = 1,
maxLines = 8,
)
}
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) { send() }
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) { send() }
}
}
@@ -411,9 +697,9 @@ private fun RoundButton(
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 6.dp).size(46.dp).clip(CircleShape).background(background)
modifier = Modifier.padding(start = 6.dp).size(42.dp).clip(CircleShape).background(background)
.clickable(enabled = enabled, onClick = onClick).testTag(tag),
) {
Icon(icon, label, tint = tint, modifier = Modifier.size(22.dp))
Icon(icon, label, tint = tint, modifier = Modifier.size(21.dp))
}
}
@@ -14,10 +14,12 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -190,3 +192,71 @@ internal fun AgentProcessList(modifier: Modifier) {
}
}
}
/** How full the conversation's context is, how much of the plan's limits is used, and what this conversation cost. */
@Composable
internal fun AgentUsage() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (AgentHost.window > 0) UsageRow(
stringResource(R.string.agent_usage_context),
stringResource(R.string.agent_usage_of, tokens(AgentHost.context), tokens(AgentHost.window)),
(AgentHost.context.toFloat() / AgentHost.window).coerceIn(0f, 1f),
)
for (limit in AgentHost.limits) {
val used = liveUsed(limit)
val label = when {
limit.minutes in 9_000..11_000 -> stringResource(R.string.agent_limit_week)
limit.minutes >= 60 -> stringResource(R.string.agent_limit_hours, limit.minutes / 60)
else -> stringResource(R.string.agent_limit_minutes, limit.minutes)
}
val value = if (limit.resetsAt * 1000 > System.currentTimeMillis()) stringResource(R.string.agent_limit_resets, used, resetTime(context, limit.resetsAt)) else "$used%"
UsageRow(label, value, used / 100f)
}
val turns = AgentHost.entries.filterIsInstance<AgentHost.Entry.Finished>().mapNotNull { it.usage }
val cost = turns.sumOf { it.costUsd }
val ms = turns.sumOf { it.durationMs }
Row(verticalAlignment = Alignment.CenterVertically) {
val facts = buildList {
if (ms > 0) add(clock(ms / 1000))
if (cost >= 0.005) add("$" + String.format(java.util.Locale.US, "%.2f", cost))
}
Text(
if (facts.isEmpty()) stringResource(R.string.agent_usage_unknown) else stringResource(R.string.agent_usage_conversation, facts.joinToString(" · ")),
fontSize = 12.5.sp, color = pal.onSurfaceVariant, modifier = Modifier.weight(1f),
)
if (AgentHost.harness.plans && AgentHost.entries.isNotEmpty() && AgentHost.state == AgentHost.State.IDLE) {
SecondaryButton("/compact", compact = true) { AgentHost.send(context, "/compact") }
}
}
}
}
@Composable
private fun UsageRow(label: String, value: String, fraction: Float) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 14.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
Text(value, fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
LinearProgressIndicator(
progress = { fraction }, color = if (fraction >= 0.8f) AttentionAmber else pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().height(5.dp).clip(CircleShape),
)
}
}
/** A reset later today shows its time; one further off shows the day too. */
private fun resetTime(context: android.content.Context, epochSeconds: Long): String {
val ms = epochSeconds * 1000
val flags = if (ms - System.currentTimeMillis() < 20 * 3_600_000L) DateUtils.FORMAT_SHOW_TIME
else DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_WEEKDAY or DateUtils.FORMAT_SHOW_TIME
return DateUtils.formatDateTime(context, ms, flags)
}
@@ -558,6 +558,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
inputModifier = focus.track(page, "agent-input"),
visible = open,
startTyping = false,
) else Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)),
) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) {
+22
View File
@@ -1193,6 +1193,28 @@
<string name="agent_remove_attachment">Remove</string>
<string name="agent_model_default">Default</string>
<string name="agent_effort">Reasoning effort</string>
<string name="agent_plan_go">Go</string>
<string name="agent_plan_revise">Revise</string>
<string name="agent_plan_untouched">Nothing changed yet</string>
<string name="agent_plan_go_message">Go ahead with the plan.</string>
<string name="agent_send_now">Send now</string>
<string name="agent_message">Message</string>
<string name="agent_more">More</string>
<string name="agent_close">Close</string>
<string name="agent_latest">Latest</string>
<string name="agent_working_short">Working</string>
<string name="agent_usage_context">Context</string>
<string name="agent_usage_of">%1$s of %2$s</string>
<string name="agent_usage_conversation">This conversation · %1$s</string>
<string name="agent_usage_unknown">Usage shows after the first reply</string>
<string name="agent_limit_hours">%1$d-hour limit</string>
<string name="agent_limit_minutes">%1$d-minute limit</string>
<string name="agent_limit_week">Weekly limit</string>
<string name="agent_limit_resets">%1$d%% · resets %2$s</string>
<plurals name="agent_files_changed">
<item quantity="one">%1$d file</item>
<item quantity="other">%1$d files</item>
</plurals>
<string name="agent_plan">Plan first</string>
<string name="agent_plan_short">Plan</string>
<string name="agent_plan_hint">Proposes a plan without changing anything</string>
@@ -74,7 +74,8 @@ class AgentHostTest {
}
@Test fun claudeShowsWholeEditsAndTodos() {
assertEquals("a.kt\n\n- old\n\n+ new", ClaudeCode.fullInput("Edit", org.json.JSONObject("""{"file_path":"a.kt","old_string":"old","new_string":"new"}""")))
assertEquals("a.kt\n-old\n+new", ClaudeCode.fullInput("Edit", org.json.JSONObject("""{"file_path":"a.kt","old_string":"old","new_string":"new"}""")))
assertEquals("b.kt\n+one\n+two", ClaudeCode.fullInput("Write", org.json.JSONObject("""{"file_path":"b.kt","content":"one\ntwo"}""")))
assertEquals("[x] read\n[~] fix\n[ ] test", ClaudeCode.fullInput("TodoWrite", org.json.JSONObject(
"""{"todos":[{"content":"read","status":"completed"},{"content":"fix","status":"in_progress"},{"content":"test","status":"pending"}]}""")))
}
@@ -164,6 +165,7 @@ class AgentHostTest {
val written = listOf(
Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}"),
Entry.Result("t1", "contents", false), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true),
Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true),
)
written.forEach { AgentChats.append(file, it) }
file.appendText("broken line\n")
@@ -173,6 +175,7 @@ class AgentHostTest {
assertEquals(listOf(
Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}", "contents", false),
Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true),
Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true),
), loaded.entries)
assertEquals(emptyList<Entry>(), AgentChats.read(File(file.path + ".missing")).entries)
}
@@ -208,4 +211,46 @@ class AgentHostTest {
assertTrue(p.running && !p.prepare)
assertEquals(95, p.etaSeconds)
}
@Test fun anEditBecomesALineDiffWithItsNearbyLines() {
assertEquals(" a\n b\n-c\n+C\n+D\n e\n f", lineDiff("x\na\nb\nc\ne\nf\ny", "x\na\nb\nC\nD\ne\nf\ny"))
assertEquals("+only", lineDiff("", "only"))
assertEquals("-gone", lineDiff("gone", ""))
assertEquals("+one\n+two", lineDiff("", "one\ntwo\n"))
}
@Test fun claudeRateLimitsAndContextWindowAreRead() {
val event = ClaudeCode.parse("""{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","unifiedWindows":{"five_hour":{"utilization":0.07,"resetsAt":1794435600},"seven_day":{"utilization":0.85,"resetsAt":1794592800}}},"session_id":"s"}""")!!
assertEquals(listOf(AgentHost.Limit(300, 7, 1794435600), AgentHost.Limit(10_080, 85, 1794592800)), event.limits)
val result = ClaudeCode.parse("""{"type":"result","subtype":"success","is_error":false,"result":"done","usage":{},"modelUsage":{"claude-haiku":{"costUSD":0.01,"contextWindow":200000},"claude-sonnet":{"costUSD":0.7,"contextWindow":1000000}}}""")!!
assertEquals(1_000_000L, result.window)
}
@Test fun codexTokenCountsCarryContextAndLimits() {
val event = Codex.tokenCount("""{"timestamp":"t","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":90000},"last_token_usage":{"total_tokens":41000},"model_context_window":272000},"rate_limits":{"primary":{"used_percent":12.5,"window_minutes":300,"resets_at":1794435600},"secondary":{"used_percent":40.0,"window_minutes":10080,"resets_at":1794592800}}}}""")!!
assertEquals(41_000L, event.context)
assertEquals(272_000L, event.window)
assertEquals(listOf(AgentHost.Limit(300, 12, 1794435600), AgentHost.Limit(10_080, 40, 1794592800)), event.limits)
assertNull(Codex.tokenCount("""{"type":"event_msg","payload":{"type":"agent_message"}}"""))
}
@Test fun codexUsageComesFromTheThreadsSessionLog() {
val root = Files.createTempDirectory("rootfs").toFile()
val log = File(root, "root/.codex/sessions/2026/11/12/rollout-2026-11-12T10-00-00-thread1.jsonl").apply { parentFile!!.mkdirs() }
log.writeText(
"""{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"total_tokens":15692},"model_context_window":258400},"rate_limits":{"primary":{"used_percent":86.0,"window_minutes":10080,"resets_at":1794716485},"secondary":null}}}""" + "\n" +
"""{"type":"response_item","payload":{"type":"additional_tools","tools":[{"description":"reports token_count as it goes"}]}}""" + "\n",
)
val event = Codex.usage(root, "thread1")!!
assertEquals(15_692L, event.context)
assertEquals(258_400L, event.window)
assertEquals(listOf(AgentHost.Limit(10_080, 86, 1794716485)), event.limits)
assertNull(Codex.usage(root, "other"))
}
@Test fun limitsRoundTripThroughPrefs() {
val limits = listOf(AgentHost.Limit(300, 7, 1794435600), AgentHost.Limit(10_080, 85, 1794592800))
assertEquals(limits, AgentHost.decodeLimits(AgentHost.encodeLimits(limits)))
assertEquals(emptyList<AgentHost.Limit>(), AgentHost.decodeLimits("not json"))
}
}
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.agent.AgentHost.Entry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class AgentChangesTest {
@Test fun aTurnAddsUpTheEditsItMade() {
val entries = listOf(
Entry.Asked("before"), Entry.Used("e0", "Edit", "old.kt", "old.kt\n-a\n+b"), Entry.Finished(null),
Entry.Asked("fix it"),
Entry.Used("e1", "Edit", "a.kt", "src/a.kt\n x\n-y\n+z\n+w"),
Entry.Used("e2", "Write", "b.kt", "src/b.kt\n+one"),
Entry.Used("e3", "Edit", "a.kt", "src/a.kt\n-q", failed = true),
Entry.Used("e4", "Edit", "a.kt", "src/a.kt\n-r"),
Entry.Used("b1", "Bash", "ls", "ls"),
Entry.Finished(null),
)
assertEquals(Changes(files = 2, added = 3, removed = 2), turnChanges(entries, entries.lastIndex))
assertEquals(Changes(1, 1, 1), turnChanges(entries, 2))
}
@Test fun onlyEditsCarryingADiffCount() {
assertNull(diffOf(Entry.Used("c", "Edit", "a.kt, b.kt", "a.kt\nb.kt")))
assertNull(diffOf(Entry.Used("b", "Bash", "ls", "ls\n+x")))
assertEquals(2, diffOf(Entry.Used("e", "Edit", "a.kt", "a.kt\n\n- old\n\n+ new"))?.lines?.size)
assertNull(turnChanges(listOf(Entry.Asked("hi"), Entry.Said("hello"), Entry.Finished(null)), 2))
}
@Test fun aSavedPlanIsNotAChange() {
val entries = listOf(Entry.Asked("plan it"), Entry.Used("w", "Write", "plan.md", "/root/.claude/plans/plan.md\n+step"), Entry.Finished(null))
assertNull(turnChanges(entries, 2))
}
@Test fun bigCountsReadAsMillions() {
assertEquals("1M", tokens(1_000_000))
assertEquals("1.5M", tokens(1_500_000))
assertEquals("23k", tokens(23_400))
}
}