Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。
feat(history): long-press a row to read the log behind it
booboosui4938e9c445ae
diff --git a/app/build.gradle b/app/build.gradleindex bcecfa9..4eaee45 100644--- a/app/build.gradle+++ b/app/build.gradle@@ -120,6 +120,12 @@ dependencies {implementation 'com.google.mlkit:barcode-scanning:17.2.0'testImplementation libs.junit+ // Unit tests run against android.jar's stubs, whose org.json throws+ // "not mocked" on construction. BrainTrace builds a JSONObject before it+ // can know tracing is off, so any test that reaches it needs a real+ // implementation on the unit-test classpath. Test scope only: the app still+ // serializes with Android's own org.json, and no test asserts on the JSON.+ testImplementation 'org.json:json:20240303'androidTestImplementation libs.ext.junitandroidTestImplementation libs.espresso.core}\ No newline at end of filediff --git a/app/src/main/java/net/kuafuai/andee/ScreenBodyService.kt b/app/src/main/java/net/kuafuai/andee/ScreenBodyService.ktindex 37c0ac7..2a792e9 100644--- a/app/src/main/java/net/kuafuai/andee/ScreenBodyService.kt+++ b/app/src/main/java/net/kuafuai/andee/ScreenBodyService.kt@@ -276,6 +276,33 @@ class ScreenBodyService : AccessibilityService() {openPageFrom(entry, file)}+ /**+ * Long-pressing a message row: the log behind it — see+ * [net.kuafuai.andee.ui.TracePage].+ *+ * **Off the main thread, and this is not optional.** Building the+ * page means reading and parsing `brain_trace.jsonl` — up to+ * [net.kuafuai.andee.brain.BrainTrace]'s ceiling per generation —+ * while the main thread is holding the ball's window. The read is+ * small for one turn (measured: ~8 records, 7 KB) but the file it+ * reads is not, and the cost of being wrong is a frozen ball.+ *+ * The gesture is only offered on rows that have a turn, so the+ * `?: return` here is a backstop rather than a path the user can+ * reach — see [net.kuafuai.andee.ui.ChatHistory.Entry.turn].+ *+ * Nothing is asked of the assistant, so as with [onTextOpen] this+ * starts no task and lights no glow: the dispatcher is deliberately+ * not involved.+ */+ override fun onTraceOpen(entry: net.kuafuai.andee.ui.ChatHistory.Entry) {+ val turn = entry.turn ?: return+ Thread {+ val file = net.kuafuai.andee.ui.TracePage.write(this@ScreenBodyService, turn)+ if (file != null) ui.post { openPageFrom(entry, file) }+ }.start()+ }+/*** A suggestion bubble on an empty card — the one turn the device* starts on the user's behalf.@@ -2078,6 +2105,14 @@ class ScreenBodyService : AccessibilityService() {/** The finished answer. See [onBrainProgress] for why this is not inline. */private fun onBrainFinal(text: String) {+ // Read first, before anything else can end the turn. This runs inside+ // the turn it is describing — `onFinal` is called from the loop thread+ // while `runTurn` is still going — but `LocalBrain.launch` clears the+ // turn in its `finally`, so the window is this function's entry, not+ // wherever the string is finally written below. Reading late would+ // attach null to real answers, which fails silently and looks exactly+ // like the feature not existing. See [BrainTrace.current].+ val turn = net.kuafuai.andee.brain.BrainTrace.currentTurn()if (acceptBrainOutput) {// The brain's own verdict on whether this conversation is still// open. Written before the speak below because [followUpWindow]@@ -2108,7 +2143,7 @@ class ScreenBodyService : AccessibilityService() {// fires many times per task with successive drafts of the// same sentence — logging those would bury the answer under// its own rough cuts.- net.kuafuai.andee.ui.ChatHistory.addAssistant(plain)+ net.kuafuai.andee.ui.ChatHistory.addAssistant(plain, turn)// Kept for one reason only: if speaking this fails and the card is// folded, the row above is `GONE` and this string is the last copy// of the answer on the device. See [showAnswerAsCard].diff --git a/app/src/main/java/net/kuafuai/andee/brain/BrainTrace.kt b/app/src/main/java/net/kuafuai/andee/brain/BrainTrace.ktindex 3d7d8b8..ae34406 100644--- a/app/src/main/java/net/kuafuai/andee/brain/BrainTrace.kt+++ b/app/src/main/java/net/kuafuai/andee/brain/BrainTrace.kt@@ -14,6 +14,15 @@ import java.util.concurrent.Executors* trace anywhere. This file is app-private, read back with `run-as`, bounded* at two generations of [MAX_BYTES], and wiped with the chat history.*+ * **Every record says which turn it belongs to** — see [idOf], and do not match+ * on `gen` instead. That is what lets the scrollback open one row onto the work+ * behind it (see [net.kuafuai.andee.ui.TracePage]). One turn is a handful of+ * records, and they are four kinds: a `turn` (what was asked), a `step` per+ * model reply (what it said, what it reasoned, and what the request cost in+ * prompt tokens), a `tool` per call (name, arguments, duration, result), and an+ * `end` saying why it stopped. Measured on the test device: ~8 records and+ * 7.3 KB for an ordinary turn.+ ** Vault results are never written: `get_vault` returns phone numbers and* emails in the clear, and a debug file is the last place they should land.*/@@ -24,6 +33,63 @@ object BrainTrace {private const val MAX_BYTES = 1_000_000Lprivate const val MAX_FIELD = 4_000+ /**+ * Wall clock at class load, which for this file is process start.+ *+ * It exists because [idOf]'s other half is not unique on its own. See there.+ */+ private val run = System.currentTimeMillis()++ /**+ * The turn being recorded right now, or null between turns.+ *+ * This is how the scrollback finds a row's log: the value is copied onto+ * [net.kuafuai.andee.ui.ChatHistory.Entry.turn] when the answer is written,+ * and the reader matches it back here. See [idOf] for why it is not just+ * `gen`.+ *+ * Cleared by [net.kuafuai.andee.brain.LocalBrain] when a turn **ends**, not+ * when it is read. That direction matters for one path: `submit` returns+ * early when the API key is missing, and the row it writes is a device+ * complaint with no log behind it. Reading-and-clearing would still leave+ * *that* row claiming whatever the previous turn recorded, whereas ending+ * clears it before the next turn can inherit it.+ */+ @Volatile+ private var current: String? = null++ /**+ * The identity of turn [gen], and the only thing a caller should match a+ * log against.+ *+ * **`gen` alone is not enough, and this is measured rather than feared.**+ * It is [net.kuafuai.andee.brain.LocalBrain]'s in-memory `AtomicInteger`, so+ * it restarts at 1 with every process while this file is persistent and+ * append-only. On the test device `"gen":1` accounted for **176 of 278**+ * records — "the first turn since the last restart", 176 times over. A+ * scrollback that matched on `gen` would open a reinstall's first turn onto+ * yesterday's first turn, and there would be no visible sign it had.+ *+ * So the file records `run-gen`, `run` being the process's own start. A+ * timestamp rather than a random id because it also *sorts*: two runs order+ * the same way their turns do, which keeps the file readable end to end.+ */+ private fun idOf(gen: Int) = turnId(run, gen)++ /**+ * [idOf] with `run` passed in, so a test can stand in for a restart by+ * handing it two different stamps. See [idOf] for what the pair means.+ */+ internal fun turnId(run: Long, gen: Int) = "$run-$gen"++ /** The turn in flight, or null. See [current]. */+ fun currentTurn(): String? = current++ /** A turn ended, however it ended. See [current] for why this is not [currentTurn]. */+ fun clearTurn() {+ current = null+ }+private val exec = Executors.newSingleThreadExecutor { r ->Thread(r, "brain-trace").apply { isDaemon = true }}@@ -34,12 +100,28 @@ object BrainTrace {dir = context.applicationContext.filesDir}- fun turn(gen: Int, kind: String, text: String) =- append(JSONObject().put("ev", "turn").put("gen", gen).put("kind", kind).put("text", clip(text)))+ /**+ * A turn began — the user's words, a todo coming due, a sweep.+ *+ * Sets [current] as a side effect, so this must be called by whatever starts+ * the turn and before any [step] or [tool] of it.+ *+ * `gen` stays in the record beside `turn` even though it is redundant once+ * you have the latter: it is what makes a line legible to a person reading+ * the file, and records written before `turn` existed still have it. It is+ * **not** what a reader should match on — see [idOf].+ */+ fun turn(gen: Int, kind: String, text: String) {+ current = idOf(gen)+ append(+ JSONObject().put("ev", "turn").put("turn", idOf(gen)).put("gen", gen)+ .put("kind", kind).put("text", clip(text)),+ )+ }fun step(gen: Int, step: Int, content: String, reasoning: String, calls: Int, promptTokens: Int) =append(- JSONObject().put("ev", "step").put("gen", gen).put("step", step)+ JSONObject().put("ev", "step").put("turn", idOf(gen)).put("gen", gen).put("step", step).put("content", clip(content)).put("reasoning", clip(reasoning)).put("calls", calls).put("prompt_tokens", promptTokens),)@@ -47,13 +129,14 @@ object BrainTrace {fun tool(gen: Int, name: String, method: String?, args: String, result: String, ms: Long) {val secret = method?.startsWith("device.vault.") == trueappend(- JSONObject().put("ev", "tool").put("gen", gen).put("name", name)+ JSONObject().put("ev", "tool").put("turn", idOf(gen)).put("gen", gen).put("name", name).put("args", clip(args)).put("ms", ms).put("result", if (secret) "<vault result not traced>" else clip(result)),)}- fun end(gen: Int, why: String) = append(JSONObject().put("ev", "end").put("gen", gen).put("why", why))+ fun end(gen: Int, why: String) =+ append(JSONObject().put("ev", "end").put("turn", idOf(gen)).put("gen", gen).put("why", why))fun wipe(context: Context) {val d = context.applicationContext.filesDirdiff --git a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.ktindex 776f345..cd28ee8 100644--- a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt+++ b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt@@ -346,6 +346,13 @@ class LocalBrain(// dozen `return`s: leaving the kind set on any of them would// make the *next* turn refuse every device tool.currentKind = TurnKind.USER+ // The same place, for the same reason, and one more: the trace's+ // idea of "the turn in flight" has to end with the turn even+ // when the turn recorded almost nothing. `submit`'s missing-key+ // early return writes a scrollback row without ever reaching+ // here, which is exactly why this clears rather than being+ // consumed on read — see [BrainTrace.current].+ BrainTrace.clearTurn()busy.set(false)dropUnfinishedHarvest(kind)if (kind == TurnKind.SWEEP) onSweepSpent(turnTokens)diff --git a/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt b/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.ktindex 662c8e5..9a35204 100644--- a/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt@@ -41,6 +41,9 @@ object ChatHistory {/*** @param page for [Role.PAGE], the archived HTML — null once it has been* evicted, which is how a row knows to stop offering to re-open itself.+ * @param turn which run of the brain produced this row, named the way+ * [net.kuafuai.andee.brain.BrainTrace] names it, or null when there is no+ * log to open — see [addAssistant].*/data class Entry(val id: Long,@@ -48,6 +51,7 @@ object ChatHistory {val role: Role,val text: String,val page: File?,+ val turn: String? = null,)/**@@ -158,7 +162,24 @@ object ChatHistory {fun addUser(text: String) = add(Role.USER, text, null)- fun addAssistant(text: String) = add(Role.ASSISTANT, text, null)+ /**+ * The assistant's finished answer.+ *+ * @param turn the run of the local brain this came out of, so the row can be+ * long-pressed into its own log (see [net.kuafuai.andee.ui.TracePage]).+ * **Null is the normal case, not an oversight.** Most answers in the+ * scrollback were not produced by a turn at all — a scene being entered, a+ * notification read out, a line from `ScreenController` — and the hub+ * brain writes no trace even when it did answer. A row with no [Entry.turn]+ * simply has no log to offer, and must not pretend otherwise: an entry+ * point that opens an empty page is worse than no entry point.+ *+ * The caller reads it from [net.kuafuai.andee.brain.BrainTrace.currentTurn]+ * *while the turn is still in flight*, which is safe because this is+ * called from `onFinal` on the loop thread and the next turn cannot have+ * started.+ */+ fun addAssistant(text: String, turn: String? = null) = add(Role.ASSISTANT, text, null, turn)/** Call through [CardUi.error], which de-dups bursts before they get here. */fun addError(text: String) = add(Role.ERROR, text, null)@@ -189,14 +210,14 @@ object ChatHistory {return file}- private fun add(role: Role, text: String, page: File?) {+ private fun add(role: Role, text: String, page: File?, turn: String? = null) {if (appContext == null) returnval clean = text.trim().let {if (it.length > MAX_TEXT) it.take(MAX_TEXT) + "…" else it}if (clean.isEmpty()) returnsynchronized(lock) {- entries.add(Entry(nextId++, System.currentTimeMillis(), role, clean, page))+ entries.add(Entry(nextId++, System.currentTimeMillis(), role, clean, page, turn))trim()save()}@@ -249,6 +270,7 @@ object ChatHistory {.put("role", e.role.name).put("text", e.text).put("page", e.page?.name ?: JSONObject.NULL)+ .put("turn", e.turn ?: JSONObject.NULL))}f.writeText(arr.toString())@@ -271,8 +293,12 @@ object ChatHistory {// a file that isn't there is worse than one that doesn't.val page = o.optString("page").takeIf { it.isNotEmpty() && it != "null" }?.let { File(dir, it) }?.takeIf { it.exists() }+ // Same treatment as `page`: a row written before this field+ // existed, or by a build that never had a turn for it, reads as+ // absent rather than as a turn named "null".+ val turn = o.optString("turn").takeIf { it.isNotEmpty() && it != "null" }val id = o.optLong("id")- entries.add(Entry(id, o.optLong("ts"), role, o.optString("text"), page))+ entries.add(Entry(id, o.optLong("ts"), role, o.optString("text"), page, turn))if (id >= nextId) nextId = id + 1}}.onFailure {diff --git a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.ktindex 137ee39..9668cc3 100644--- a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt@@ -219,6 +219,21 @@ class FloatingWindowUi(*/fun onTextOpen(entry: ChatHistory.Entry)+ /**+ * A message row, long-pressed, for the log behind it — see+ * [net.kuafuai.andee.ui.TracePage].+ *+ * Handed out rather than built here for the same reason plus a sharper+ * one: turning a turn id into a page means reading and parsing the trace+ * file, which blocks and must not do so on the UI thread. The window+ * knows how to hold a row; only the service knows how to read a log.+ *+ * Never fired for a row whose [ChatHistory.Entry.turn] is null — there+ * is no log to read, and a gesture that opens an empty page is worse+ * than one that stays still.+ */+ fun onTraceOpen(entry: ChatHistory.Entry)+/*** A suggestion bubble on a card with no history — the user taking the* assistant up on one of the things it says it can do.@@ -2206,6 +2221,7 @@ class FloatingWindowUi(val history = HistoryListView(context).apply {onPageClick = { listeners.onHistoryPageClick(it) }onTextOpen = { listeners.onTextOpen(it) }+ onTraceOpen = { listeners.onTraceOpen(it) }onSuggestionClick = { name, title, example ->listeners.onSuggestionClick(name, title, example)}diff --git a/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt b/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.ktindex 87e627f..90863c6 100644--- a/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt@@ -57,7 +57,7 @@ class HistoryListView(private val context: Context) : ScrollView(context) {var onPageClick: ((ChatHistory.Entry) -> Unit)? = null/**- * Double-tapping a message — read it fullscreen. See [attachDoubleTap].+ * Double-tapping a message — read it fullscreen. See [attachRowGestures].** Handed out rather than opened here for the same reason page rows are: the* reader is a fullscreen screen, so the card has to fold out of its way@@ -65,6 +65,22 @@ class HistoryListView(private val context: Context) : ScrollView(context) {*/var onTextOpen: ((ChatHistory.Entry) -> Unit)? = null+ /**+ * Long-pressing a message row — what the device actually did to answer it.+ *+ * Handed out for the same reasons as the two above, and one of its own: the+ * log lives on disk and has to be read and rendered into a page before there+ * is anything to open, and that read must not happen on the UI thread. See+ * `ScreenBodyService.onTraceOpen`.+ *+ * **Only rows that have a log fire this.** A row with no+ * [ChatHistory.Entry.turn] — a scene being entered, a notification read out,+ * an answer from the hub brain — has nothing behind it, so the gesture stays+ * silent on it rather than opening a page that explains it is empty. See+ * [attachRowGestures].+ */+ var onTraceOpen: ((ChatHistory.Entry) -> Unit)? = null+/*** A suggestion bubble was tapped — one of the ready-made scenes, offered by* name, that sends its own example when taken up.@@ -535,7 +551,7 @@ class HistoryListView(private val context: Context) : ScrollView(context) {)bubble.setOnClickListener { onPageClick?.invoke(e) }} else {- attachDoubleTap(bubble, e)+ attachRowGestures(bubble, e)}// The bubble is the row's whole width minus a shoulder on the side it@@ -558,14 +574,21 @@ class HistoryListView(private val context: Context) : ScrollView(context) {}/**- * Open a message fullscreen on a double tap.+ * The gestures a message row answers to: double tap reads it, long press+ * shows what it took to write it.*- * **Double, not single.** A single tap inside a scrollable list is how you- * stop a fling and how you start a drag, and a chat where one stray tap+ * **Neither is a single tap.** A single tap inside a scrollable list is how+ * you stop a fling and how you start a drag, and a chat where one stray tap* replaces the whole screen with a reader is a chat you learn to tap- * carefully. Nothing else on a text row wants a tap, so the gesture is free- * — and it is the same one the ball uses for "the other thing", which is one- * less thing to learn.+ * carefully. Long press is free — nothing else on a row wanted it, and it is+ * the gesture that already reads as "there is more here", which is exactly+ * what it opens ([TracePage]).+ *+ * **One detector for both.** `setOnTouchListener` replaces rather than+ * chains, so installing a second one for the long press would silently+ * retire the first — leaving a row that reads fullscreen but never shows its+ * log, or the reverse, with no error anywhere. They share a listener because+ * they have to.** Page rows are excluded at the call site, not here: their single tap* already means "open the page again", and a page is not text to be read out@@ -580,7 +603,7 @@ class HistoryListView(private val context: Context) : ScrollView(context) {* Main thread only.*/@SuppressLint("ClickableViewAccessibility")- private fun attachDoubleTap(v: View, e: ChatHistory.Entry) {+ private fun attachRowGestures(v: View, e: ChatHistory.Entry) {val detector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {/*** **Must return true, and the default is false.**@@ -598,6 +621,16 @@ class HistoryListView(private val context: Context) : ScrollView(context) {onTextOpen?.invoke(e)return true}++ /**+ * Declined rather than fired-and-ignored for a row with no log: see+ * [onTraceOpen]. Keeping the test here rather than at the call site+ * leaves the question next to the record that answers it.+ */+ override fun onLongPress(ev: MotionEvent) {+ if (e.turn == null) return+ onTraceOpen?.invoke(e)+ }})v.setOnTouchListener { _, ev -> detector.onTouchEvent(ev) }}diff --git a/app/src/main/java/net/kuafuai/andee/ui/TracePage.kt b/app/src/main/java/net/kuafuai/andee/ui/TracePage.ktnew file mode 100644index 0000000..3393964--- /dev/null+++ b/app/src/main/java/net/kuafuai/andee/ui/TracePage.kt@@ -0,0 +1,287 @@+package net.kuafuai.andee.ui++import android.content.Context+import android.util.Log+import net.kuafuai.andee.R+import net.kuafuai.andee.i18n.AppLocale+import org.json.JSONObject+import java.io.File+import java.text.SimpleDateFormat+import java.util.Date++/**+ * One turn's log, as a full-screen page.+ *+ * The scrollback shows what was *said*; this shows what was *done*. A row is a+ * sentence the user heard, and everything the device did to earn the right to+ * say it — which tools it called, with what arguments, what came back, what it+ * was thinking, and what every request cost in prompt tokens — is in+ * `files/brain_trace.jsonl` and nowhere the user can reach. This is the page+ * that reaches it, opened by long-pressing the row.+ *+ * **Long-press, because the two other taps on a row are taken.** A single tap+ * already means "open that page again" on a page row and nothing at all on a+ * message row (a single tap in a scrollable list is how you stop a fling, see+ * [HistoryListView.attachRowGestures]); a double tap already reads the message+ * fullscreen ([TextPage]). Long-press is the one gesture on a row that was+ * still free, and it is the one that reads as "there is more here".+ *+ * It goes through [HtmlActivity] for the same reason [TextPage] does, and that+ * is mechanics rather than markup: folding the card, hanging the ball off the+ * ledge, floating the 完成 pill and reporting itself closed are all already+ * solved on that path, and none of them is worth solving twice.+ *+ * **Not everything has a log.** A row written by the hub brain, by a scene+ * change, or by a notification being read out has no local turn behind it, and+ * those rows are given `turn = null` and offer no gesture at all — see+ * [ChatHistory.Entry.turn]. A turn that *is* named but has no records left+ * (rotated out of the log by [net.kuafuai.andee.brain.BrainTrace]) gets a page+ * that says so rather than a blank one: the gesture happened, so something has+ * to explain why nothing came of it.+ *+ * Everything read out of the file is escaped. It is data twice over — the+ * model's output, and before that whatever the user or a notification said.+ */+object TracePage {++ private const val TAG = "Body"+ private const val FILE = "brain_trace.jsonl"++ /** Where built pages are staged: the same directory the model's pages use. */+ private fun dir(context: Context) = File(context.filesDir, "pages").apply { mkdirs() }++ /**+ * Write [turn]'s log out as a page and return the file, or null if the disk+ * said no — in which case the caller shows nothing rather than an empty+ * screen.+ *+ * **Blocks: call it off the main thread.** It parses however much of the log+ * belongs to this turn, which is a few kilobytes, but it does so by reading+ * a file that can be a megabyte per generation.+ *+ * One file per turn, named after it, so opening the same row twice+ * overwrites rather than accumulating. The name is safe as a filename+ * because a turn id is `"<processStart>-<n>"` — see+ * [net.kuafuai.andee.brain.BrainTrace] — and so contains no separator.+ * `ChatHistory.wipe` already deletes this whole directory on a factory+ * reset.+ */+ fun write(context: Context, turn: String): File? = runCatching {+ File(dir(context), "trace_$turn.html").also {+ it.writeText(html(AppLocale.wrap(context), read(context, turn)))+ }+ }.getOrElse {+ Log.w(TAG, "trace page: could not write: ${it.message}")+ null+ }++ /**+ * The records belonging to [turn], oldest first.+ *+ * **Both generations of the log are read.** [net.kuafuai.andee.brain.BrainTrace]+ * bounds itself by renaming the live file to `.1` and starting a fresh one,+ * so a turn whose records straddle that moment — or one old enough to have+ * been rotated since — is split across two files, and reading only the live+ * one would show half a turn with nothing to say it was half.+ *+ * Streamed line by line rather than read whole. The whole point of opening+ * one row's log is that it is one turn's worth; nothing here should hold two+ * megabytes of JSON in memory to find eight lines.+ */+ private fun read(context: Context, turn: String): List<JSONObject> {+ val out = ArrayList<JSONObject>()+ // `.1` first: it holds the older records, so appending in this order+ // gives one chronological list across the rotation boundary.+ for (name in listOf("$FILE.1", FILE)) {+ val f = File(context.filesDir, name)+ if (!f.exists()) continue+ runCatching {+ f.forEachLine { line ->+ if (line.isBlank()) return@forEachLine+ val o = runCatching { JSONObject(line) }.getOrNull() ?: return@forEachLine+ if (o.optString("turn") == turn) out.add(o)+ }+ }.onFailure { Log.w(TAG, "trace page: read $name: ${it.message}") }+ }+ return out+ }++ /** The whole document. */+ private fun html(lctx: Context, rows: List<JSONObject>): String {+ val head = if (rows.isEmpty()) lctx.getString(R.string.tracepage_gone)+ else SimpleDateFormat("MM-dd HH:mm:ss", AppLocale.localeOf(lctx))+ .format(Date(rows.minOf { it.optLong("ts") }))++ val body = if (rows.isEmpty()) """+ <div class="card">+ <p>${esc(lctx.getString(R.string.tracepage_gone_hint))}</p>+ </div>"""+ else rows.joinToString("\n") { block(lctx, it) }++ return """+<!doctype html>+<html><head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">+<style>+ html,body { margin:0; padding:0; background:#0F172A; color:#F8FAFC;+ font-family:-apple-system,"PingFang SC","Noto Sans CJK SC",system-ui,sans-serif;+ font-size:16px; line-height:1.6; -webkit-text-size-adjust:100%; }+ /* 88px of top padding clears the ✕完成 pill the page floats there. */+ .wrap { padding:88px 20px 40px; }+ .who { margin:0 0 16px; font-size:13px; color:#94A3B8; }+ .card { background:#1E293B; border:1px solid rgba(148,163,184,.18);+ border-radius:14px; padding:16px 18px; margin:0 0 14px; }+ .kind { margin:0 0 10px; font-size:12px; color:#94A3B8; }+ .kind b { color:#CBD5E1; font-weight:500; }+ /* The rail is what ties a tool to the step that asked for it: indented, and+ coloured, so a turn reads as blocks rather than one grey column. */+ .card.tool { margin-left:16px; border-left:3px solid #378ADD; }+ .card.turn { border-left:3px solid #4ADE80; }+ .card.end { border-left:3px solid #E24B4A; }+ p { margin:0 0 10px; word-break:break-word; }+ p:last-child { margin-bottom:0; }+ .said { font-size:15px; }+ .thought { color:#94A3B8; font-size:14px; }+ .name { font-family:ui-monospace,Menlo,Consolas,monospace; font-size:14px;+ color:#85B7EB; margin:0 0 8px; word-break:break-all; }+ .why { color:#F09595; }+ pre { margin:0 0 10px; padding:10px 12px; background:#0B1220; border-radius:10px;+ font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px;+ line-height:1.5; white-space:pre-wrap; word-break:break-word; color:#CBD5E1; }+ pre:last-child { margin-bottom:0; }+</style>+</head><body>+ <div class="wrap">+ <p class="who">${esc(head)}</p>+$body+ </div>+</body></html>+""".trimIndent()+ }++ /**+ * One record, as its own card. Unknown event kinds are skipped, not guessed at.+ *+ * The `turn` card's heading is the **reason** the turn happened, not the word+ * "started", and its body carries **no** label. Both come from the same+ * measurement: a `turn` record's `text` is the *prompt*, which for a user turn+ * is the user's own sentence and for the other four is a note the device+ * wrote to itself. Labelling that "Said" — as this page first did, because+ * `step` and `turn` both keep their prose in `text` — puts the user's words+ * in the assistant's mouth on the very first card. The heading is where the+ * origin belongs, and `kind` is the field that knows it.+ */+ private fun block(lctx: Context, r: JSONObject): String {+ val ev = r.optString("ev")+ return when (ev) {+ "turn" -> card(+ "turn",+ kind(kindOf(lctx, r.optString("kind"))),+ para(null, "said", r.optString("text")),+ )++ "step" -> card(+ "step",+ kind(stepHead(lctx, r)),+ para(lctx.getString(R.string.tracepage_said), "said", r.optString("content")) ++ para(lctx.getString(R.string.tracepage_thought), "thought", r.optString("reasoning")),+ )++ "tool" -> card(+ "tool",+ "<p class=\"name\">${esc(r.optString("name"))}" ++ " <span class=\"why\">${r.optLong("ms")} ms</span></p>",+ pre(r.optString("args")) + pre(r.optString("result")),+ )++ "end" -> card(+ "end",+ kind(lctx.getString(R.string.tracepage_end)),+ "<p class=\"why\">${esc(r.optString("why"))}</p>",+ )++ else -> ""+ }+ }++ /**+ * [net.kuafuai.andee.brain.LocalBrain.TurnKind] as a sentence.+ *+ * A `when` over the raw name rather than an enum: this reads a file, and a+ * record written by a build that knew a kind this one does not must render as+ * the neutral heading rather than crash the page. New kinds are not+ * hypothetical — `NOTIFY` and `HARVEST` were both added after the first+ * version of this file.+ */+ private fun kindOf(lctx: Context, kind: String): String = lctx.getString(+ when (kind) {+ "USER" -> R.string.tracepage_kind_user+ "WAKE" -> R.string.tracepage_kind_wake+ "NOTIFY" -> R.string.tracepage_kind_notify+ "SWEEP" -> R.string.tracepage_kind_sweep+ "HARVEST" -> R.string.tracepage_kind_harvest+ else -> R.string.tracepage_kind_other+ }+ )++ /**+ * `Step 2 · 44,005 tokens · 1 tool call`.+ *+ * The token count is the point of showing a step at all: it is what every+ * request carries as context, and it is the number that explains why this+ * device triages notifications without one (see+ * [net.kuafuai.andee.brain.NotificationTriage]).+ */+ private fun stepHead(lctx: Context, r: JSONObject): String {+ val parts = ArrayList<String>()+ parts.add(lctx.getString(R.string.tracepage_step, r.optInt("step", 0)))+ val tokens = r.optInt("prompt_tokens", 0)+ if (tokens > 0) {+ parts.add(lctx.getString(R.string.tracepage_tokens, "%,d".format(tokens)))+ }+ parts.add(+ if (r.optInt("calls", 0) > 0) lctx.getString(R.string.tracepage_calls, r.optInt("calls"))+ else lctx.getString(R.string.tracepage_no_calls)+ )+ return parts.joinToString(" · ")+ }++ private fun card(cls: String, head: String, inner: String) = """+ <div class="card $cls">+ $head+$inner+ </div>"""++ private fun kind(text: String) = "<p class=\"kind\"><b>${esc(text)}</b></p>"++ /**+ * A labelled paragraph, skipped entirely when there is nothing to show.+ *+ * A null [label] means the text stands on its own under the card's heading.+ * Used once, on the `turn` card, where a label would have to name whoever+ * spoke — and the heading already does. See [block].+ */+ private fun para(label: String?, cls: String, text: String): String {+ val t = text.trim()+ if (t.isEmpty()) return ""+ val head = if (label == null) "" else "<p class=\"kind\">${esc(label)}</p>\n "+ return "${head}<p class=\"$cls\">${esc(t)}</p>"+ }++ /** Monospaced and pre-wrapped — arguments and results are JSON, not prose. */+ private fun pre(text: String): String {+ val t = text.trim()+ if (t.isEmpty()) return ""+ return "<pre>${esc(t)}</pre>"+ }++ /**+ * The three characters that would otherwise turn text into markup. Quotes+ * are left alone: nothing here is interpolated into an attribute.+ */+ private fun esc(s: String): String = s+ .replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+}diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xmlindex 52a247f..deb5a98 100644--- a/app/src/main/res/values-en/strings.xml+++ b/app/src/main/res/values-en/strings.xml@@ -276,6 +276,27 @@<string name="textpage_role_assistant">Andee</string><string name="textpage_role_error">Error</string><string name="textpage_role_page">Page</string>+ <!-- What called this turn into being. The old wording was just "Started",+ which answers nothing: the first thing a log page owes a reader is+ "why did he suddenly do something", and these five are five stories. -->+ <string name="tracepage_kind_user">You spoke</string>+ <string name="tracepage_kind_wake">A reminder came due</string>+ <string name="tracepage_kind_notify">A notification arrived</string>+ <string name="tracepage_kind_sweep">Quiet-hour review</string>+ <string name="tracepage_kind_harvest">Reviewing before tidying up</string>+ <string name="tracepage_kind_other">Started</string>+ <string name="tracepage_step">Step %1$d</string>+ <string name="tracepage_tokens">%1$s tokens in</string>+ <string name="tracepage_calls">%1$d tool calls</string>+ <string name="tracepage_no_calls">no tools</string>+ <string name="tracepage_said">Said</string>+ <string name="tracepage_thought">Thought</string>+ <!-- The end event is only written on an ABNORMAL finish: a throw, the+ repeat guard, or running out of steps. So this card never means "and+ then it finished nicely", and its heading must not read that way. -->+ <string name="tracepage_end">This turn did not finish on its own</string>+ <string name="tracepage_gone">The log for this turn is gone</string>+ <string name="tracepage_gone_hint">It may have been rotated out by newer entries, or this turn was not run by the local brain — only turns the local brain ran leave a log.</string><string name="card_ack">Got it</string><string name="bubble_tap_to_talk">Tap to talk</string><string name="input_hint">Type to talk to it…</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 3f15eb1..52f7778 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -258,6 +258,25 @@<string name="textpage_role_assistant">Andee</string><string name="textpage_role_error">出错</string><string name="textpage_role_page">界面</string>+ <!-- 是什么把这一轮叫起来的。原来的「起因」太笼统:一条日志页的第一句+ 话要回答的就是「他为什么忽然动了」,而这五种起因讲的是五个不同的故事。 -->+ <string name="tracepage_kind_user">你开口了</string>+ <string name="tracepage_kind_wake">一件待办到点了</string>+ <string name="tracepage_kind_notify">来了一条通知</string>+ <string name="tracepage_kind_sweep">安静时段的回顾</string>+ <string name="tracepage_kind_harvest">整理对话前的回顾</string>+ <string name="tracepage_kind_other">起因</string>+ <string name="tracepage_step">步骤 %1$d</string>+ <string name="tracepage_tokens">上下文 %1$s token</string>+ <string name="tracepage_calls">%1$d 个工具调用</string>+ <string name="tracepage_no_calls">没有调用工具</string>+ <string name="tracepage_said">说</string>+ <string name="tracepage_thought">想</string>+ <!-- end 事件只在**非正常收尾**时才写:抛异常、复读保护、超步数。+ 所以这张卡永远不是在报「顺利结束」,标题不能那么平淡。 -->+ <string name="tracepage_end">这一轮没能自己跑完</string>+ <string name="tracepage_gone">这一轮的日志已经不在了</string>+ <string name="tracepage_gone_hint">它可能已经被更新的日志挤掉了,或者这一轮不是本地大脑跑的 —— 只有本地大脑跑过的轮次才留日志。</string><string name="card_ack">知道了</string><string name="bubble_tap_to_talk">点击说话</string><string name="input_hint">打字跟它说…</string>diff --git a/app/src/test/java/net/kuafuai/andee/brain/BrainTraceTest.kt b/app/src/test/java/net/kuafuai/andee/brain/BrainTraceTest.ktnew file mode 100644index 0000000..dc780d6--- /dev/null+++ b/app/src/test/java/net/kuafuai/andee/brain/BrainTraceTest.kt@@ -0,0 +1,60 @@+package net.kuafuai.andee.brain++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * The turn id is the only thing tying a scrollback row to its log, and it is+ * the half of that pair the file cannot check for itself. A wrong id does not+ * fail — it opens the wrong turn, or nothing, and looks like "the log is gone".+ */+class BrainTraceTest {++ @Test+ fun `the turn id is stable to read and distinct across a restart`() {+ // Same turn, read twice, same answer: the id is copied onto the row when+ // the answer lands and matched back when the row is long-pressed, and+ // those are two different moments.+ assertEquals(BrainTrace.turnId(1_000L, 7), BrainTrace.turnId(1_000L, 7))++ // The trap, measured on the device rather than feared: `gen` is+ // LocalBrain's in-memory counter, so it restarts at 1 with every process+ // while the trace file is persistent and append-only. On the test device+ // "gen":1 covered 176 of 278 records. Same gen in two runs must not be+ // the same turn.+ assertNotEquals(BrainTrace.turnId(1_000L, 1), BrainTrace.turnId(2_000L, 1))++ // The dash is load-bearing, not formatting: run 12 / gen 3 and+ // run 1 / gen 23 would concatenate to the same string without it.+ assertNotEquals(BrainTrace.turnId(12L, 3), BrainTrace.turnId(1L, 23))+ }++ @Test+ fun `the turn in flight is announced, survives being read, and ends when told`() {+ // `init` is never called here, so every append in this test is a no-op.+ // That is deliberate: the bookkeeping the scrollback reads must not+ // depend on the trace file being writable.+ BrainTrace.clearTurn()+ assertNull(BrainTrace.currentTurn())++ BrainTrace.turn(gen = 7, kind = "user", text = "hi")+ val announced = BrainTrace.currentTurn()+ assertNotNull("turn() did not announce itself", announced)+ assertTrue("$announced does not end in its own gen", announced!!.endsWith("-7"))++ // Reading must not consume it. The last step overwrites nothing, and the+ // row is only written once the answer is final.+ assertEquals(announced, BrainTrace.currentTurn())++ // Ending is explicit rather than done on read, for one path: `submit`+ // returns early when the API key is missing and writes a device+ // complaint with no log behind it. That row must not inherit whatever+ // the previous turn recorded.+ BrainTrace.clearTurn()+ assertNull(BrainTrace.currentTurn())+ }+}