From 1cada9ad50d07c3768833846f77c6a27e1464019 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:29:38 -0500 Subject: [PATCH] fix(agent): protect retained Claude background work (#2678) * fix(agent): protect retained Claude background work * fix(agent): address retained session review findings * fix(agent): reset Claude cost tracking on clear --- .../droiddeck/launcher/agent/AgentChats.kt | 2 + .../com/droiddeck/launcher/agent/AgentHost.kt | 84 +++++++++++++++---- .../launcher/agent/AgentHostService.kt | 15 ++-- .../com/droiddeck/launcher/ui/AgentEntries.kt | 1 + .../launcher/agent/AgentHostServiceTest.kt | 51 +++++++++++ .../droiddeck/launcher/agent/AgentHostTest.kt | 18 +++- 6 files changed, 145 insertions(+), 26 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/agent/AgentHostServiceTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt index be9be4fd0e..d1096d7373 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt @@ -84,6 +84,7 @@ object AgentChats { 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.Notice -> JSONObject().put("notice", 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) @@ -119,6 +120,7 @@ object AgentChats { 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("notice") -> Entry.Notice(o.getString("notice")) 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.optString("parent")) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index 72f01ea3b5..d4cf0035b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -29,6 +29,7 @@ object AgentHost { sealed interface Entry { data class Asked(val text: String, val files: List = emptyList()) : Entry data class Said(val text: String) : Entry + data class Notice(val text: String) : Entry data class Thought(val text: String) : Entry /** * A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any. @@ -130,7 +131,12 @@ object AgentHost { var lab by mutableStateOf(null) private set - private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) + private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) { + var writingGeneration: Int? = null + var exitStatus: Int? = null + var costs: AgentCostTracker? = null + var clearingCosts = false + } private val main = Handler(Looper.getMainLooper()) private var turn: Turn? = null @@ -301,7 +307,7 @@ object AgentHost { live = "" liveThinking = "" turnStarted = SystemClock.elapsedRealtime() - AgentHostService.start(app) + AgentHostService.start(app)?.let { serviceWarning(app, it) } val current = harness val prompt = AgentAttachments.prompt(message, attached) turnPlanned = plan && current.plans @@ -314,14 +320,19 @@ object AgentHost { if (kept != null && line != null && sessionKey == key && kept.process.isAlive) { main.removeCallbacks(reap) turn = kept + kept.writingGeneration = gen + kept.clearingCosts = prompt == "/clear" Thread({ val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false) // The process died between turns: the same message goes to a new one, which resumes the conversation. - if (!written) main.post { + main.post { + if (kept.writingGeneration == gen) kept.writingGeneration = null if (generation == gen && session === kept) { - dropSession() - turn = null - spawn(app, gen, current, current.turn(prompt, conversation, options), line, key) + if (!written) { + dropSession() + turn = null + spawn(app, gen, current, current.turn(prompt, conversation, options), line, key) + } else kept.exitStatus?.let { processExited(app, kept, current, it) } } } }, "agent-input").start() @@ -346,7 +357,9 @@ object AgentHost { main.post { if (generation == gen) finish(app, e.message ?: "could not start") } return@Thread } - val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null) + val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply { + if (current === ClaudeCode && line != null) costs = AgentCostTracker() + } OrphanReaper.keep(started.pid) main.post { if (generation == gen && state == State.WORKING && turn == null) { @@ -375,20 +388,34 @@ object AgentHost { val status = runCatching { child.waitFor() }.getOrDefault(-1) OrphanReaper.release(started.pid) main.post { - if (session === started) { session = null; main.removeCallbacks(reap) } - if (turn === started) { - turn = null - if (state == State.WORKING) finish(app, app.getString(R.string.agent_exited, current.name, status)) - } + if (started.writingGeneration != null) started.exitStatus = status + else processExited(app, started, current, status) } }, "agent-output").start() } + private fun processExited(app: Context, exited: Turn, current: AgentHarness, status: Int) { + if (session === exited) { + session = null + launchedBackground = false + main.removeCallbacks(reap) + AgentHostService.backgroundDone(app) + } + if (turn === exited) { + turn = null + if (state == State.WORKING) finish(app, app.getString(R.string.agent_exited, current.name, status)) + } + } + + private fun serviceWarning(app: Context, error: Throwable) { + record(app, Entry.Notice("Unable to keep the agent running in the background: ${error.message ?: error.javaClass.simpleName}")) + } + /** One event from the CLI, which may belong to a turn it started on its own once the user's has ended. */ private fun handle(app: Context, from: Turn, event: AgentEvent) { if (event.background) { // A leftover task answered before the user's message is not the user's turn; one the CLI started is its own. - if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage) + if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it }) return } val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished } @@ -401,9 +428,16 @@ object AgentHost { live = "" liveThinking = "" turnStarted = SystemClock.elapsedRealtime() - AgentHostService.start(app) + AgentHostService.start(app)?.let { serviceWarning(app, it) } } - apply(app, event) + val finished = event.entries.filterIsInstance().firstOrNull() + if (finished != null && state == State.WORKING && from.clearingCosts) { + if (finished.error == null) from.costs?.reset() + from.clearingCosts = false + } + val applied = if (finished != null && state == State.WORKING && event.usage != null) + event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event + apply(app, applied) } /** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */ @@ -531,11 +565,13 @@ object AgentHost { live = "" liveThinking = "" val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage - record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null)) state = State.IDLE unseen = true failed = error != null - if (session != null && launchedBackground) AgentHostService.waitForBackground(app) else AgentHostService.stop(app) + if (session != null && launchedBackground) { + AgentHostService.waitForBackground(app)?.let { serviceWarning(app, it) } + } else AgentHostService.stop(app) + record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null)) // Claude Code now and then ends a resumed turn at once without reading the message; nothing // happened, so the message is sent once more. val asked = entries.lastOrNull { it is Entry.Asked } as? Entry.Asked @@ -781,3 +817,17 @@ internal fun choices(reply: String): Choices { val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() } return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options) } + +internal class AgentCostTracker { + private var previous = 0.0 + + fun reset() { previous = 0.0 } + + fun perTurn(usage: AgentHost.Usage): AgentHost.Usage { + val total = usage.costUsd + if (total == 0.0 && previous > 0.0) return usage + val delta = if (total >= previous) total - previous else total + previous = total + return usage.copy(costUsd = delta) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt index a253e80411..ef8130f1cc 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt @@ -42,15 +42,16 @@ class AgentHostService : Service() { /** Setup steps that keep the app alive while they run, besides the agent's turn. */ private var setupSteps = 0 - fun start(context: Context) { + fun start(context: Context): Throwable? { + if (started) { update(context); return null } lastText = null - started = true - runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) } - .onSuccess { awaiting++ } + return runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) } + .onSuccess { started = true; awaiting++ } + .exceptionOrNull() } fun stop(context: Context) { - if (setupSteps > 0) return + if (setupSteps > 0 || waiting) return started = false if (awaiting == 0) context.stopService(Intent(context, AgentHostService::class.java)) } @@ -61,9 +62,9 @@ class AgentHostService : Service() { */ @Volatile private var waiting = false - fun waitForBackground(context: Context) { + fun waitForBackground(context: Context): Throwable? { waiting = true - if (started) update(context) else start(context) + return if (started) { update(context); null } else start(context) } fun backgroundDone(context: Context) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt index 1ea5094ed7..ff282615f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt @@ -82,6 +82,7 @@ internal fun AgentEntry( if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent) } } + is Entry.Notice -> Text(entry.text, color = colors.error, modifier = Modifier.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, children) is Entry.Result -> Unit diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostServiceTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostServiceTest.kt new file mode 100644 index 0000000000..ed50c7e10f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostServiceTest.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.agent + +import android.content.ComponentName +import android.content.ContextWrapper +import android.content.Intent +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class AgentHostServiceTest { + private class ServiceContext : ContextWrapper(RuntimeEnvironment.getApplication()) { + var stops = 0 + var reject = false + override fun startForegroundService(service: Intent): ComponentName { + if (reject) throw IllegalStateException("start rejected") + return ComponentName(packageName, AgentHostService::class.java.name) + } + override fun stopService(service: Intent): Boolean { stops++; return true } + } + + @Test fun setupCompletionKeepsBackgroundWaitUntilItEnds() { + val context = ServiceContext() + AgentHostService.setupStarted(context) + val service = Robolectric.buildService(AgentHostService::class.java).create().get() + service.onStartCommand(Intent(context, AgentHostService::class.java), 0, 1) + assertNull(AgentHostService.waitForBackground(context)) + AgentHostService.setupEnded(context) + assertEquals(0, context.stops) + AgentHostService.backgroundDone(context) + assertEquals(1, context.stops) + } + + @Test fun rejectedForegroundStartIsReportedAndCanBeRetried() { + val context = ServiceContext() + context.reject = true + assertNotNull(AgentHostService.start(context)) + context.reject = false + assertNull(AgentHostService.start(context)) + val service = Robolectric.buildService(AgentHostService::class.java).create().get() + service.onStartCommand(Intent(context, AgentHostService::class.java), 0, 1) + AgentHostService.stop(context) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt index 6d84317791..30cb71009e 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt @@ -98,6 +98,19 @@ class AgentHostTest { assertNull(event.backgroundError) } + @Test fun retainedClaudeCostsAreRecordedOncePerProcess() { + val costs = AgentCostTracker() + fun usage(cost: Double) = AgentHost.Usage(1, cost, 1, 1) + assertEquals(0.05, costs.perTurn(usage(0.05)).costUsd, 0.000001) + assertEquals(0.02, costs.perTurn(usage(0.07)).costUsd, 0.000001) + assertEquals(0.0, costs.perTurn(usage(0.07)).costUsd, 0.000001) + costs.reset() + assertEquals(0.0, costs.perTurn(usage(0.0)).costUsd, 0.000001) + assertEquals(0.07, costs.perTurn(usage(0.07)).costUsd, 0.000001) + assertEquals(0.01, costs.perTurn(usage(0.01)).costUsd, 0.000001) + assertEquals(0.07, AgentCostTracker().perTurn(usage(0.07)).costUsd, 0.000001) + } + @Test fun aFailedTaskNotificationResultKeepsItsError() { val event = ClaudeCode.parse("""{"type":"result","is_error":true,"result":"API Error: overloaded","session_id":"s","usage":{"input_tokens":0,"output_tokens":0},"origin":{"kind":"task-notification"}}""")!! assertTrue(event.background) @@ -212,7 +225,7 @@ class AgentHostTest { 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.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Notice("service unavailable"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}"), Entry.Result("t1", "contents", false), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true), ) @@ -222,7 +235,7 @@ class AgentHostTest { 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.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Notice("service unavailable"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}", "contents", false), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true), ), loaded.entries) @@ -231,6 +244,7 @@ class AgentHostTest { @Test fun aTurnThatEndsWithNothingIsAnswerless() { assertTrue(AgentHost.answerless(listOf(Entry.Said("x"), Entry.Asked("go on"), Entry.Finished(null)))) + assertTrue(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Notice("service unavailable"), Entry.Finished(null)))) assertFalse(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Said("ok"), Entry.Finished(null)))) assertFalse(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Finished("boom")))) assertFalse(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Finished(null, stopped = true))))