mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-25 07:46:01 +00:00
feat(agent): conversation history, model and plan mode, live replies, full tool input and output, processes, attachments, queued messages and a Stop that ends the turn
This commit is contained in:
1 parent
c64a72b2a1
commit
173ffac05b
13 files changed
+1804
-397
No files matched your search
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Files the user attaches to a message, copied into the Linux userland so the agent's own tools
|
||||
* can read them (Claude Code's Read shows images and PDFs to the model).
|
||||
*/
|
||||
object AgentAttachments {
|
||||
/** Guest paths waiting to go with the next message. */
|
||||
val pending = mutableStateListOf<String>()
|
||||
|
||||
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
|
||||
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
|
||||
|
||||
fun hostDir(context: Context) = File(LinuxRuntime.rootDir(context.applicationContext), GUEST_DIR.removePrefix("/"))
|
||||
|
||||
fun host(context: Context, guestPath: String) = File(LinuxRuntime.rootDir(context.applicationContext), guestPath.removePrefix("/"))
|
||||
|
||||
fun isImage(path: String) = path.substringAfterLast('.', "").lowercase() in IMAGE
|
||||
|
||||
/** Copies [uris] for [chat] (or a new conversation) on the calling thread; returns their guest paths. */
|
||||
fun copy(context: Context, chat: String?, uris: List<Uri>): List<String> {
|
||||
val app = context.applicationContext
|
||||
val folder = chat ?: "new"
|
||||
val dir = File(hostDir(app), folder).apply { mkdirs() }
|
||||
return uris.mapNotNull { uri ->
|
||||
runCatching {
|
||||
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
|
||||
var target = File(dir, name)
|
||||
var n = 1
|
||||
while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
|
||||
app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
|
||||
"$GUEST_DIR/$folder/${target.name}"
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** The message the CLI gets: the user's text, then where the attached files are. */
|
||||
fun prompt(text: String, files: List<String>): String {
|
||||
if (files.isEmpty()) return text
|
||||
val list = files.joinToString("\n") { "- $it" }
|
||||
return "$text\n\nAttached files (read them with your tools):\n$list".trim()
|
||||
}
|
||||
|
||||
private fun displayName(context: Context, uri: Uri): String =
|
||||
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: uri.lastPathSegment?.substringAfterLast('/') ?: "file"
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import com.droiddeck.launcher.agent.AgentHost.Entry
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Conversations kept on the device, one JSON Lines file each in `files/agent/chats`: a header
|
||||
* line with the harness, a line with the CLI's conversation id once it has one, then the entries.
|
||||
*/
|
||||
object AgentChats {
|
||||
data class Chat(val id: String, val harness: String, val title: String, val updated: Long)
|
||||
|
||||
class Loaded(val harness: String?, val conversation: String?, val entries: List<Entry>)
|
||||
|
||||
private const val MAX_OUTPUT = 24_000
|
||||
|
||||
fun dir(context: Context) = File(context.filesDir, "agent/chats")
|
||||
|
||||
fun file(context: Context, id: String) = File(dir(context), "$id.jsonl")
|
||||
|
||||
fun newId(context: Context): String {
|
||||
var stamp = System.currentTimeMillis()
|
||||
while (file(context, stamp.toString()).exists()) stamp++
|
||||
return stamp.toString()
|
||||
}
|
||||
|
||||
/** Newest first; chats with nothing asked yet are left out. */
|
||||
fun list(context: Context): List<Chat> = dir(context).listFiles { f -> f.name.endsWith(".jsonl") }.orEmpty()
|
||||
.mapNotNull { f ->
|
||||
val loaded = read(f)
|
||||
val title = loaded.entries.firstNotNullOfOrNull { (it as? Entry.Asked)?.text } ?: return@mapNotNull null
|
||||
Chat(f.name.removeSuffix(".jsonl"), loaded.harness ?: ClaudeCode.id, title.lineSequence().first().take(120), f.lastModified())
|
||||
}
|
||||
.sortedByDescending { it.updated }
|
||||
|
||||
fun delete(context: Context, id: String) {
|
||||
file(context, id).delete()
|
||||
File(AgentAttachments.hostDir(context), id).deleteRecursively()
|
||||
}
|
||||
|
||||
fun start(file: File, harness: String) {
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(JSONObject().put("harness", harness).toString() + "\n")
|
||||
}
|
||||
|
||||
fun appendConversation(file: File, conversation: String) =
|
||||
runCatching { file.appendText(JSONObject().put("conversation", conversation).toString() + "\n") }
|
||||
|
||||
fun append(file: File, entry: Entry) = runCatching { file.appendText(encode(entry) + "\n") }
|
||||
|
||||
/** The transcript before chats were kept, moved into the first chat. */
|
||||
fun migrate(context: Context, harness: String, conversation: String?): String? {
|
||||
val old = File(context.filesDir, "agent/transcript.jsonl")
|
||||
if (!old.isFile) return null
|
||||
val id = newId(context)
|
||||
val target = file(context, id)
|
||||
start(target, harness)
|
||||
conversation?.let { appendConversation(target, it) }
|
||||
target.appendText(old.readText())
|
||||
old.delete()
|
||||
return id
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun encode(entry: Entry): String = when (entry) {
|
||||
is Entry.Asked -> JSONObject().put("asked", entry.text).apply { if (entry.files.isNotEmpty()) put("files", JSONArray(entry.files)) }
|
||||
is Entry.Said -> JSONObject().put("said", entry.text)
|
||||
is Entry.Thought -> JSONObject().put("thought", entry.text)
|
||||
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
|
||||
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) }
|
||||
}
|
||||
}.toString()
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun read(file: File): Loaded {
|
||||
var harness: String? = null
|
||||
var conversation: String? = null
|
||||
val entries = mutableListOf<Entry>()
|
||||
runCatching {
|
||||
file.forEachLine { line ->
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@forEachLine
|
||||
when {
|
||||
o.has("harness") -> harness = o.getString("harness")
|
||||
o.has("conversation") -> conversation = o.getString("conversation")
|
||||
else -> decode(o)?.let { merge(entries, it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
return Loaded(harness, conversation, entries)
|
||||
}
|
||||
|
||||
private fun decode(o: JSONObject): Entry? = when {
|
||||
o.has("asked") -> Entry.Asked(o.getString("asked"), o.optJSONArray("files")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty())
|
||||
o.has("said") -> Entry.Said(o.getString("said"))
|
||||
o.has("thought") -> Entry.Thought(o.getString("thought"))
|
||||
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
|
||||
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"))
|
||||
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,
|
||||
)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** A tool's result is shown on the call it answers, and a call seen again (an updated todo list) replaces it. */
|
||||
fun merge(entries: MutableList<Entry>, entry: Entry): Boolean {
|
||||
if (entry is Entry.Used && entry.id.isNotEmpty()) {
|
||||
val same = entries.indexOfLast { it is Entry.Used && it.id == entry.id }
|
||||
if (same >= 0) {
|
||||
entries[same] = entry
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (entry !is Entry.Result) {
|
||||
entries += entry
|
||||
return true
|
||||
}
|
||||
val index = entries.indexOfLast { it is Entry.Used && it.id == entry.id && entry.id.isNotEmpty() }
|
||||
if (index < 0) return false
|
||||
entries[index] = (entries[index] as Entry.Used).copy(output = clip(entry.output), failed = entry.failed)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Long outputs keep their end, where errors and summaries usually are. */
|
||||
fun clip(output: String) = if (output.length <= MAX_OUTPUT) output else "…\n" + output.takeLast(MAX_OUTPUT)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.agent
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/** One coding agent CLI in the Linux userland, run one process per turn. */
|
||||
interface AgentHarness {
|
||||
@@ -16,18 +17,35 @@ interface AgentHarness {
|
||||
val signedIn: List<String>
|
||||
/** A guest command that signs in through $BROWSER. */
|
||||
val signIn: List<String>
|
||||
/** Whether [Options.plan] means anything to this CLI. */
|
||||
val plans: Boolean
|
||||
/** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */
|
||||
fun models(rootfs: File): List<Model>
|
||||
/** The guest command for one turn; [conversation] is null for the first one. */
|
||||
fun turn(message: String, conversation: String?): List<String>
|
||||
fun turn(message: String, conversation: String?, options: Options): List<String>
|
||||
/** One line of the CLI's output, or null when it carries nothing to show. */
|
||||
fun parse(line: String): AgentEvent?
|
||||
|
||||
data class Model(val id: String, val label: String)
|
||||
|
||||
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null)
|
||||
|
||||
companion object {
|
||||
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
|
||||
fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode
|
||||
}
|
||||
}
|
||||
|
||||
data class AgentEvent(val conversation: String?, val entries: List<AgentHost.Entry>)
|
||||
/** What one line of output carries: whole entries, or text still being written. */
|
||||
data class AgentEvent(
|
||||
val conversation: String? = null,
|
||||
val entries: List<AgentHost.Entry> = emptyList(),
|
||||
val text: String? = null,
|
||||
val thinking: String? = null,
|
||||
/** Tokens the conversation's context holds after this step. */
|
||||
val context: Long? = null,
|
||||
val usage: AgentHost.Usage? = null,
|
||||
)
|
||||
|
||||
/** Claude Code: `claude -p` with stream-json output, resumed by session id. */
|
||||
object ClaudeCode : AgentHarness {
|
||||
@@ -37,43 +55,112 @@ object ClaudeCode : AgentHarness {
|
||||
override val install = "curl -fsSL https://claude.ai/install.sh | bash"
|
||||
override val signedIn = listOf("sh", "-c", "$binary auth status | grep -q '\"loggedIn\": true'")
|
||||
override val signIn = listOf(binary, "auth", "login", "--claudeai")
|
||||
override val plans = true
|
||||
|
||||
override fun models(rootfs: File) = listOf(
|
||||
AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"),
|
||||
)
|
||||
|
||||
// DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them.
|
||||
override fun turn(message: String, conversation: String?) = buildList {
|
||||
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"))
|
||||
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
|
||||
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
|
||||
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
|
||||
options.model?.let { addAll(listOf("--model", it)) }
|
||||
options.brief?.let { addAll(listOf("--append-system-prompt", it)) }
|
||||
if (conversation != null) addAll(listOf("--resume", conversation))
|
||||
}
|
||||
|
||||
override fun parse(line: String): AgentEvent? {
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
|
||||
val entries = when (o.optString("type")) {
|
||||
return when (o.optString("type")) {
|
||||
"stream_event" -> {
|
||||
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
|
||||
when (delta.optString("type")) {
|
||||
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
|
||||
"thinking_delta" -> AgentEvent(conversation, thinking = delta.optString("thinking"))
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
"assistant" -> {
|
||||
val content = o.optJSONObject("message")?.optJSONArray("content") ?: JSONArray()
|
||||
(0 until content.length()).mapNotNull { i ->
|
||||
val message = o.optJSONObject("message")
|
||||
val content = message?.optJSONArray("content") ?: JSONArray()
|
||||
val entries = (0 until content.length()).mapNotNull { i ->
|
||||
val block = content.optJSONObject(i) ?: return@mapNotNull null
|
||||
when (block.optString("type")) {
|
||||
"text" -> block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
|
||||
"tool_use" -> AgentHost.Entry.Used(block.optString("name"), detail(block.optJSONObject("input")))
|
||||
"thinking" -> block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
|
||||
"tool_use" -> {
|
||||
val input = block.optJSONObject("input")
|
||||
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input))
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
val usage = message?.optJSONObject("usage")
|
||||
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
|
||||
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 })
|
||||
}
|
||||
"result" -> listOf(AgentHost.Entry.Finished(
|
||||
if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null,
|
||||
))
|
||||
else -> emptyList()
|
||||
"user" -> {
|
||||
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
|
||||
val results = (0 until content.length()).mapNotNull { i ->
|
||||
val block = content.optJSONObject(i)?.takeIf { it.optString("type") == "tool_result" } ?: return@mapNotNull null
|
||||
AgentHost.Entry.Result(block.optString("tool_use_id"), resultText(block.opt("content")), block.optBoolean("is_error"))
|
||||
}
|
||||
AgentEvent(conversation, results)
|
||||
}
|
||||
"result" -> AgentEvent(
|
||||
conversation,
|
||||
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
|
||||
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,
|
||||
o.optJSONObject("usage")?.optLong("output_tokens") ?: 0,
|
||||
),
|
||||
)
|
||||
else -> conversation?.let { AgentEvent(it) }
|
||||
}
|
||||
return if (conversation == null && entries.isEmpty()) null else AgentEvent(conversation, entries)
|
||||
}
|
||||
|
||||
private fun resultText(content: Any?): String = when (content) {
|
||||
is String -> content
|
||||
is JSONArray -> (0 until content.length()).mapNotNull { i ->
|
||||
val part = content.optJSONObject(i) ?: return@mapNotNull null
|
||||
when (part.optString("type")) {
|
||||
"text" -> part.optString("text")
|
||||
"image" -> "[image]"
|
||||
else -> null
|
||||
}
|
||||
}.joinToString("\n")
|
||||
null, JSONObject.NULL -> ""
|
||||
else -> content.toString()
|
||||
}
|
||||
|
||||
private fun detail(input: JSONObject?): String {
|
||||
input ?: return ""
|
||||
for (key in listOf("command", "file_path", "pattern", "url", "description")) {
|
||||
for (key in listOf("command", "file_path", "pattern", "url", "query", "description", "prompt")) {
|
||||
input.optString(key).takeIf { it.isNotEmpty() }?.let { return firstLine(it) }
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun fullInput(tool: String, input: JSONObject?): String {
|
||||
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 == "TodoWrite" -> todos(input.optJSONArray("todos"))
|
||||
else -> input.toString(2)
|
||||
}
|
||||
}
|
||||
|
||||
private fun todos(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { i ->
|
||||
val todo = list?.optJSONObject(i) ?: return@mapNotNull null
|
||||
val mark = when (todo.optString("status")) { "completed" -> "[x]"; "in_progress" -> "[~]"; else -> "[ ]" }
|
||||
"$mark ${todo.optString("content")}"
|
||||
}.joinToString("\n")
|
||||
}
|
||||
|
||||
/** OpenAI Codex: `codex exec --json`, resumed by thread id. */
|
||||
@@ -90,39 +177,85 @@ object Codex : AgentHarness {
|
||||
""".trimIndent()
|
||||
override val signedIn = listOf(binary, "login", "status")
|
||||
override val signIn = listOf(binary, "login")
|
||||
override val plans = false
|
||||
|
||||
/** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */
|
||||
override fun models(rootfs: File): List<AgentHarness.Model> = runCatching {
|
||||
val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText())
|
||||
val list = o.optJSONArray("models") ?: JSONArray()
|
||||
(0 until list.length()).mapNotNull { i ->
|
||||
val m = list.optJSONObject(i) ?: return@mapNotNull null
|
||||
val slug = m.optString("slug").ifEmpty { m.optString("id") }.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
|
||||
if (m.has("visibility") && m.optString("visibility") != "list") return@mapNotNull null
|
||||
AgentHarness.Model(slug, m.optString("display_name").ifEmpty { slug })
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
// Codex's own sandbox needs Landlock and seccomp, which proot does not provide.
|
||||
override fun turn(message: String, conversation: String?) = buildList {
|
||||
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
|
||||
addAll(listOf(binary, "exec"))
|
||||
if (conversation != null) addAll(listOf("resume", conversation))
|
||||
addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", message))
|
||||
addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check"))
|
||||
options.model?.let { addAll(listOf("-m", it)) }
|
||||
// codex exec has no system prompt option, so a new conversation starts with the brief.
|
||||
add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message)
|
||||
}
|
||||
|
||||
override fun parse(line: String): AgentEvent? {
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||
val item = o.optJSONObject("item")
|
||||
val id = item?.optString("id").orEmpty()
|
||||
val entries = when (o.optString("type")) {
|
||||
"thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() }, emptyList())
|
||||
"thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() })
|
||||
"item.started" -> when (item?.optString("type")) {
|
||||
"command_execution" -> listOf(AgentHost.Entry.Used("Shell", firstLine(item.optString("command"))))
|
||||
"command_execution" -> listOf(AgentHost.Entry.Used(id, "Shell", firstLine(item.optString("command")), item.optString("command")))
|
||||
"mcp_tool_call" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.optJSONObject("arguments")?.toString(2).orEmpty()))
|
||||
"web_search" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query")))
|
||||
else -> emptyList()
|
||||
}
|
||||
"item.updated" -> when (item?.optString("type")) {
|
||||
"todo_list" -> listOf(todoEntry(id, item))
|
||||
else -> emptyList()
|
||||
}
|
||||
"item.completed" -> when (item?.optString("type")) {
|
||||
"agent_message" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty()
|
||||
"file_change" -> listOf(AgentHost.Entry.Used("Edit", changedFiles(item)))
|
||||
"reasoning" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Thought(it)) }.orEmpty()
|
||||
"command_execution" -> listOf(AgentHost.Entry.Result(id, item.optString("aggregated_output"),
|
||||
item.has("exit_code") && !item.isNull("exit_code") && item.optInt("exit_code") != 0))
|
||||
"mcp_tool_call" -> listOf(AgentHost.Entry.Result(id, item.optJSONObject("result")?.toString(2) ?: item.optJSONObject("error")?.optString("message").orEmpty(),
|
||||
item.optString("status") == "failed"))
|
||||
"web_search" -> listOf(AgentHost.Entry.Result(id, "", false))
|
||||
"file_change" -> listOf(
|
||||
AgentHost.Entry.Used(id, "Edit", changedFiles(item), changedFiles(item).replace(", ", "\n")),
|
||||
AgentHost.Entry.Result(id, item.optString("status"), item.optString("status") == "failed"),
|
||||
)
|
||||
"todo_list" -> listOf(todoEntry(id, item))
|
||||
"error" -> listOf(AgentHost.Entry.Said("⚠ " + item.optString("message")))
|
||||
else -> emptyList()
|
||||
}
|
||||
"turn.completed" -> listOf(AgentHost.Entry.Finished(null))
|
||||
"turn.completed" -> return AgentEvent(
|
||||
entries = listOf(AgentHost.Entry.Finished(null)),
|
||||
usage = o.optJSONObject("usage")?.let { AgentHost.Usage(0, 0.0, it.optLong("input_tokens") + it.optLong("cached_input_tokens"), it.optLong("output_tokens")) },
|
||||
)
|
||||
"turn.failed" -> listOf(AgentHost.Entry.Finished(o.optJSONObject("error")?.optString("message") ?: "turn failed"))
|
||||
"error" -> listOf(AgentHost.Entry.Finished(o.optString("message").ifEmpty { "error" }))
|
||||
else -> emptyList()
|
||||
}
|
||||
return if (entries.isEmpty()) null else AgentEvent(null, entries)
|
||||
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
|
||||
}
|
||||
|
||||
private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
|
||||
val items = item.optJSONArray("items") ?: JSONArray()
|
||||
val text = (0 until items.length()).mapNotNull { i ->
|
||||
val todo = items.optJSONObject(i) ?: return@mapNotNull null
|
||||
"${if (todo.optBoolean("completed")) "[x]" else "[ ]"} ${todo.optString("text")}"
|
||||
}.joinToString("\n")
|
||||
return AgentHost.Entry.Used("$id-todo", "TodoWrite", "", text, output = "")
|
||||
}
|
||||
|
||||
private fun changedFiles(item: JSONObject): String {
|
||||
val changes = item.optJSONArray("changes") ?: return ""
|
||||
return (0 until changes.length()).mapNotNull { changes.optJSONObject(it)?.optString("path") }.joinToString(", ").take(160)
|
||||
return (0 until changes.length()).mapNotNull { changes.optJSONObject(it)?.optString("path") }.joinToString(", ").take(400)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,38 +4,59 @@ import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
/**
|
||||
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
|
||||
* one process per turn, outside any game or desktop session. The conversation id and transcript
|
||||
* are kept on disk, so a restart (a Lab build, a crash) continues the same conversation.
|
||||
* one process per turn, outside any game or desktop session. Conversations are kept on disk
|
||||
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
|
||||
*/
|
||||
object AgentHost {
|
||||
sealed interface Entry {
|
||||
data class Asked(val text: String) : Entry
|
||||
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
|
||||
data class Said(val text: String) : Entry
|
||||
data class Used(val tool: String, val detail: String) : Entry
|
||||
data class Finished(val error: String?) : Entry
|
||||
data class Thought(val text: String) : Entry
|
||||
/** 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
|
||||
}
|
||||
|
||||
data class Usage(val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long)
|
||||
|
||||
/** A message typed while the agent was working, sent when the turn ends. */
|
||||
data class Queued(val text: String, val files: List<String>)
|
||||
|
||||
enum class State { MISSING, IDLE, WORKING }
|
||||
|
||||
private const val TAG = "AgentHost"
|
||||
private const val WORKSPACE = "/root/DroidDeck"
|
||||
private const val TICK_MS = 1_000L
|
||||
|
||||
/** Where the agent runs and what the user sees, which no file in the checkout tells it. */
|
||||
@VisibleForTesting
|
||||
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
|
||||
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
|
||||
"droiddeckctl (in the /root/DroidDeck checkout, tools/droiddeckctl) inspects and drives the app over loopback adb (\$ADB_SERIAL). " +
|
||||
"dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md); the app shows the user its " +
|
||||
"progress and time left, so start it in the background and check on it instead of waiting in one long command. " +
|
||||
"The restart ends this process and the conversation continues afterwards. " +
|
||||
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments."
|
||||
|
||||
val entries = mutableStateListOf<Entry>()
|
||||
val queue = mutableStateListOf<Queued>()
|
||||
var state by mutableStateOf(State.IDLE)
|
||||
private set
|
||||
var installed by mutableStateOf(false)
|
||||
@@ -45,32 +66,102 @@ object AgentHost {
|
||||
private set
|
||||
var harness by mutableStateOf<AgentHarness>(ClaudeCode)
|
||||
private set
|
||||
/** The chosen model for [harness]; null is the CLI's default. */
|
||||
var model by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var plan by mutableStateOf(false)
|
||||
private set
|
||||
var chat by mutableStateOf<String?>(null)
|
||||
private set
|
||||
/** A reply finished since the conversation was last on screen. */
|
||||
var unseen by mutableStateOf(false)
|
||||
private set
|
||||
var failed by mutableStateOf(false)
|
||||
private set
|
||||
/** Text and thinking of the reply being written. */
|
||||
var live by mutableStateOf("")
|
||||
private set
|
||||
var liveThinking by mutableStateOf("")
|
||||
private set
|
||||
/** When the current turn started, on [SystemClock.elapsedRealtime]. */
|
||||
var turnStarted by mutableLongStateOf(0L)
|
||||
private set
|
||||
var now by mutableLongStateOf(0L)
|
||||
private set
|
||||
/** Tokens in the conversation's context after its last step. */
|
||||
var context by mutableLongStateOf(0L)
|
||||
private set
|
||||
var lab by mutableStateOf<LabProgress?>(null)
|
||||
private set
|
||||
|
||||
private class Turn(val process: Process, val pid: Int)
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var process: Process? = null
|
||||
private var turn: Turn? = null
|
||||
/** Counts turns, so a process that starts after its turn was stopped is not adopted by the next one. */
|
||||
private var generation = 0
|
||||
private var conversation: String? = null
|
||||
private var loaded = false
|
||||
private var appContext: Context? = null
|
||||
|
||||
val turnPid: Int get() = turn?.pid ?: 0
|
||||
|
||||
fun seen() {
|
||||
unseen = false
|
||||
}
|
||||
|
||||
fun refresh(context: Context) {
|
||||
harness = AgentHarness.byId(prefs(context).getString(HARNESS_KEY, null))
|
||||
available = LinuxRuntime.isInstalled(context)
|
||||
installed = guestFileExists(context, harness.binary)
|
||||
val app = context.applicationContext
|
||||
appContext = app
|
||||
harness = AgentHarness.byId(prefs(app).getString(HARNESS_KEY, null))
|
||||
model = prefs(app).getString(modelKey(harness), null)
|
||||
plan = prefs(app).getBoolean(PLAN_KEY, false)
|
||||
available = LinuxRuntime.isInstalled(app)
|
||||
installed = guestFileExists(app, harness.binary)
|
||||
if (!installed) state = State.MISSING else if (state == State.MISSING) state = State.IDLE
|
||||
if (!loaded) {
|
||||
loaded = true
|
||||
entries.addAll(readTranscript(transcript(context)))
|
||||
resumeAfterRestart(context.applicationContext)
|
||||
val migrated = AgentChats.migrate(app, harness.id, prefs(app).getString(LEGACY_CONVERSATION_KEY, null))
|
||||
if (migrated != null) prefs(app).edit().remove(LEGACY_CONVERSATION_KEY).putString(CHAT_KEY, migrated).apply()
|
||||
prefs(app).getString(CHAT_KEY, null)?.let { load(app, it) }
|
||||
resumeAfterRestart(app)
|
||||
tick()
|
||||
}
|
||||
}
|
||||
|
||||
private fun load(app: Context, id: String) {
|
||||
val file = AgentChats.file(app, id)
|
||||
if (!file.isFile) return
|
||||
val loaded = AgentChats.read(file)
|
||||
chat = id
|
||||
conversation = loaded.conversation
|
||||
entries.clear()
|
||||
entries.addAll(loaded.entries)
|
||||
context = 0
|
||||
}
|
||||
|
||||
/** Opens a kept conversation, switching to the CLI it belongs to. */
|
||||
fun open(context: Context, id: String) {
|
||||
val app = context.applicationContext
|
||||
if (state == State.WORKING || id == chat) return
|
||||
val harnessId = AgentChats.read(AgentChats.file(app, id)).harness
|
||||
if (harnessId != null && harnessId != harness.id) {
|
||||
prefs(app).edit().putString(HARNESS_KEY, harnessId).apply()
|
||||
AgentSetup.forget()
|
||||
refresh(app)
|
||||
}
|
||||
load(app, id)
|
||||
prefs(app).edit().putString(CHAT_KEY, id).apply()
|
||||
}
|
||||
|
||||
fun delete(context: Context, id: String) {
|
||||
if (id == chat) {
|
||||
if (state == State.WORKING) return
|
||||
forget(context)
|
||||
}
|
||||
AgentChats.delete(context.applicationContext, id)
|
||||
}
|
||||
|
||||
/**
|
||||
* A Lab build restarts the app, which ends the agent's process mid-turn. dd-lab-build leaves
|
||||
* [RESUME] when the app's own agent ran it, so the same conversation picks up on the new build.
|
||||
@@ -84,6 +175,9 @@ object AgentHost {
|
||||
send(app, app.getString(R.string.agent_resumed))
|
||||
}
|
||||
|
||||
/** True when DroidDeck restarted in the middle of one of the agent's turns. */
|
||||
fun resuming(context: Context) = File(context.applicationContext.filesDir, RESUME).isFile
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun interrupted(entries: List<Entry>) = entries.isNotEmpty() && entries.last() !is Entry.Finished
|
||||
|
||||
@@ -96,54 +190,99 @@ object AgentHost {
|
||||
refresh(context)
|
||||
}
|
||||
|
||||
fun send(context: Context, text: String) {
|
||||
fun chooseModel(context: Context, id: String?) {
|
||||
model = id
|
||||
prefs(context).edit().putString(modelKey(harness), id).apply()
|
||||
}
|
||||
|
||||
fun choosePlan(context: Context, on: Boolean) {
|
||||
plan = on
|
||||
prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
|
||||
}
|
||||
|
||||
fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext))
|
||||
|
||||
/** Sends [text] now, or after the current turn when the agent is working. */
|
||||
fun send(context: Context, text: String, files: List<String> = emptyList()) {
|
||||
val app = context.applicationContext
|
||||
val message = text.trim()
|
||||
if (message.isEmpty() || state != State.IDLE) return
|
||||
record(app, Entry.Asked(message))
|
||||
if (message.isEmpty() && files.isEmpty()) return
|
||||
if (state == State.WORKING) {
|
||||
queue += Queued(message, files)
|
||||
return
|
||||
}
|
||||
if (state != State.IDLE) return
|
||||
val id = chat ?: AgentChats.newId(app).also { id ->
|
||||
AgentChats.start(AgentChats.file(app, id), harness.id)
|
||||
chat = id
|
||||
conversation = null
|
||||
prefs(app).edit().putString(CHAT_KEY, id).apply()
|
||||
}
|
||||
record(app, Entry.Asked(message, files))
|
||||
state = State.WORKING
|
||||
val gen = ++generation
|
||||
live = ""
|
||||
liveThinking = ""
|
||||
turnStarted = SystemClock.elapsedRealtime()
|
||||
AgentHostService.start(app)
|
||||
val current = harness
|
||||
val conversation = prefs(app).getString(CONVERSATION_KEY, null)
|
||||
val prompt = AgentAttachments.prompt(message, files)
|
||||
val command = current.turn(prompt, conversation, AgentHarness.Options(model, plan && current.plans, BRIEF))
|
||||
val workdir = workspace(app)
|
||||
Thread({
|
||||
val child = try {
|
||||
guest(app, current.turn(message, conversation), workdir).start()
|
||||
guest(app, command, workdir).start()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not start ${current.name}", e)
|
||||
main.post { finish(app, e.message ?: "could not start") }
|
||||
main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
|
||||
return@Thread
|
||||
}
|
||||
main.post { process = child }
|
||||
val started = Turn(child, AgentProcesses.pidOf(child))
|
||||
main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) }
|
||||
child.outputStream.close()
|
||||
var ended = false
|
||||
runCatching {
|
||||
child.inputStream.bufferedReader().forEachLine { line ->
|
||||
val event = current.parse(line) ?: return@forEachLine
|
||||
if (event.entries.any { it is Entry.Finished }) ended = true
|
||||
main.post { apply(app, child, event) }
|
||||
main.post { if (turn === started) apply(app, event) }
|
||||
}
|
||||
}
|
||||
val status = runCatching { child.waitFor() }.getOrDefault(-1)
|
||||
main.post {
|
||||
if (process === child) {
|
||||
process = null
|
||||
if (state == State.WORKING && !ended) finish(app, "${current.name} stopped (exit $status)")
|
||||
if (turn === started) {
|
||||
turn = null
|
||||
if (state == State.WORKING && !ended) finish(app, app.getString(R.string.agent_exited, current.name, status))
|
||||
}
|
||||
}
|
||||
}, "agent-output").start()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
process?.destroy()
|
||||
process = null
|
||||
/** Ends the turn now: its process and everything it started, a build included. */
|
||||
fun stop(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val running = turn
|
||||
turn = null
|
||||
queue.clear()
|
||||
if (running != null) {
|
||||
AgentProcesses.killTree(running.pid)
|
||||
running.process.destroy()
|
||||
}
|
||||
if (state == State.WORKING) finish(app, null, stopped = true)
|
||||
}
|
||||
|
||||
fun unqueue(item: Queued) {
|
||||
queue.remove(item)
|
||||
}
|
||||
|
||||
/** Starts a new conversation; the current one stays in the history. */
|
||||
fun forget(context: Context) {
|
||||
stop()
|
||||
stop(context)
|
||||
entries.clear()
|
||||
transcript(context).delete()
|
||||
prefs(context).edit().remove(CONVERSATION_KEY).apply()
|
||||
chat = null
|
||||
conversation = null
|
||||
this.context = 0
|
||||
prefs(context).edit().remove(CHAT_KEY).apply()
|
||||
state = if (installed) State.IDLE else State.MISSING
|
||||
}
|
||||
|
||||
@@ -184,53 +323,78 @@ object AgentHost {
|
||||
|
||||
private fun workspace(app: Context) = if (guestFileExists(app, WORKSPACE)) WORKSPACE else "/root"
|
||||
|
||||
private fun apply(app: Context, child: Process, event: AgentEvent) {
|
||||
if (process !== child) return
|
||||
event.conversation?.let { prefs(app).edit().putString(CONVERSATION_KEY, it).apply() }
|
||||
event.entries.forEach { if (it is Entry.Finished) finish(app, it.error) else record(app, it) }
|
||||
private fun apply(app: Context, event: AgentEvent) {
|
||||
event.conversation?.takeIf { it != conversation }?.let { id ->
|
||||
conversation = id
|
||||
chat?.let { AgentChats.appendConversation(AgentChats.file(app, it), id) }
|
||||
}
|
||||
event.text?.let { live += it }
|
||||
event.thinking?.let { liveThinking += it }
|
||||
event.context?.let { context = it }
|
||||
for (entry in event.entries) when (entry) {
|
||||
is Entry.Finished -> finish(app, entry.error, usage = event.usage)
|
||||
else -> {
|
||||
if (entry is Entry.Said) live = ""
|
||||
if (entry is Entry.Thought) liveThinking = ""
|
||||
record(app, entry)
|
||||
}
|
||||
}
|
||||
AgentHostService.update(app)
|
||||
}
|
||||
|
||||
private fun finish(app: Context, error: String?) {
|
||||
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
|
||||
if (state != State.WORKING) return
|
||||
record(app, Entry.Finished(error))
|
||||
turn = null
|
||||
live = ""
|
||||
liveThinking = ""
|
||||
record(app, Entry.Finished(error, stopped, usage))
|
||||
state = State.IDLE
|
||||
unseen = true
|
||||
failed = error != null
|
||||
AgentHostService.stop(app)
|
||||
if (!stopped && queue.isNotEmpty()) {
|
||||
val next = queue.removeAt(0)
|
||||
send(app, next.text, next.files)
|
||||
}
|
||||
}
|
||||
|
||||
private fun record(app: Context, entry: Entry) {
|
||||
entries += entry
|
||||
runCatching { transcript(app).apply { parentFile?.mkdirs() }.appendText(encode(entry) + "\n") }
|
||||
if (!AgentChats.merge(entries, entry)) return
|
||||
chat?.let { AgentChats.append(AgentChats.file(app, it), entry) }
|
||||
}
|
||||
|
||||
private const val CONVERSATION_KEY = "session_id"
|
||||
/** The tool call still running in this turn, if any. */
|
||||
fun running(): Entry.Used? {
|
||||
if (state != State.WORKING) return null
|
||||
val start = entries.indexOfLast { it is Entry.Asked }
|
||||
return entries.withIndex().lastOrNull { (i, e) -> i > start && e is Entry.Used && e.output == null }?.value as? Entry.Used
|
||||
}
|
||||
|
||||
/** The latest todo list the agent wrote in this conversation. */
|
||||
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" }?.let { (it as Entry.Used).input }
|
||||
|
||||
private fun tick() {
|
||||
now = SystemClock.elapsedRealtime()
|
||||
appContext?.let { app ->
|
||||
lab = LabProgress.read(LinuxRuntime.rootDir(app))
|
||||
if (state == State.WORKING) AgentHostService.update(app)
|
||||
}
|
||||
main.postDelayed(::tick, TICK_MS)
|
||||
}
|
||||
|
||||
fun cancelLabBuild(context: Context) {
|
||||
val progress = lab ?: return
|
||||
LabProgress.cancel(LinuxRuntime.rootDir(context.applicationContext), progress)
|
||||
lab = LabProgress.read(LinuxRuntime.rootDir(context.applicationContext))
|
||||
}
|
||||
|
||||
private const val LEGACY_CONVERSATION_KEY = "session_id"
|
||||
private const val HARNESS_KEY = "harness"
|
||||
private const val CHAT_KEY = "chat"
|
||||
private const val PLAN_KEY = "plan"
|
||||
private const val RESUME = "agent/resume"
|
||||
|
||||
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
|
||||
|
||||
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
|
||||
|
||||
private fun transcript(context: Context) = File(context.filesDir, "agent/transcript.jsonl")
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun encode(entry: Entry): String = when (entry) {
|
||||
is Entry.Asked -> JSONObject().put("asked", entry.text)
|
||||
is Entry.Said -> JSONObject().put("said", entry.text)
|
||||
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail)
|
||||
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL)
|
||||
}.toString()
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun readTranscript(file: File): List<Entry> = runCatching {
|
||||
file.readLines().mapNotNull { line ->
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@mapNotNull null
|
||||
when {
|
||||
o.has("asked") -> Entry.Asked(o.getString("asked"))
|
||||
o.has("said") -> Entry.Said(o.getString("said"))
|
||||
o.has("used") -> Entry.Used(o.getString("used"), o.optString("detail"))
|
||||
o.has("finished") -> Entry.Finished(if (o.isNull("error")) null else o.optString("error"))
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
@@ -8,44 +8,81 @@ import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.IBinder
|
||||
import android.os.SystemClock
|
||||
import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/** Keeps the app process alive while the agent works and the launcher is in the background. */
|
||||
/** Keeps the app process alive while the agent works, and says what it is doing, with a way to stop it. */
|
||||
class AgentHostService : Service() {
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.agent_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
|
||||
val open = PendingIntent.getActivity(this, 0,
|
||||
Intent(this, FrontEndActivity::class.java)
|
||||
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
|
||||
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val notification = Notification.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(getString(R.string.agent_working))
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
.setShowWhen(false)
|
||||
.setCategory(Notification.CATEGORY_PROGRESS)
|
||||
.build()
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
AgentHost.stop(this)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
startForeground(NOTIFICATION_ID, build(this))
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "agent"
|
||||
private const val NOTIFICATION_ID = 4107
|
||||
private const val ACTION_STOP = "com.droiddeck.launcher.agent.STOP"
|
||||
private var lastText: String? = null
|
||||
|
||||
fun start(context: Context) {
|
||||
lastText = null
|
||||
runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) }
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, AgentHostService::class.java))
|
||||
}
|
||||
|
||||
/** Refreshes the notification with the current step; unchanged text is not re-posted. */
|
||||
fun update(context: Context) {
|
||||
if (AgentHost.state != AgentHost.State.WORKING) return
|
||||
val text = describe(context)
|
||||
if (text == lastText) return
|
||||
lastText = text
|
||||
context.getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, build(context))
|
||||
}
|
||||
|
||||
private fun describe(context: Context): String {
|
||||
val lab = AgentHost.lab?.takeIf { it.running }
|
||||
if (lab != null) return context.getString(R.string.agent_lab_progress, lab.permille / 10, minutes(lab.etaSeconds.toLong()))
|
||||
val tool = AgentHost.running()
|
||||
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
|
||||
return if (tool != null) "${tool.tool} · ${tool.detail}".take(120) + " · $elapsed" else context.getString(R.string.agent_thinking_for, elapsed)
|
||||
}
|
||||
|
||||
private fun minutes(seconds: Long) = if (seconds < 60) "${seconds.coerceAtLeast(0)}s" else "${seconds / 60}m ${seconds % 60}s"
|
||||
|
||||
private fun build(context: Context): Notification {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
|
||||
val open = PendingIntent.getActivity(context, 0,
|
||||
Intent(context, FrontEndActivity::class.java)
|
||||
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
|
||||
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val stop = PendingIntent.getService(context, 1, Intent(context, AgentHostService::class.java).setAction(ACTION_STOP),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val lab = AgentHost.lab?.takeIf { it.running }
|
||||
return Notification.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(context.getString(if (lab != null) R.string.agent_lab_building else R.string.agent_working))
|
||||
.setContentText(describe(context))
|
||||
.setContentIntent(open)
|
||||
.addAction(Notification.Action.Builder(null, context.getString(R.string.agent_stop), stop).build())
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setShowWhen(false)
|
||||
.apply { if (lab != null) setProgress(1000, lab.permille, lab.stage != "building") }
|
||||
.setCategory(Notification.CATEGORY_PROGRESS)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.os.Process
|
||||
import android.os.SystemClock
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Linux userland processes, read from /proc: proot runs them as real processes under the app's
|
||||
* own uid, so the app can list and end them without a shell.
|
||||
*/
|
||||
object AgentProcesses {
|
||||
data class Proc(
|
||||
val pid: Int, val ppid: Int, val name: String, val args: String,
|
||||
val seconds: Long, val rssKb: Long, val cpuPercent: Int, val agent: Boolean,
|
||||
)
|
||||
|
||||
private const val HZ = 100L
|
||||
private var lastTicks = emptyMap<Int, Long>()
|
||||
private var lastAt = 0L
|
||||
|
||||
@VisibleForTesting
|
||||
internal class Stat(val pid: Int, val ppid: Int, val ticks: Long, val startTicks: Long, val rssPages: Long)
|
||||
|
||||
/** Guest processes, those under [turnPid] (the agent's current turn) first. */
|
||||
@Synchronized
|
||||
fun snapshot(turnPid: Int): List<Proc> {
|
||||
val me = Process.myPid()
|
||||
val uid = Process.myUid()
|
||||
val stats = HashMap<Int, Stat>()
|
||||
val args = HashMap<Int, String>()
|
||||
for (dir in File("/proc").listFiles().orEmpty()) {
|
||||
val pid = dir.name.toIntOrNull() ?: continue
|
||||
if (pid == me) continue
|
||||
val stat = runCatching { parseStat(File(dir, "stat").readText()) }.getOrNull() ?: continue
|
||||
if (!owned(dir, uid)) continue
|
||||
stats[pid] = stat
|
||||
args[pid] = runCatching { File(dir, "cmdline").readBytes().toString(Charsets.UTF_8).trimEnd('\u0000').replace('\u0000', ' ') }.getOrDefault("")
|
||||
}
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val uptimeTicks = now * HZ / 1000
|
||||
val elapsed = (now - lastAt).coerceAtLeast(1)
|
||||
fun isProot(pid: Int) = args[pid].orEmpty().substringBefore(' ').endsWith("proot.so") || args[pid].orEmpty().substringBefore(' ').endsWith("/proot")
|
||||
fun ancestors(pid: Int) = generateSequence(stats[pid]?.ppid) { stats[it]?.ppid }.takeWhile { it > 1 }.take(64)
|
||||
val out = stats.values.filter { s ->
|
||||
!isProot(s.pid) && args[s.pid].orEmpty().isNotEmpty() && ancestors(s.pid).any { isProot(it) }
|
||||
}.map { s ->
|
||||
val full = args[s.pid].orEmpty()
|
||||
val cpu = lastTicks[s.pid]?.let { ((s.ticks - it) * 1000 * 100 / HZ / elapsed).toInt().coerceIn(0, 800) } ?: 0
|
||||
Proc(
|
||||
s.pid, s.ppid, full.substringBefore(' ').substringAfterLast('/'), full,
|
||||
((uptimeTicks - s.startTicks) / HZ).coerceAtLeast(0), s.rssPages * 4, cpu,
|
||||
turnPid > 0 && ancestors(s.pid).any { it == turnPid },
|
||||
)
|
||||
}
|
||||
lastTicks = stats.mapValues { it.value.ticks }
|
||||
lastAt = now
|
||||
return out.sortedWith(compareByDescending<Proc> { it.agent }.thenBy { it.seconds * -1 })
|
||||
}
|
||||
|
||||
/** Ends [pid] and everything it started, children first so none is left to be re-parented. */
|
||||
fun killTree(pid: Int) {
|
||||
if (pid <= 0) return
|
||||
val children = HashMap<Int, MutableList<Int>>()
|
||||
for (dir in File("/proc").listFiles().orEmpty()) {
|
||||
val child = dir.name.toIntOrNull() ?: continue
|
||||
val stat = runCatching { parseStat(File(dir, "stat").readText()) }.getOrNull() ?: continue
|
||||
children.getOrPut(stat.ppid) { mutableListOf() } += child
|
||||
}
|
||||
val order = mutableListOf<Int>()
|
||||
fun walk(p: Int) {
|
||||
children[p].orEmpty().forEach(::walk)
|
||||
order += p
|
||||
}
|
||||
walk(pid)
|
||||
order.forEach { runCatching { Process.sendSignal(it, Process.SIGNAL_KILL) } }
|
||||
}
|
||||
|
||||
fun alive(pid: Int) = pid > 0 && File("/proc/$pid").exists()
|
||||
|
||||
/** Processes whose command line contains [text], for ending a build the app did not start. */
|
||||
fun find(text: String): List<Int> = File("/proc").listFiles().orEmpty().mapNotNull { dir ->
|
||||
val pid = dir.name.toIntOrNull() ?: return@mapNotNull null
|
||||
if (pid == Process.myPid()) return@mapNotNull null
|
||||
val args = runCatching { File(dir, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ') }.getOrDefault("")
|
||||
pid.takeIf { args.contains(text) && owned(dir, Process.myUid()) }
|
||||
}
|
||||
|
||||
private fun owned(dir: File, uid: Int) = runCatching {
|
||||
File(dir, "status").useLines { lines -> lines.first { it.startsWith("Uid:") }.split(Regex("\\s+"))[1].toInt() == uid }
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** `/proc/<pid>/stat`: the name in parentheses may hold spaces, so fields count from its end. */
|
||||
@VisibleForTesting
|
||||
internal fun parseStat(text: String): Stat {
|
||||
val pid = text.substringBefore(' ').toInt()
|
||||
val f = text.substring(text.lastIndexOf(')') + 2).split(' ')
|
||||
return Stat(pid, f[1].toInt(), f[11].toLong() + f[12].toLong(), f[19].toLong(), f[21].toLong())
|
||||
}
|
||||
|
||||
/** The pid of a [java.lang.Process] the app started. */
|
||||
fun pidOf(process: java.lang.Process): Int =
|
||||
runCatching { process.javaClass.getDeclaredField("pid").apply { isAccessible = true }.getInt(process) }.getOrNull()
|
||||
?: Regex("pid=(\\d+)").find(process.toString())?.groupValues?.get(1)?.toInt() ?: 0
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/** A Lab build in progress, as dd-lab-build reports it in `~/.cache/dd-lab-build.json`. */
|
||||
data class LabProgress(
|
||||
val stage: String, val prepare: Boolean, val permille: Int, val task: String,
|
||||
val done: Int, val total: Int, val etaSeconds: Int, val elapsedSeconds: Int, val pid: Int,
|
||||
) {
|
||||
val running get() = stage in RUNNING
|
||||
val failed get() = stage == "failed"
|
||||
|
||||
companion object {
|
||||
private val RUNNING = setOf("checking", "fetching", "sdk", "planning", "building", "packaging", "restarting")
|
||||
private const val PATH = "root/.cache/dd-lab-build.json"
|
||||
/** A finished build stays on screen this long. */
|
||||
private const val SHOW_DONE_MS = 60_000L
|
||||
|
||||
/** The build, while it runs and shortly after; null when there is none to show. */
|
||||
fun read(rootfs: File): LabProgress? {
|
||||
val file = File(rootfs, PATH)
|
||||
if (!file.isFile) return null
|
||||
val progress = parse(runCatching { file.readText() }.getOrNull() ?: return null) ?: return null
|
||||
if (progress.running) return progress.takeIf { AgentProcesses.alive(it.pid) } ?: progress.copy(stage = "failed", task = "stopped")
|
||||
return progress.takeIf { System.currentTimeMillis() - file.lastModified() < SHOW_DONE_MS }
|
||||
}
|
||||
|
||||
/** Ends the build and Gradle's daemon, which keeps compiling after its client is gone. */
|
||||
fun cancel(rootfs: File, progress: LabProgress) {
|
||||
AgentProcesses.killTree(progress.pid)
|
||||
AgentProcesses.find("GradleDaemon").forEach(AgentProcesses::killTree)
|
||||
runCatching {
|
||||
File(rootfs, PATH).writeText(JSONObject().put("stage", "failed").put("task", "stopped").put("pid", 0).toString())
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
internal fun parse(json: String): LabProgress? = runCatching {
|
||||
val o = JSONObject(json)
|
||||
LabProgress(
|
||||
o.getString("stage"), o.optString("mode") == "prepare", o.optInt("permille"), o.optString("task"),
|
||||
o.optInt("done"), o.optInt("total"), o.optInt("eta", -1), o.optInt("elapsed"), o.optInt("pid"),
|
||||
)
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentHost
|
||||
|
||||
private object BubblePlace {
|
||||
var x by mutableStateOf(Float.NaN)
|
||||
var y by mutableStateOf(Float.NaN)
|
||||
var hidden by mutableStateOf(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent's bubble over a session: there once the agent has been used, pulsing while it works,
|
||||
* marked when a reply or failure has not been seen. Drag it to either edge; a long press hides it
|
||||
* until the next session.
|
||||
*/
|
||||
@Composable
|
||||
internal fun AgentBubble(onOpen: () -> Unit) {
|
||||
if (!AgentHost.installed || BubblePlace.hidden || AgentHost.entries.isEmpty()) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val density = androidx.compose.ui.platform.LocalDensity.current
|
||||
val size = 56.dp
|
||||
val sizePx = with(density) { size.toPx() }
|
||||
val margin = with(density) { 12.dp.toPx() }
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
val pulse = androidx.compose.animation.core.rememberInfiniteTransition(label = "agentPulse")
|
||||
val ring by pulse.animateFloat(
|
||||
0.35f, 1f,
|
||||
androidx.compose.animation.core.infiniteRepeatable(androidx.compose.animation.core.tween(900), androidx.compose.animation.core.RepeatMode.Reverse),
|
||||
label = "agentRing",
|
||||
)
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val width = constraints.maxWidth.toFloat()
|
||||
val height = constraints.maxHeight.toFloat()
|
||||
if (BubblePlace.x.isNaN()) {
|
||||
BubblePlace.x = width - sizePx - margin
|
||||
BubblePlace.y = height * 0.3f
|
||||
}
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
.offset { androidx.compose.ui.unit.IntOffset(BubblePlace.x.toInt(), BubblePlace.y.toInt()) }
|
||||
.size(size)
|
||||
.graphicsLayer { alpha = if (working || AgentHost.unseen) 1f else 0.7f }
|
||||
.clip(androidx.compose.foundation.shape.CircleShape)
|
||||
.background(colors.surface)
|
||||
.border(
|
||||
2.dp,
|
||||
if (working) colors.primary.copy(alpha = ring) else if (AgentHost.failed && AgentHost.unseen) colors.error else colors.outlineVariant,
|
||||
androidx.compose.foundation.shape.CircleShape,
|
||||
)
|
||||
.pointerInput(width, height) {
|
||||
detectDragGestures(onDragEnd = {
|
||||
BubblePlace.x = if (BubblePlace.x + sizePx / 2 < width / 2) margin else width - sizePx - margin
|
||||
}) { change, drag ->
|
||||
change.consume()
|
||||
BubblePlace.x = (BubblePlace.x + drag.x).coerceIn(0f, width - sizePx)
|
||||
BubblePlace.y = (BubblePlace.y + drag.y).coerceIn(0f, height - sizePx)
|
||||
}
|
||||
}
|
||||
.pointerInput(Unit) {
|
||||
detectTapGestures(onTap = { onOpen() }, onLongPress = { BubblePlace.hidden = true })
|
||||
}
|
||||
.testTag("agent-bubble"),
|
||||
) {
|
||||
Icon(androidx.compose.material.icons.Icons.Outlined.AutoAwesome, stringResource(R.string.rail_agent), tint = colors.primary)
|
||||
if (AgentHost.unseen && !working) Box(
|
||||
Modifier.align(Alignment.TopEnd).padding(6.dp).size(10.dp)
|
||||
.clip(androidx.compose.foundation.shape.CircleShape)
|
||||
.background(if (AgentHost.failed) colors.error else colors.primary),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.CheckCircle
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Description
|
||||
import androidx.compose.material.icons.outlined.ErrorOutline
|
||||
import androidx.compose.material.icons.outlined.ExpandLess
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
import androidx.compose.material.icons.outlined.Psychology
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
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.stringResource
|
||||
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.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentAttachments
|
||||
import com.droiddeck.launcher.agent.AgentHost.Entry
|
||||
|
||||
@Composable
|
||||
internal fun AgentEntry(entry: Entry, running: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
when (entry) {
|
||||
is Entry.Asked -> Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (entry.files.isNotEmpty()) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { entry.files.forEach { AttachmentChip(it, null) } }
|
||||
if (entry.text.isNotEmpty()) SelectionContainer {
|
||||
Text(entry.text, fontSize = 15.sp, color = pal.onPrimary,
|
||||
modifier = Modifier.widthIn(max = 560.dp).clip(Shape16).background(pal.primary).padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
}
|
||||
}
|
||||
is Entry.Said -> SelectionContainer { AgentMarkdown(entry.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
|
||||
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 -> AgentTurnEnd(entry)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AgentTurnEnd(entry: Entry.Finished) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val text = when {
|
||||
entry.stopped -> stringResource(R.string.agent_stopped)
|
||||
entry.error != null -> stringResource(R.string.agent_failed, entry.error)
|
||||
else -> entry.usage?.let { u ->
|
||||
buildList {
|
||||
if (u.durationMs > 0) add(clock(u.durationMs / 1000))
|
||||
if (u.costUsd > 0) add("$" + String.format(java.util.Locale.US, "%.2f", u.costUsd))
|
||||
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))
|
||||
}
|
||||
|
||||
internal fun tokens(n: Long) = if (n >= 1000) "${n / 1000}k" else n.toString()
|
||||
|
||||
@Composable
|
||||
internal fun AgentThought(text: String, live: Boolean) {
|
||||
val pal = LocalPalette.current
|
||||
var open by rememberSaveable(text.take(40)) { mutableStateOf(false) }
|
||||
Column(Modifier.padding(horizontal = 4.dp).animateContentSize()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clip(Shape12).clickable { open = !open }.padding(vertical = 4.dp)) {
|
||||
Icon(Icons.Outlined.Psychology, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
|
||||
Text(stringResource(if (live) R.string.agent_thinking else R.string.agent_thought), fontSize = 13.sp, color = pal.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 6.dp))
|
||||
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
if (open || live) Text(
|
||||
if (open) text else text.takeLast(240), fontSize = 13.sp, fontStyle = FontStyle.Italic, color = pal.onSurfaceVariant, lineHeight = 19.sp,
|
||||
maxLines = if (open) Int.MAX_VALUE else 3, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 760.dp).padding(start = 22.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AgentTodos(list: String) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
Modifier.widthIn(max = 560.dp).padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
for (line in list.lines().filter { it.isNotBlank() }) {
|
||||
val done = line.startsWith("[x]")
|
||||
val doing = line.startsWith("[~]")
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(14.dp).clip(Shape12).background(when {
|
||||
done -> pal.good
|
||||
doing -> pal.primary
|
||||
else -> pal.line
|
||||
}))
|
||||
Text(line.drop(4), fontSize = 13.sp, color = if (done) pal.onSurfaceVariant else colors.onSurface,
|
||||
fontWeight = if (doing) FontWeight.SemiBold else null, modifier = Modifier.padding(start = 8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A tool call: one line with its status, opening to the full input and output. */
|
||||
@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) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).animateContentSize().testTag("agent-tool"),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clickable { open = !open }.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
) {
|
||||
Box(Modifier.size(16.dp), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
running -> CircularProgressIndicator(Modifier.size(13.dp), strokeWidth = 2.dp, color = pal.primary)
|
||||
entry.failed -> Icon(Icons.Outlined.ErrorOutline, null, tint = colors.error, modifier = Modifier.size(16.dp))
|
||||
entry.output != null -> Icon(Icons.Outlined.CheckCircle, null, tint = pal.good, modifier = Modifier.size(16.dp))
|
||||
else -> Icon(Icons.Outlined.Close, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
}
|
||||
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,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(start = 8.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 (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)
|
||||
entry.output == null -> Text(stringResource(R.string.agent_tool_no_result), fontSize = 12.sp, color = pal.onSurfaceVariant)
|
||||
entry.output.isBlank() -> Text(stringResource(R.string.agent_tool_empty), fontSize = 12.sp, color = pal.onSurfaceVariant)
|
||||
else -> CodeBox(stringResource(R.string.agent_tool_output), entry.output, if (entry.failed) colors.error else colors.onSurface)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CodeBox(label: String, text: String, color: Color) {
|
||||
val pal = LocalPalette.current
|
||||
Column {
|
||||
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
|
||||
SelectionContainer {
|
||||
Text(
|
||||
text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = color, lineHeight = 17.sp,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface)
|
||||
.verticalScroll(rememberScrollState()).padding(10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** An attached file: a thumbnail for images, the name otherwise; [onRemove] adds a remove mark. */
|
||||
@Composable
|
||||
internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
Box {
|
||||
if (AgentAttachments.isImage(path)) AsyncImage(
|
||||
model = AgentAttachments.host(context, path), contentDescription = path.substringAfterLast('/'), contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant),
|
||||
) else Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.heightIn(min = 40.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.Description, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
|
||||
Text(path.substringAfterLast('/'), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurface, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 200.dp).padding(start = 6.dp, end = if (onRemove != null) 18.dp else 0.dp))
|
||||
}
|
||||
if (onRemove != null) Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(3.dp).size(20.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).clickable(onClick = onRemove),
|
||||
) {
|
||||
Icon(Icons.Outlined.Close, stringResource(R.string.agent_remove_attachment), tint = pal.onSurfaceVariant, modifier = Modifier.size(14.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The Markdown agents write: headings, lists, fenced code, `code` and **bold**. */
|
||||
@Composable
|
||||
internal fun AgentMarkdown(text: String, modifier: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
for (block in markdownBlocks(text)) when (block) {
|
||||
is MdBlock.Code -> Text(block.text, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface,
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(12.dp))
|
||||
is MdBlock.Line -> Text(
|
||||
inlineMarkdown(block.text, pal.primary2, pal.surfaceVariant),
|
||||
fontSize = if (block.heading) 17.sp else 15.sp,
|
||||
fontWeight = if (block.heading) FontWeight.Bold else null,
|
||||
lineHeight = 22.sp, color = colors.onSurface,
|
||||
modifier = if (block.bullet) Modifier.padding(start = 12.dp) else Modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
data class Line(val text: String, val heading: Boolean = false, val bullet: Boolean = false) : MdBlock
|
||||
data class Code(val text: String) : MdBlock
|
||||
}
|
||||
|
||||
private val HEADING = Regex("^#{1,6}\\s+")
|
||||
private val BULLET = Regex("^\\s*[-*+]\\s+")
|
||||
|
||||
internal fun markdownBlocks(text: String): List<MdBlock> {
|
||||
val out = mutableListOf<MdBlock>()
|
||||
val code = StringBuilder()
|
||||
var inCode = false
|
||||
for (raw in text.lines()) {
|
||||
if (raw.trimStart().startsWith("```")) {
|
||||
if (inCode) {
|
||||
out += MdBlock.Code(code.toString().trimEnd('\n'))
|
||||
code.clear()
|
||||
}
|
||||
inCode = !inCode
|
||||
continue
|
||||
}
|
||||
if (inCode) {
|
||||
code.append(raw).append('\n')
|
||||
continue
|
||||
}
|
||||
val line = raw.trimEnd()
|
||||
if (line.isBlank()) continue
|
||||
val heading = HEADING.find(line)
|
||||
val bullet = BULLET.find(line)
|
||||
out += when {
|
||||
heading != null -> MdBlock.Line(line.substring(heading.range.last + 1), heading = true)
|
||||
bullet != null -> MdBlock.Line("• " + line.substring(bullet.range.last + 1), bullet = true)
|
||||
else -> MdBlock.Line(line)
|
||||
}
|
||||
}
|
||||
if (inCode && code.isNotEmpty()) out += MdBlock.Code(code.toString().trimEnd('\n'))
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun inlineMarkdown(text: String, codeColor: Color, codeBackground: Color): AnnotatedString = buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
val boldEnd = if (text.startsWith("**", i)) text.indexOf("**", i + 2) else -1
|
||||
val tickEnd = if (text[i] == '`') text.indexOf('`', i + 1) else -1
|
||||
when {
|
||||
boldEnd > i + 2 -> {
|
||||
withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(text, i + 2, boldEnd) }
|
||||
i = boldEnd + 2
|
||||
}
|
||||
tickEnd > i + 1 -> {
|
||||
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, color = codeColor, background = codeBackground)) { append(text, i + 1, tickEnd) }
|
||||
i = tickEnd + 1
|
||||
}
|
||||
else -> append(text[i++])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,49 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
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.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
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.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
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.AttachFile
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
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.Settings
|
||||
import androidx.compose.material.icons.outlined.Stop
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
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.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -33,308 +52,338 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
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.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.material.icons.outlined.Stop
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withStyle
|
||||
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
|
||||
|
||||
internal enum class AgentPanel { NONE, MODEL, 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")
|
||||
|
||||
@Composable
|
||||
internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true) {
|
||||
val context = LocalContext.current
|
||||
remember { AgentHost.refresh(context) }
|
||||
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
|
||||
remember { com.droiddeck.launcher.agent.AgentSetup.check(context) }
|
||||
remember { AgentSetup.check(context) }
|
||||
var setup by rememberSaveable { mutableStateOf(false) }
|
||||
if (setup || AgentHost.state == AgentHost.State.MISSING ||
|
||||
!(com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context))) {
|
||||
if (setup || AgentHost.state == AgentHost.State.MISSING || !(AgentSetup.ready || AgentSetup.completed(context))) {
|
||||
AgentSetupView(modifier, onDone = { setup = false })
|
||||
return
|
||||
}
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
var draft by rememberSaveable { mutableStateOf("") }
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
val send = {
|
||||
if (!working && draft.isNotBlank()) {
|
||||
AgentHost.send(context, draft)
|
||||
draft = ""
|
||||
}
|
||||
}
|
||||
LaunchedEffect(AgentHost.entries.size) {
|
||||
if (AgentHost.entries.isNotEmpty()) list.animateScrollToItem(AgentHost.entries.size - 1)
|
||||
}
|
||||
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
|
||||
Column(modifier.fillMaxSize()) {
|
||||
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)
|
||||
Text(AgentHost.harness.name, fontSize = 13.sp, color = pal.onSurfaceVariant)
|
||||
}
|
||||
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty()) { AgentHost.forget(context) }
|
||||
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working) { setup = true }
|
||||
}
|
||||
if (AgentHost.entries.isEmpty() && !working) {
|
||||
Column(Modifier.weight(1f).fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Icon(Icons.Outlined.AutoAwesome, null, tint = pal.primary, modifier = Modifier.size(40.dp))
|
||||
Text(stringResource(R.string.agent_empty), fontSize = 15.sp, color = pal.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center, modifier = Modifier.widthIn(max = 460.dp).padding(top = 12.dp))
|
||||
}
|
||||
} else {
|
||||
LazyColumn(Modifier.weight(1f).fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
itemsIndexed(AgentHost.entries) { _, entry -> AgentEntry(entry) }
|
||||
if (working) item {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) {
|
||||
CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary)
|
||||
Text(stringResource(R.string.agent_working), fontSize = 13.sp, color = pal.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 16.dp).clip(Shape16).background(colors.surface)
|
||||
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(start = 18.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
|
||||
) {
|
||||
Box(Modifier.weight(1f).padding(vertical = 8.dp)) {
|
||||
if (draft.isEmpty()) Text(stringResource(R.string.agent_hint), fontSize = 16.sp, color = pal.onSurfaceVariant)
|
||||
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() }),
|
||||
maxLines = 5,
|
||||
)
|
||||
}
|
||||
val canSend = !working && draft.isNotBlank()
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(44.dp).clip(CircleShape)
|
||||
.background(if (canSend) pal.primary else pal.surfaceVariant)
|
||||
.clickable(enabled = working || canSend) { if (working) AgentHost.stop() else send() }
|
||||
.testTag("agent-send"),
|
||||
) {
|
||||
Icon(
|
||||
if (working) Icons.Outlined.Stop else Icons.AutoMirrored.Outlined.Send,
|
||||
stringResource(if (working) R.string.agent_stop else R.string.agent_send),
|
||||
tint = if (canSend) pal.onPrimary else pal.onSurfaceVariant, modifier = Modifier.size(20.dp),
|
||||
)
|
||||
AgentHeader(panel, { panel = if (panel == it) AgentPanel.NONE else it }, onSetup = { setup = true })
|
||||
when (panel) {
|
||||
AgentPanel.HISTORY -> AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE }
|
||||
AgentPanel.PROCESSES -> AgentProcessList(Modifier.weight(1f))
|
||||
else -> {
|
||||
if (panel == AgentPanel.MODEL) AgentModelPicker()
|
||||
AgentConversation(Modifier.weight(1f))
|
||||
AgentStatus()
|
||||
AgentComposer(inputModifier) { panel = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HeaderAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, enabled: Boolean, onClick: () -> Unit) {
|
||||
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, 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 = 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)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(start = 8.dp).size(44.dp).clip(Shape12).background(pal.surfaceVariant)
|
||||
.clickable(enabled = enabled, onClick = onClick),
|
||||
modifier = Modifier.padding(start = 8.dp).size(44.dp).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),
|
||||
) {
|
||||
Icon(icon, label, tint = if (enabled) pal.onBackground else pal.onSurfaceVariant.copy(alpha = 0.5f), modifier = Modifier.size(22.dp))
|
||||
Icon(icon, label, tint = when {
|
||||
selected -> pal.primary
|
||||
enabled -> pal.onBackground
|
||||
else -> pal.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
}, modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AgentEntry(entry: Entry) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
private fun AgentConversation(modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
when (entry) {
|
||||
is Entry.Asked -> Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
|
||||
Text(entry.text, fontSize = 15.sp, color = pal.onPrimary,
|
||||
modifier = Modifier.widthIn(max = 560.dp).clip(Shape16).background(pal.primary).padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
}
|
||||
is Entry.Said -> AgentMarkdown(entry.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
|
||||
is Entry.Used -> Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(entry.tool, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.primary)
|
||||
if (entry.detail.isNotEmpty()) Text(entry.detail, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 8.dp))
|
||||
}
|
||||
is Entry.Finished -> entry.error?.let {
|
||||
Text(stringResource(R.string.agent_failed, it), fontSize = 13.sp, color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The Markdown agents write: headings, lists, fenced code, `code` and **bold**. */
|
||||
@Composable
|
||||
private fun AgentMarkdown(text: String, modifier: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
for (block in markdownBlocks(text)) when (block) {
|
||||
is MdBlock.Code -> Text(block.text, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface,
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(12.dp))
|
||||
is MdBlock.Line -> Text(
|
||||
inlineMarkdown(block.text, pal.primary2, pal.surfaceVariant),
|
||||
fontSize = if (block.heading) 17.sp else 15.sp,
|
||||
fontWeight = if (block.heading) FontWeight.Bold else null,
|
||||
lineHeight = 22.sp, color = colors.onSurface,
|
||||
modifier = if (block.bullet) Modifier.padding(start = 12.dp) else Modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
data class Line(val text: String, val heading: Boolean = false, val bullet: Boolean = false) : MdBlock
|
||||
data class Code(val text: String) : MdBlock
|
||||
}
|
||||
|
||||
private val HEADING = Regex("^#{1,6}\\s+")
|
||||
private val BULLET = Regex("^\\s*[-*+]\\s+")
|
||||
|
||||
internal fun markdownBlocks(text: String): List<MdBlock> {
|
||||
val out = mutableListOf<MdBlock>()
|
||||
val code = StringBuilder()
|
||||
var inCode = false
|
||||
for (raw in text.lines()) {
|
||||
if (raw.trimStart().startsWith("```")) {
|
||||
if (inCode) {
|
||||
out += MdBlock.Code(code.toString().trimEnd('\n'))
|
||||
code.clear()
|
||||
}
|
||||
inCode = !inCode
|
||||
continue
|
||||
}
|
||||
if (inCode) {
|
||||
code.append(raw).append('\n')
|
||||
continue
|
||||
}
|
||||
val line = raw.trimEnd()
|
||||
if (line.isBlank()) continue
|
||||
val heading = HEADING.find(line)
|
||||
val bullet = BULLET.find(line)
|
||||
out += when {
|
||||
heading != null -> MdBlock.Line(line.substring(heading.range.last + 1), heading = true)
|
||||
bullet != null -> MdBlock.Line("• " + line.substring(bullet.range.last + 1), bullet = true)
|
||||
else -> MdBlock.Line(line)
|
||||
}
|
||||
}
|
||||
if (inCode && code.isNotEmpty()) out += MdBlock.Code(code.toString().trimEnd('\n'))
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun inlineMarkdown(text: String, codeColor: Color, codeBackground: Color): AnnotatedString = buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
val boldEnd = if (text.startsWith("**", i)) text.indexOf("**", i + 2) else -1
|
||||
val tickEnd = if (text[i] == '`') text.indexOf('`', i + 1) else -1
|
||||
when {
|
||||
boldEnd > i + 2 -> {
|
||||
withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(text, i + 2, boldEnd) }
|
||||
i = boldEnd + 2
|
||||
}
|
||||
tickEnd > i + 1 -> {
|
||||
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, color = codeColor, background = codeBackground)) { append(text, i + 1, tickEnd) }
|
||||
i = tickEnd + 1
|
||||
}
|
||||
else -> append(text[i++])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private object BubblePlace {
|
||||
var x by mutableStateOf(Float.NaN)
|
||||
var y by mutableStateOf(Float.NaN)
|
||||
var hidden by mutableStateOf(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent's bubble over a session: there once the agent has been used, pulsing while it works,
|
||||
* marked when a reply or failure has not been seen. Drag it to either edge; a long press hides it
|
||||
* until the next session.
|
||||
*/
|
||||
@Composable
|
||||
internal fun AgentBubble(onOpen: () -> Unit) {
|
||||
if (!AgentHost.installed || BubblePlace.hidden || AgentHost.entries.isEmpty()) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val density = androidx.compose.ui.platform.LocalDensity.current
|
||||
val size = 56.dp
|
||||
val sizePx = with(density) { size.toPx() }
|
||||
val margin = with(density) { 12.dp.toPx() }
|
||||
val list = rememberLazyListState()
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
val pulse = androidx.compose.animation.core.rememberInfiniteTransition(label = "agentPulse")
|
||||
val ring by pulse.animateFloat(
|
||||
0.35f, 1f,
|
||||
androidx.compose.animation.core.infiniteRepeatable(androidx.compose.animation.core.tween(900), androidx.compose.animation.core.RepeatMode.Reverse),
|
||||
label = "agentRing",
|
||||
)
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val width = constraints.maxWidth.toFloat()
|
||||
val height = constraints.maxHeight.toFloat()
|
||||
if (BubblePlace.x.isNaN()) {
|
||||
BubblePlace.x = width - sizePx - margin
|
||||
BubblePlace.y = height * 0.3f
|
||||
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(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
|
||||
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
|
||||
}
|
||||
if (AgentHost.entries.isEmpty() && !working) {
|
||||
Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Icon(Icons.Outlined.AutoAwesome, null, tint = pal.primary, modifier = Modifier.size(40.dp))
|
||||
Text(stringResource(R.string.agent_empty), fontSize = 15.sp, color = pal.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center, modifier = Modifier.widthIn(max = 460.dp).padding(top = 12.dp))
|
||||
}
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
.offset { androidx.compose.ui.unit.IntOffset(BubblePlace.x.toInt(), BubblePlace.y.toInt()) }
|
||||
.size(size)
|
||||
.graphicsLayer { alpha = if (working || AgentHost.unseen) 1f else 0.7f }
|
||||
.clip(androidx.compose.foundation.shape.CircleShape)
|
||||
.background(colors.surface)
|
||||
.border(
|
||||
2.dp,
|
||||
if (working) colors.primary.copy(alpha = ring) else if (AgentHost.failed && AgentHost.unseen) colors.error else colors.outlineVariant,
|
||||
androidx.compose.foundation.shape.CircleShape,
|
||||
)
|
||||
.pointerInput(width, height) {
|
||||
detectDragGestures(onDragEnd = {
|
||||
BubblePlace.x = if (BubblePlace.x + sizePx / 2 < width / 2) margin else width - sizePx - margin
|
||||
}) { change, drag ->
|
||||
change.consume()
|
||||
BubblePlace.x = (BubblePlace.x + drag.x).coerceIn(0f, width - sizePx)
|
||||
BubblePlace.y = (BubblePlace.y + drag.y).coerceIn(0f, height - sizePx)
|
||||
}
|
||||
}
|
||||
.pointerInput(Unit) {
|
||||
detectTapGestures(onTap = { onOpen() }, onLongPress = { BubblePlace.hidden = true })
|
||||
}
|
||||
.testTag("agent-bubble"),
|
||||
) {
|
||||
Icon(androidx.compose.material.icons.Icons.Outlined.AutoAwesome, stringResource(R.string.rail_agent), tint = colors.primary)
|
||||
if (AgentHost.unseen && !working) Box(
|
||||
Modifier.align(Alignment.TopEnd).padding(6.dp).size(10.dp)
|
||||
.clip(androidx.compose.foundation.shape.CircleShape)
|
||||
.background(if (AgentHost.failed) colors.error else colors.primary),
|
||||
return
|
||||
}
|
||||
val start = AgentHost.entries.indexOfLast { it is Entry.Asked }
|
||||
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)
|
||||
}
|
||||
if (working) item { AgentLive() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The reply being written, and what the agent is doing right now. */
|
||||
@Composable
|
||||
private fun AgentLive() {
|
||||
val pal = LocalPalette.current
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (AgentHost.liveThinking.isNotBlank()) AgentThought(AgentHost.liveThinking, live = true)
|
||||
if (AgentHost.live.isNotBlank()) AgentMarkdown(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
|
||||
val running = AgentHost.running()
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) {
|
||||
CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary)
|
||||
val elapsed = clock((AgentHost.now - AgentHost.turnStarted) / 1000)
|
||||
Text(
|
||||
if (running != null) stringResource(R.string.agent_running, running.tool, elapsed) else stringResource(R.string.agent_thinking_for, elapsed),
|
||||
fontSize = 13.sp, color = pal.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun clock(seconds: Long): String {
|
||||
val s = seconds.coerceAtLeast(0)
|
||||
return when {
|
||||
s < 60 -> "${s}s"
|
||||
s < 3600 -> "${s / 60}m ${s % 60}s"
|
||||
else -> "${s / 3600}h ${s % 3600 / 60}m"
|
||||
}
|
||||
}
|
||||
|
||||
/** Above the composer: a Lab build's progress, the todo item in progress, and queued messages. */
|
||||
@Composable
|
||||
private fun AgentStatus() {
|
||||
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),
|
||||
)
|
||||
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 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab.stage) {
|
||||
"building" -> stringResource(R.string.agent_lab_stage_building, lab.permille / 10)
|
||||
"packaging" -> stringResource(R.string.agent_lab_stage_packaging)
|
||||
"restarting" -> stringResource(R.string.agent_lab_stage_restarting)
|
||||
"ready", "prepared" -> stringResource(R.string.agent_lab_stage_ready)
|
||||
"failed" -> stringResource(R.string.agent_lab_stage_failed, lab.task)
|
||||
else -> stringResource(R.string.agent_lab_stage_starting)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AgentComposer(inputModifier: Modifier, onPanel: (AgentPanel) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var draft by rememberSaveable { mutableStateOf("") }
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
val send = send@{
|
||||
val text = draft.trim()
|
||||
when (text.substringBefore(' ')) {
|
||||
"/new" -> AgentHost.forget(context)
|
||||
"/model" -> onPanel(AgentPanel.MODEL)
|
||||
"/plan" -> AgentHost.choosePlan(context, !AgentHost.plan)
|
||||
"/history" -> onPanel(AgentPanel.HISTORY)
|
||||
"/processes" -> onPanel(AgentPanel.PROCESSES)
|
||||
"/stop" -> AgentHost.stop(context)
|
||||
else -> {
|
||||
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
|
||||
AgentHost.send(context, text, AgentAttachments.pending.toList())
|
||||
AgentAttachments.pending.clear()
|
||||
}
|
||||
}
|
||||
draft = ""
|
||||
}
|
||||
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()),
|
||||
) {
|
||||
for (command in matches) Text(
|
||||
command, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = pal.primary,
|
||||
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).clickable { draft = "$command " }.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (AgentAttachments.pending.isNotEmpty()) Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
) {
|
||||
for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) }
|
||||
}
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 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),
|
||||
) {
|
||||
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() }),
|
||||
maxLines = 6,
|
||||
)
|
||||
}
|
||||
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() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AttachButton() {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||
if (uris.isEmpty()) return@rememberLauncherForActivityResult
|
||||
val chat = AgentHost.chat
|
||||
Thread({
|
||||
val paths = AgentAttachments.copy(context, chat, uris)
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post { AgentAttachments.pending.addAll(paths) }
|
||||
}, "agent-attach").start()
|
||||
}
|
||||
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
|
||||
runCatching { picker.launch(arrayOf("*/*")) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RoundButton(
|
||||
icon: ImageVector, label: String, background: androidx.compose.ui.graphics.Color, tint: androidx.compose.ui.graphics.Color,
|
||||
tag: String, enabled: Boolean = true, onClick: () -> Unit,
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(start = 6.dp).size(46.dp).clip(CircleShape).background(background)
|
||||
.clickable(enabled = enabled, onClick = onClick).testTag(tag),
|
||||
) {
|
||||
Icon(icon, label, tint = tint, modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import android.text.format.Formatter
|
||||
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.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
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.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentChats
|
||||
import com.droiddeck.launcher.agent.AgentHarness
|
||||
import com.droiddeck.launcher.agent.AgentHost
|
||||
import com.droiddeck.launcher.agent.AgentProcesses
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** The model and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
|
||||
@Composable
|
||||
internal fun AgentModelPicker() {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val models = remember(AgentHost.harness) { AgentHost.models(context) }
|
||||
Column(Modifier.fillMaxWidth().padding(bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
|
||||
val choices = listOf(AgentHarness.Model("", stringResource(R.string.agent_model_default))) + models
|
||||
for (choice in choices) {
|
||||
val id = choice.id.ifEmpty { null }
|
||||
if (id == AgentHost.model) PrimaryButton(choice.label, compact = true) {}
|
||||
else SecondaryButton(choice.label, compact = true) { AgentHost.chooseModel(context, id) }
|
||||
}
|
||||
}
|
||||
if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(stringResource(R.string.agent_plan_hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
|
||||
}
|
||||
ToggleSwitch(AgentHost.plan, label = stringResource(R.string.agent_plan)) { AgentHost.choosePlan(context, it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AgentHistory(modifier: Modifier, onOpened: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var version by remember { mutableIntStateOf(0) }
|
||||
val chats by produceState(emptyList<AgentChats.Chat>(), version, AgentHost.entries.size) {
|
||||
value = withContext(Dispatchers.IO) { AgentChats.list(context) }
|
||||
}
|
||||
if (chats.isEmpty()) {
|
||||
Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.agent_history_empty), fontSize = 15.sp, color = pal.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
items(chats, key = { it.id }) { chat ->
|
||||
var armed by remember(chat.id) { mutableStateOf(false) }
|
||||
val current = chat.id == AgentHost.chat
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
|
||||
.clickable(enabled = !working || current) {
|
||||
AgentHost.open(context, chat.id)
|
||||
onOpened()
|
||||
}
|
||||
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (armed) stringResource(R.string.agent_history_delete_warning)
|
||||
else AgentHarness.byId(chat.harness).name + " · " + DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS),
|
||||
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
SecondaryButton(
|
||||
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
|
||||
enabled = !(current && working),
|
||||
) {
|
||||
if (armed) {
|
||||
AgentHost.delete(context, chat.id)
|
||||
version++
|
||||
} else armed = true
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Processes in the Linux userland, the agent's own first, each with a way to end it. */
|
||||
@Composable
|
||||
internal fun AgentProcessList(modifier: Modifier) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
var procs by remember { mutableStateOf<List<AgentProcesses.Proc>?>(null) }
|
||||
LaunchedEffect(refresh) {
|
||||
while (true) {
|
||||
procs = withContext(Dispatchers.IO) { AgentProcesses.snapshot(AgentHost.turnPid) }
|
||||
delay(2_000)
|
||||
}
|
||||
}
|
||||
val list = procs ?: return
|
||||
if (list.isEmpty()) {
|
||||
Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.agent_processes_empty), fontSize = 15.sp, color = pal.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
items(list, key = { it.pid }) { proc ->
|
||||
var open by remember(proc.pid) { mutableStateOf(false) }
|
||||
Column(Modifier.fillMaxWidth().clickable { open = !open }.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-process")) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(proc.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
if (proc.agent) Text(stringResource(R.string.agent_process_agent), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = pal.primary,
|
||||
modifier = Modifier.clip(Shape12).background(pal.primary.copy(alpha = 0.15f)).padding(horizontal = 6.dp, vertical = 1.dp))
|
||||
}
|
||||
Text(
|
||||
listOf("pid ${proc.pid}", clock(proc.seconds), Formatter.formatShortFileSize(context, proc.rssKb * 1024), "${proc.cpuPercent}% CPU").joinToString(" · "),
|
||||
fontSize = 12.5.sp, color = pal.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.agent_process_stop), compact = true) {
|
||||
AgentProcesses.killTree(proc.pid)
|
||||
refresh++
|
||||
}
|
||||
}
|
||||
SelectionContainer {
|
||||
Text(proc.args, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
|
||||
maxLines = if (open) 40 else 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1161,7 +1161,49 @@
|
||||
<string name="agent_storage_reinstall_warning">Setup can install it again; sign-ins are kept</string>
|
||||
<string name="agent_resumed">DroidDeck restarted on your Lab build. Continue where you left off.</string>
|
||||
<string name="agent_empty">Ask it why a game won\'t start, to explain a log, or to change DroidDeck and try the change on this device.</string>
|
||||
<string name="agent_failed">Stopped: %1$s</string>
|
||||
<string name="agent_failed">Failed: %1$s</string>
|
||||
<string name="agent_exited">%1$s ended (exit %2$d)</string>
|
||||
<string name="agent_stopped">Stopped</string>
|
||||
<string name="agent_tokens">%1$s in · %2$s out</string>
|
||||
<string name="agent_thinking">Thinking</string>
|
||||
<string name="agent_thought">Thought</string>
|
||||
<string name="agent_thinking_for">Thinking · %1$s</string>
|
||||
<string name="agent_running">%1$s · %2$s</string>
|
||||
<string name="agent_tool_input">INPUT</string>
|
||||
<string name="agent_tool_output">OUTPUT</string>
|
||||
<string name="agent_tool_running">Running…</string>
|
||||
<string name="agent_tool_no_result">No result: the turn ended first</string>
|
||||
<string name="agent_tool_empty">No output</string>
|
||||
<string name="agent_hint_working">Type to queue the next message</string>
|
||||
<string name="agent_queue">Queue</string>
|
||||
<string name="agent_queued">Next: %1$s</string>
|
||||
<string name="agent_unqueue">Don\'t send</string>
|
||||
<string name="agent_attach">Attach</string>
|
||||
<string name="agent_remove_attachment">Remove</string>
|
||||
<string name="agent_model_default">Default</string>
|
||||
<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>
|
||||
<string name="agent_history">Conversations</string>
|
||||
<string name="agent_history_empty">No conversations yet</string>
|
||||
<string name="agent_history_delete">Delete</string>
|
||||
<string name="agent_history_delete_warning">Deletes it and its attachments</string>
|
||||
<string name="agent_processes">Processes</string>
|
||||
<string name="agent_processes_empty">Nothing is running in the Linux userland</string>
|
||||
<string name="agent_process_agent">AGENT</string>
|
||||
<string name="agent_process_stop">Stop</string>
|
||||
<string name="agent_lab_building">Lab build</string>
|
||||
<string name="agent_lab_preparing">Preparing Lab builds</string>
|
||||
<string name="agent_lab_progress">Lab build %1$d%% · about %2$s left</string>
|
||||
<string name="agent_lab_left">about %1$s left</string>
|
||||
<string name="agent_lab_cancel">Cancel</string>
|
||||
<string name="agent_lab_cancel_confirm">Cancel build</string>
|
||||
<string name="agent_lab_stage_starting">Starting</string>
|
||||
<string name="agent_lab_stage_building">%1$d%%</string>
|
||||
<string name="agent_lab_stage_packaging">Packaging</string>
|
||||
<string name="agent_lab_stage_restarting">Restarting DroidDeck on it</string>
|
||||
<string name="agent_lab_stage_ready">Done</string>
|
||||
<string name="agent_lab_stage_failed">Failed: %1$s</string>
|
||||
<string name="agent_setup_title">Set up the agent</string>
|
||||
<string name="agent_setup_runtime">Install the Linux runtime in Setup first.</string>
|
||||
<string name="agent_setup_retry">Retry</string>
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.agent
|
||||
|
||||
import com.droiddeck.launcher.agent.AgentHost.Entry
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -20,64 +21,128 @@ class AgentHostTest {
|
||||
assertEquals(emptyList<Entry>(), event.entries)
|
||||
}
|
||||
|
||||
@Test fun claudeTextAndToolUseBecomeEntries() {
|
||||
@Test fun claudeTextThinkingAndToolUseBecomeEntries() {
|
||||
val event = ClaudeCode.parse(
|
||||
"""{"type":"assistant","session_id":"abc","message":{"content":[
|
||||
{"type":"text","text":" Looking at the log. "},
|
||||
{"type":"tool_use","name":"Bash","input":{"command":"droiddeckctl state\nmore"}},
|
||||
{"type":"thinking","thinking":"hidden"}]}}""",
|
||||
{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"droiddeckctl state\nmore"}},
|
||||
{"type":"thinking","thinking":"why"}],"usage":{"input_tokens":10,"cache_read_input_tokens":90,"output_tokens":5}}}""",
|
||||
)!!
|
||||
assertEquals(listOf(Entry.Said("Looking at the log."), Entry.Used("Bash", "droiddeckctl state")), event.entries)
|
||||
assertEquals(listOf(Entry.Said("Looking at the log."), Entry.Used("t1", "Bash", "droiddeckctl state", "droiddeckctl state\nmore"), Entry.Thought("why")), event.entries)
|
||||
assertEquals(105L, event.context)
|
||||
}
|
||||
|
||||
@Test fun aClaudeResultEndsTheTurn() {
|
||||
assertEquals(listOf(Entry.Finished(null)), ClaudeCode.parse("""{"type":"result","subtype":"success","is_error":false,"result":"done"}""")!!.entries)
|
||||
@Test fun claudeStreamsTextAsItIsWritten() {
|
||||
val event = ClaudeCode.parse("""{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}}""")!!
|
||||
assertEquals("Hel", event.text)
|
||||
assertEquals("hm", ClaudeCode.parse("""{"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"hm"}}}""")!!.thinking)
|
||||
assertNull(ClaudeCode.parse("""{"type":"stream_event","event":{"type":"message_start"}}"""))
|
||||
}
|
||||
|
||||
@Test fun claudeToolResultsAnswerTheirCall() {
|
||||
val event = ClaudeCode.parse(
|
||||
"""{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"text","text":"ok"}],"is_error":true}]}}""",
|
||||
)!!
|
||||
assertEquals(listOf(Entry.Result("t1", "ok", true)), event.entries)
|
||||
val entries = mutableListOf<Entry>(Entry.Used("t1", "Bash", "ls", "ls"))
|
||||
assertTrue(AgentChats.merge(entries, event.entries.single()))
|
||||
assertEquals(Entry.Used("t1", "Bash", "ls", "ls", "ok", true), entries.single())
|
||||
assertFalse(AgentChats.merge(entries, Entry.Result("unknown", "x", false)))
|
||||
}
|
||||
|
||||
@Test fun aClaudeResultEndsTheTurnWithItsUsage() {
|
||||
val event = ClaudeCode.parse("""{"type":"result","subtype":"success","is_error":false,"result":"done","duration_ms":4200,"total_cost_usd":0.05,"usage":{"input_tokens":3,"output_tokens":7}}""")!!
|
||||
assertEquals(listOf(Entry.Finished(null)), event.entries)
|
||||
assertEquals(AgentHost.Usage(4200, 0.05, 3, 7), event.usage)
|
||||
assertEquals(listOf(Entry.Finished("Invalid API key")),
|
||||
ClaudeCode.parse("""{"type":"result","subtype":"success","is_error":true,"result":"Invalid API key"}""")!!.entries)
|
||||
assertNull(ClaudeCode.parse("not json"))
|
||||
}
|
||||
|
||||
@Test fun claudeTurnsBypassPermissionsAndResume() {
|
||||
val first = ClaudeCode.turn("hi", null)
|
||||
assertTrue("bypassPermissions" in first && "--resume" !in first)
|
||||
assertEquals("abc", ClaudeCode.turn("hi", "abc").let { it[it.indexOf("--resume") + 1] })
|
||||
@Test fun claudeTurnsBypassPermissionsOrPlanAndTakeAModel() {
|
||||
val first = ClaudeCode.turn("hi", null, AgentHarness.Options())
|
||||
assertTrue("bypassPermissions" in first && "--resume" !in first && "--model" !in first && "--include-partial-messages" in first)
|
||||
val next = ClaudeCode.turn("hi", "abc", AgentHarness.Options(model = "opus", plan = true))
|
||||
assertEquals("abc", next[next.indexOf("--resume") + 1])
|
||||
assertEquals("opus", next[next.indexOf("--model") + 1])
|
||||
assertEquals("plan", next[next.indexOf("--permission-mode") + 1])
|
||||
}
|
||||
|
||||
@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("[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"}]}""")))
|
||||
}
|
||||
|
||||
@Test fun codexEventsBecomeEntries() {
|
||||
assertEquals("t1", Codex.parse("""{"type":"thread.started","thread_id":"t1"}""")!!.conversation)
|
||||
assertEquals(listOf(Entry.Used("Shell", "uname -m")),
|
||||
assertEquals(listOf(Entry.Used("i1", "Shell", "uname -m", "uname -m")),
|
||||
Codex.parse("""{"type":"item.started","item":{"id":"i1","type":"command_execution","command":"uname -m","status":"in_progress"}}""")!!.entries)
|
||||
assertEquals(listOf(Entry.Result("i1", "aarch64\n", false)),
|
||||
Codex.parse("""{"type":"item.completed","item":{"id":"i1","type":"command_execution","command":"uname -m","aggregated_output":"aarch64\n","exit_code":0}}""")!!.entries)
|
||||
assertEquals(listOf(Entry.Said("It is aarch64.")),
|
||||
Codex.parse("""{"type":"item.completed","item":{"id":"i2","type":"agent_message","text":"It is aarch64."}}""")!!.entries)
|
||||
assertEquals(listOf(Entry.Used("Edit", "a.kt, b.kt")),
|
||||
Codex.parse("""{"type":"item.completed","item":{"type":"file_change","changes":[{"path":"a.kt"},{"path":"b.kt"}]}}""")!!.entries)
|
||||
assertEquals(Entry.Used("i3", "Edit", "a.kt, b.kt", "a.kt\nb.kt"),
|
||||
Codex.parse("""{"type":"item.completed","item":{"id":"i3","type":"file_change","status":"completed","changes":[{"path":"a.kt"},{"path":"b.kt"}]}}""")!!.entries.first())
|
||||
assertEquals(listOf(Entry.Finished(null)), Codex.parse("""{"type":"turn.completed","usage":{}}""")!!.entries)
|
||||
assertEquals(listOf(Entry.Finished("quota")), Codex.parse("""{"type":"turn.failed","error":{"message":"quota"}}""")!!.entries)
|
||||
assertNull(Codex.parse("""{"type":"item.started","item":{"type":"reasoning"}}"""))
|
||||
}
|
||||
|
||||
@Test fun codexTurnsSkipItsSandboxAndResume() {
|
||||
@Test fun codexTurnsSkipItsSandboxResumeAndTakeAModel() {
|
||||
assertEquals(listOf("/root/.local/bin/codex", "exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", "hi"),
|
||||
Codex.turn("hi", null))
|
||||
assertEquals(listOf("exec", "resume", "t1"), Codex.turn("hi", "t1").subList(1, 4))
|
||||
}
|
||||
|
||||
@Test fun anUnknownHarnessFallsBackToClaudeCode() {
|
||||
assertEquals(Codex, AgentHarness.byId("codex"))
|
||||
assertEquals(ClaudeCode, AgentHarness.byId("gone"))
|
||||
Codex.turn("hi", null, AgentHarness.Options()))
|
||||
assertEquals(listOf("/root/.local/bin/codex", "exec", "resume", "t1", "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", "-m", "gpt", "hi"),
|
||||
Codex.turn("hi", "t1", AgentHarness.Options(model = "gpt")))
|
||||
}
|
||||
|
||||
@Test fun aTurnWithoutAnEndWasInterrupted() {
|
||||
assertTrue(AgentHost.interrupted(listOf(Entry.Asked("hi"), Entry.Used("Bash", "dd-lab-build"))))
|
||||
assertTrue(AgentHost.interrupted(listOf(Entry.Asked("hi"), Entry.Used("1", "Bash", "dd-lab-build"))))
|
||||
assertEquals(false, AgentHost.interrupted(listOf(Entry.Asked("hi"), Entry.Finished(null))))
|
||||
assertEquals(false, AgentHost.interrupted(emptyList()))
|
||||
}
|
||||
|
||||
@Test fun theTranscriptSurvivesARestart() {
|
||||
val entries = listOf(Entry.Asked("hi"), Entry.Said("hello"), Entry.Used("Read", "/root/x"), Entry.Finished(null), Entry.Finished("stopped"))
|
||||
val file = Files.createTempFile("transcript", ".jsonl").toFile()
|
||||
file.writeText(entries.joinToString("\n") { AgentHost.encode(it) } + "\nbroken line\n")
|
||||
assertEquals(entries, AgentHost.readTranscript(file))
|
||||
assertEquals(emptyList<Entry>(), AgentHost.readTranscript(File(file.path + ".missing")))
|
||||
@Test fun aChatRoundTripsThroughItsFile() {
|
||||
val file = Files.createTempFile("chat", ".jsonl").toFile()
|
||||
AgentChats.start(file, "claude")
|
||||
AgentChats.appendConversation(file, "abc")
|
||||
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),
|
||||
)
|
||||
written.forEach { AgentChats.append(file, it) }
|
||||
file.appendText("broken line\n")
|
||||
val loaded = AgentChats.read(file)
|
||||
assertEquals("claude", loaded.harness)
|
||||
assertEquals("abc", loaded.conversation)
|
||||
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),
|
||||
), loaded.entries)
|
||||
assertEquals(emptyList<Entry>(), AgentChats.read(File(file.path + ".missing")).entries)
|
||||
}
|
||||
|
||||
@Test fun longOutputKeepsItsEnd() {
|
||||
val clipped = AgentChats.clip("a".repeat(30_000) + "END")
|
||||
assertTrue(clipped.endsWith("END") && clipped.length < 30_000)
|
||||
}
|
||||
|
||||
@Test fun attachmentsAreListedForTheAgent() {
|
||||
assertEquals("look", AgentAttachments.prompt("look", emptyList()))
|
||||
assertEquals("look\n\nAttached files (read them with your tools):\n- /root/a.png", AgentAttachments.prompt("look", listOf("/root/a.png")))
|
||||
}
|
||||
|
||||
@Test fun procStatFieldsCountFromTheEndOfTheName() {
|
||||
val stat = AgentProcesses.parseStat("1234 (java (x) y) S 1200 1234 1234 0 -1 4194304 10 0 0 0 150 50 0 0 20 0 30 0 98765 1000000 2048 18446744073709551615")
|
||||
assertEquals(1200, stat.ppid)
|
||||
assertEquals(200L, stat.ticks)
|
||||
assertEquals(98765L, stat.startTicks)
|
||||
assertEquals(2048L, stat.rssPages)
|
||||
}
|
||||
|
||||
@Test fun labProgressIsRead() {
|
||||
val p = LabProgress.parse("""{"stage":"building","mode":"build","permille":420,"task":":app:compileReleaseKotlin","done":120,"total":300,"eta":95,"elapsed":30,"pid":77}""")!!
|
||||
assertEquals(420, p.permille)
|
||||
assertTrue(p.running && !p.prepare)
|
||||
assertEquals(95, p.etaSeconds)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user