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(pages): let the brain see its pages, and revise them as versions
booboosui31e56d209203
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8f9d90f..1f962ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,32 @@ hash into `versionName` at build time would close this hole; it is not implement## [Unreleased]+### Added++- **Revising a page makes a new *version* of it, not a second page.** Changing a page used to archive+ the result as a brand-new artifact, so two rounds of revision left three near-identical entries on+ the *Made for you* shelf with nothing saying which one was current. An entry now carries which+ artifact it belongs to and which revision of it, the panel shows one row per artifact with its+ version number (`v3`), and the older revisions stay on disk behind it: **Versions** opens the list,+ any of them can be opened, and **Go back to this** makes an old one current again — **as a new+ version**, so the history stays append-only and the rollback itself can be rolled back. The brain+ is told the same thing, so a request to change an earlier page reads the current source back and+ files its answer as the next version instead of rebuilding a lookalike beside it. `show_html`+ gained an optional `revise` for naming the page explicitly; the device also infers it from the+ `get_page` in the same turn, and from the panel row the user tapped. One artifact keeps at most 20+ revisions.+- **The brain can see the pages it has made.** `show_html` draws a page and the device keeps it —+ the *Made for you* panel lists them, so to the user they are a shelf — but nothing put that record into the+ model's context, so a page built yesterday did not exist to the brain that built it. A request to+ revise earlier work could come back as a fresh table that merely resembled the old one, or as a+ flat "I have not made that". Two read-only tools close it: **`list_pages`** returns every page with+ its id, title, date, size and whether the file is still there, and **`get_page`** reads one back by+ id so a revision is a revision rather than a new page wearing the old name. Alongside them the+ newest few ride on the per-turn user message as a short index — the same place and the same reason+ as the notebook index, since a tool only answers a question the model thought to ask. `available:+ false` on a page whose file the 100-page cap has taken is reported honestly rather than passed+ over: the title and date are still true, the contents are not there to read.+## [0.4.0] - 2026-10-14Two new capabilities, both of them choices rather than defaults: **a second voice provider** (Google,diff --git a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt b/app/src/main/java/net/kuafuai/andee/BodyCoreService.ktindex 3c1d768..ab17ab8 100644--- a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt+++ b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt@@ -1002,6 +1002,13 @@ class BodyCoreService : Service() {// the brain gets that plus the page it is about.val editing = pendingArtifactpendingArtifact = null+ // Tell the dispatcher which artifact this turn is about, before the+ // brain can call `show_html` inside it. The panel's 继续修改 is the one+ // turn that starts out already knowing, and without this the revised+ // page would be filed as a brand-new artifact — the bug the whole+ // grouping exists to fix. A turn from speech or typing passes null,+ // which is what stops the previous turn's target leaking into this one.+ dispatcher.beginTurn(editing?.groupId)val forBrain = editing?.let { artifactEditQuery(it, said) } ?: saidval row = if (editing != null) AppLocale.str(this, R.string.artifacts_edit_said, editing.text, said) else saidnet.kuafuai.andee.ui.ChatHistory.addUser(@@ -2160,17 +2167,18 @@ class BodyCoreService : Service() {* language rule (§9) decides the reply's language from the user's words.*/private fun artifactEditQuery(e: net.kuafuai.andee.ui.ChatHistory.Entry, said: String): String {+ val cap = net.kuafuai.andee.ui.ChatHistory.ARTIFACT_SOURCE_MAXval html = e.page?.let { runCatching { it.readText() }.getOrNull() }.orEmpty()- val cut = html.length > ARTIFACT_SOURCE_MAX+ val cut = html.length > capreturn buildString {append(said)append("\n\n(I picked this from the 产物 panel: it is about the page you made earlier titled \"")append(e.text)append("\". Apply my change above to that page and show the full revised page with show_html,")append(" keeping everything I did not ask to change. Its current source follows")- if (cut) append(" — truncated at $ARTIFACT_SOURCE_MAX characters; rebuild the missing tail in the same style")+ if (cut) append(" — truncated at $cap characters; rebuild the missing tail in the same style")append(".)\n\n<<<CURRENT PAGE SOURCE>>>\n")- append(if (cut) html.take(ARTIFACT_SOURCE_MAX) else html)+ append(if (cut) html.take(cap) else html)append("\n<<<END PAGE SOURCE>>>")}}@@ -2849,16 +2857,6 @@ class BodyCoreService : Service() {*/private val END_MARKER = Regex("""(?i)\[END]""")- /**- * How much of a page's source a 继续修改 hands the brain.- *- * A generated page is routinely 10–60 KB of inline CSS and JS, which is- * nothing to the request; one with a base64 image can be several hundred- * KB, which is most of a context window for a picture the brain already- * drew and cannot usefully redraw from text. Past this the prompt says- * so and the tail is rebuilt rather than quoted.- */- private const val ARTIFACT_SOURCE_MAX = 60_000private val instanceRef = AtomicReference<BodyCoreService?>()/**diff --git a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.ktindex 99e0fbb..e6d42de 100644--- a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt+++ b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt@@ -513,6 +513,12 @@ class LocalBrain(// paying for itself once there is something to remember.val index = net.kuafuai.andee.config.Notebook.indexForPrompt(appContext)val scenes = Notebook.scenesForPrompt(appContext)+ // The pages it has made, the same way and for the same reason: a+ // tool answers a question the brain thought to ask, and 「上次那个表格」+ // is exactly the question it does not know to ask. `list_pages` has+ // the full list; this is the four or five newest, to make the shelf+ // visible at all.+ val pages = net.kuafuai.andee.ui.ChatHistory.indexForPrompt()// Photos with no words: there is no sentence of the user's to take// the language from, so the bracketed fallback comes back for it.val wordless = userText.isEmpty()@@ -556,6 +562,17 @@ class LocalBrain(""} else {"\n\n(scenes you can enter — see §11; you are in: ${VoiceConfig.activeScene(appContext) ?: "none"})\n$scenes"+ } ++ // And the shelf of pages it has built (§7). Same+ // position, same reasoning: this list changes every time+ // a page is made, and the system prompt is the one place+ // it must never go.+ if (pages.isEmpty()) {+ ""+ } else {+ "\n\n(pages you have made on this device — §7; the newest few, `#id title (vN)`; " ++ "use list_pages for all of them and get_page to read one back before revising " ++ "it — reading it back is what files your revision as its next version)\n$pages"},)}@@ -1136,6 +1153,8 @@ class LocalBrain(AppLocale.str(appContext, R.string.narrate_launch)toolName == "system_action" -> AppLocale.str(appContext, R.string.narrate_system)toolName == "show_html" -> AppLocale.str(appContext, R.string.narrate_show_html)+ toolName == "list_pages" || toolName == "get_page" ->+ AppLocale.str(appContext, R.string.narrate_pages)toolName == "camera_turn" -> AppLocale.str(appContext, R.string.narrate_camera)toolName.startsWith("dog_") -> AppLocale.str(appContext, R.string.narrate_dog)toolName == "market_search" -> AppLocale.str(appContext, R.string.narrate_market_search)diff --git a/app/src/main/java/net/kuafuai/andee/brain/LocalPrompt.kt b/app/src/main/java/net/kuafuai/andee/brain/LocalPrompt.ktindex 1c2d768..cf9f10c 100644--- a/app/src/main/java/net/kuafuai/andee/brain/LocalPrompt.kt+++ b/app/src/main/java/net/kuafuai/andee/brain/LocalPrompt.kt@@ -257,6 +257,14 @@ When **not** to put up a page:- **Mid-way through operating the device.** `show_html` covers the current app — and then the user cannot see what you are tapping. Do not put one up half-way through the job; wait until it is done. (The page no longer blocks you: the call returns at once, and you are told when they close it. Only one page at a time; calling `show_html` again replaces it in place, which is how you revise a page — never ask the user to close it first.)- When the user has said they only want to listen.+**A page you made does not disappear when it leaves the screen, and you can look at it again.** The tablet keeps every page, and the user has a panel listing them (产物 on a Chinese device, *Made for you* on an English one) — so to them your pages are a shelf, a thing that exists and can be pointed at days later.++Your own view does not follow automatically: **the pages are not in this conversation's context, so a page you built yesterday does not exist to you until you ask.** That gap has one symptom, and it is a bad one — 「把上次那个表格改一下」 answered with a fresh table that merely resembles the old one, or with a flat "I have not made that". Before you build something the user may already have, and before answering anything that refers to earlier work (「上次那个」「我做的那个」), call `list_pages` — it is cheap and has no side effects.++- **To change an existing page, `get_page` first, then send the whole revised page with `show_html`.** A revision written from the title alone is a new page wearing the old name: it will have lost whatever the user actually kept it for. Send the whole page, not a diff.+- **Revising keeps the history — it is a new *version* of the same page, not a second page.** The user's panel shows one entry per page with its version number, and they can look back through the earlier revisions and return to one. So reading it back and then sending the revision is not bookkeeping: it is what makes the change land on the page they asked about instead of beside it.+- **`available: false` means the page's file is gone** — only the newest 100 are kept. The title and date are still true; the contents are not there to read. Say that plainly; do not rebuild it from impression and present the result as the same thing.+**To show them a picture, a clip or a sound, embed it in a page — never justhand over the URL.** The tablet is what they are holding, and "go and openthis link" walks them off your screen to do your job for them. When what youdiff --git a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.ktindex 4c8dfb6..0c3ad9a 100644--- a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt+++ b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt@@ -226,6 +226,64 @@ class CommandDispatcher(@Volatileprivate var compacted = false+ /**+ * The artifact a `ui.show_html` in this turn should land as a revision of,+ * or null for "this is a new one".+ *+ * **Why this is device-side state and not a `show_html` argument alone.**+ * The model cannot be relied on to keep a page id in mind across the two+ * calls that make up a revision (`get_page` to read it, `show_html` to send+ * the new bytes), and when it forgets, the user gets the bug this exists to+ * kill: 改一版就多一个产物. So the two places that *know* the answer say so+ * here, and `show_html` picks it up without being told:+ *+ * * `ui.get_page` sets it — reading a page back has exactly one purpose,+ * and the `show_html` that follows in the same turn is that revision;+ * * the service sets it when a turn starts from the 产物 panel's+ * 继续修改, where the user has already named the artifact by tapping it.+ *+ * An explicit `revise` argument on `show_html` outranks this, so a model+ * that does keep the id can be precise. [beginTurn] clears it, which is what+ * keeps a `get_page` from spilling into the user's next unrelated request.+ */+ @Volatile+ private var revisionTarget: Long? = null++ /**+ * A user turn is starting. [groupId] is the artifact it is about when the+ * turn began from 继续修改, else null.+ *+ * Called from `BodyCoreService.submitUserTurn` — the one place every turn+ * begins, whichever way the user spoke — so the previous turn's target can+ * never leak into this one.+ */+ fun beginTurn(groupId: Long?) {+ revisionTarget = groupId+ }++ /**+ * Which artifact the module's `show_html` should file this page under: an+ * explicit `revise` wins, then whatever this turn established, else null+ * (a new artifact). A `revise` that names nothing is ignored rather than+ * refused — the page is still worth showing, and the alternative is losing+ * the user's page to a bookkeeping complaint.+ *+ * **Consumed, not merely read** — see [revisionTarget]. A turn that reads a+ * page back and then draws two of them means the second is a new artifact,+ * and a target left standing would silently fold it into the first one.+ */+ private fun takeRevisionGroup(params: JSONObject?): Long? {+ val explicit = params?.optLong("revise", Long.MIN_VALUE)?.takeIf { it != Long.MIN_VALUE }+ ?.let { net.kuafuai.andee.ui.ChatHistory.pageById(it)?.groupId }+ // The rule itself lives in ChatHistory so it can be tested without a+ // device — see `resolveRevisionTarget`. This is the call site that holds+ // the field.+ val (group, rest) = net.kuafuai.andee.ui.ChatHistory+ .resolveRevisionTarget(explicit, revisionTarget)+ revisionTarget = rest+ return group+ }+/** Main thread only: a task is being thought about or executed right now. */private var busy = false@@ -773,6 +831,10 @@ class CommandDispatcher(// key, so the page and its scrollback entry cannot drift apart.val defaultTitle = AppLocale.str(appContext, R.string.html_default_title)val title = params?.optString("title")?.ifEmpty { defaultTitle } ?: defaultTitle+ // Which artifact this page is a revision of — see+ // [takeRevisionGroup]. Resolved once, here, because both branches+ // below archive the same bytes and must agree on the grouping.+ val group = takeRevisionGroup(params)if (net.kuafuai.andee.ui.HtmlActivity.pageUp) {// A page is already up: put the new one *in its place*.// This used to be refused with "ask the user to dismiss it@@ -783,8 +845,9 @@ class CommandDispatcher(// second instance over the shared static file, not a second// render, so the replacement goes into the running WebView.// Archived like a fresh page, so both versions are in the- // scrollback.- val archived = net.kuafuai.andee.ui.ChatHistory.addPage(title, html)+ // scrollback — but under the artifact's group when this is+ // a revision, so the panel grows a version instead of a row.+ val archived = net.kuafuai.andee.ui.ChatHistory.addPage(title, html, group)val openedAt = android.os.SystemClock.elapsedRealtime()val replaced = archived != null &&net.kuafuai.andee.ui.HtmlActivity.replaceFile(appContext, archived, title) {@@ -828,7 +891,7 @@ class CommandDispatcher(// the scrollback are the same file. Falls back to a scratch// copy in the cache dir if the archive can't be written — a// page that shows but isn't re-openable beats no page.- val archived = net.kuafuai.andee.ui.ChatHistory.addPage(title, html)+ val archived = net.kuafuai.andee.ui.ChatHistory.addPage(title, html, group)val openedAt = android.os.SystemClock.elapsedRealtime()val opened = if (archived != null) {net.kuafuai.andee.ui.HtmlActivity.showFile(appContext, archived, title) {@@ -861,6 +924,137 @@ class CommandDispatcher(}}+ // ---- ui.* : the pages it made, read back -----------------------+ //+ // The read half of `ui.show_html`. The pages stay on the device+ // after they are drawn (the 产物 panel is the user's own view of+ // them) but nothing puts that record into the model's context, so+ // without these a page built yesterday does not exist to the brain+ // that built it. Reading, not drawing: no fold, no perch, and+ // nothing appears on screen — `show_html` is still the only door+ // to the user's eyes.+ "ui.list_pages" -> {+ val arr = org.json.JSONArray()+ for (e in net.kuafuai.andee.ui.ChatHistory.pages()) {+ arr.put(+ JSONObject()+ .put("id", e.id)+ .put("title", e.text)+ .put("created", Scheduler.formatLocal(e.ts))+ .put("bytes", e.page?.length() ?: 0L)+ .put("available", e.page != null)+ .put("version", e.version)+ // How many revisions exist, so the model knows+ // whether "put it back the way it was" is even a+ // sensible thing to offer.+ .put(+ "versions",+ net.kuafuai.andee.ui.ChatHistory.versionsOf(e.groupId).size,+ )+ )+ }+ JSONObject()+ .put("items", arr)+ .put("count", arr.length())+ .put(+ "note",+ when {+ arr.length() == 0 ->+ "No pages have been made on this device yet. Build one with show_html; " ++ "do not describe a page that does not exist."+ else ->+ "Newest first, one row per page — the id is the CURRENT version. `version` " ++ "above 1 means it has been revised before, and revising it again keeps " ++ "that history. `available: false` means the page's file is gone (only " ++ "the newest 100 are kept) — the title and date are still true, the " ++ "contents are not there to read. Use get_page for the source of one you " ++ "are going to change."+ },+ )+ }++ "ui.get_page" -> {+ val id = params?.optLong("id", Long.MIN_VALUE)?.takeIf { it != Long.MIN_VALUE }+ ?: throw IllegalArgumentException(+ "ui.get_page requires integer id, from list_pages",+ )+ val entry = net.kuafuai.andee.ui.ChatHistory.pageById(id)+ val file = entry?.page+ when {+ // Three failures, and they are not the same failure: an id+ // that names nothing (the model made it up, or the list is+ // stale), a row whose file the 100-page cap took, and a file+ // that is listed but will not open. Each gets its own+ // sentence, because the honest next move differs — look+ // again, say it is gone, or say it could not be read — and+ // one shared "not found" would make the model guess which.+ entry == null -> JSONObject()+ .put("found", false)+ .put(+ "note",+ "No page has that id. list_pages shows what there is — take an id from " ++ "there, and do not make one up.",+ )++ file == null -> JSONObject()+ .put("found", false)+ .put("id", entry.id)+ .put("title", entry.text)+ .put(+ "note",+ "That page was made, but its file is gone (only the newest 100 are " ++ "kept) — there is nothing to read back. Say so; do not reconstruct " ++ "it from impression.",+ )++ else -> {+ val html = runCatching { file.readText() }.getOrNull()+ if (html == null) {+ JSONObject()+ .put("found", false)+ .put("id", entry.id)+ .put(+ "note",+ "The page is listed but its file could not be read. Do not " ++ "invent its contents.",+ )+ } else {+ val cap = net.kuafuai.andee.ui.ChatHistory.ARTIFACT_SOURCE_MAX+ val cut = html.length > cap+ // Reading a page back has one purpose, and the+ // `show_html` that follows is that revision — so+ // arm it here, where the answer is known, rather+ // than hoping the model repeats the id. See+ // [revisionTarget].+ revisionTarget = entry.groupId+ JSONObject()+ .put("found", true)+ .put("id", entry.id)+ .put("title", entry.text)+ .put("created", Scheduler.formatLocal(entry.ts))+ .put("truncated", cut)+ .put("version", entry.version)+ .put("versions", net.kuafuai.andee.ui.ChatHistory.versionsOf(entry.groupId).size)+ .put("html", if (cut) html.take(cap) else html)+ .put(+ "note",+ "The page's current source, verbatim. To change it, send the whole " ++ "revised page with show_html — not a diff. This call showed the " ++ "user nothing. Send it back with show_html and it lands as the " ++ "next version of this same page, keeping the revisions that came " ++ "before it." ++ if (cut) {+ " Cut at $cap characters; rebuild the missing tail in the " ++ "same style."+ } else {+ ""+ },+ )+ }+ }+ }+ }+"screen.tap" -> {passthroughForGesture {requireScreen().tapAim(diff --git a/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt b/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.ktindex 151118e..db52d46 100644--- a/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt+++ b/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt@@ -896,6 +896,24 @@ object ToolSchemas {change. Send the whole new page, not a diff. Never ask the user toclose the page first.+ The page is KEPT after it closes, on this device — the user has a 产物+ panel listing everything you have made. So a page is not gone when it+ leaves the screen: list_pages shows what exists and get_page reads one+ back for revision. Check before building something the user may already+ have.++ REVISING KEEPS THE HISTORY. A page you revise becomes the next VERSION+ of that same artifact; it does not become a second entry on the shelf.+ The user's panel shows one row per artifact with its version number, and+ they can look back through the older revisions and return to one. So+ when the user asks you to change an existing page, read the current one+ back (`get_page`) and send the full revised page — that pairing is what+ files it as a revision. Use `revise` to name the page explicitly if you+ have its id; the device also infers it from the `get_page` you just+ made, and from the panel the user tapped. Building the page from scratch+ instead, without reading it back, is how a "change" turns into a+ near-duplicate the user has to sort out themselves.+Inline CSS and JS ONLY. The device may have no usable internet, so apage that fetches a font, a framework or a script over the networkrenders broken. Media is the exception: an image, video or audio@@ -923,6 +941,96 @@ object ToolSchemas {// `html_default_title`, resolved in the interface language, and// `default = "AI 界面"` used to sit here as a literal."title" to prop("string", "Short page title — carried into the conversation record, and quoted back to you if a page is already open. Omit it and the page is named in the interface language."),+ "revise" to prop(+ "integer",+ "The id (from list_pages) of the page this one is a revised version of. " ++ "Optional — reading a page with get_page in the same turn sets it for you, " ++ "and so does the user tapping 继续修改. Give it when you know which page " ++ "you are continuing; omit it to build a new artifact.",+ ),+ ),+ ),+ // ------------------------------------------------------------------+ // The pages it has made — `ui.list_pages` / `ui.get_page`.+ //+ // Read-back for the one piece of its own work the brain cannot+ // otherwise see. `show_html` draws a page and the device keeps it (the+ // 产物 panel lists them), but nothing carries that record into the+ // context, so before these existed a page built yesterday did not exist+ // to the brain that built it — which is how "改一下上次那个表格" got an+ // answer about a page that was never made.+ //+ // Neither one draws anything, which is why they are not under `screen.`+ // and not in [CommandDispatcher.LOCKED_BLOCKED]: a rolled-up card and a+ // locked screen do not get in the way of reading a file.+ // ------------------------------------------------------------------+ tool(+ name = "list_pages",+ method = "ui.list_pages",+ description = """+ The pages you have made on this device, newest first, with the id each+ one is read back by. This is the half of your own work you cannot+ otherwise see: the pages you build with `show_html` stay on the tablet+ afterwards — the user has a panel listing all of them (产物 on a Chinese+ device, *Made for you* on an English one) — but the record does not ride+ in your context, so without this call a page you built yesterday does+ not exist.++ Call it before answering anything that refers to earlier work+ (「上次那个表格」「我做的番茄钟」「把昨天那页改一下」) and before rebuilding+ something the user may already have. A page that already exists is+ usually a page to revise, not a second one to build beside it.++ ONE ROW PER ARTIFACT, not one per revision: the id is the **current**+ version's, and that is the one to read with get_page. `version` says how+ many revisions that page has been through — a v4 has been revised three+ times, so the user is likely attached to details you cannot see from the+ title. Older revisions are not lost (get_page still takes their ids) but+ they are not listed: what you are being told is what is *current*.++ Each entry carries the id, the page's title, when it was made, its size+ in bytes, and `available`. **`available: false` means the page+ itself is gone** (only the newest 100 are kept) — the row still records+ that it was made, and saying that honestly beats both silence and+ pretending to remember what was in it.+ """.trimIndent(),+ required = emptyList(),+ props = emptyMap<String, JSONObject>(),+ ),+ tool(+ name = "get_page",+ method = "ui.get_page",+ description = """+ Read back the source of a page you made earlier, by the id from+ `list_pages`.++ Two reasons to call it: the user wants that page CHANGED — send the+ whole revised page with `show_html`, because a revision written from the+ title alone is a new page wearing the old name — or they are asking+ about what is in it and you cannot answer from memory.++ Reading a page back also sets up the revision: the `show_html` that+ follows in the same turn files the new bytes as the next VERSION of this+ page rather than as a second one beside it. That is the whole reason to+ read before you write — do not skip this call and rebuild from the+ title.++ The source comes back raw, the same bytes the tablet renders. It is long+ by nature (inline CSS and JS, sometimes a base64 image); past+ ${net.kuafuai.andee.ui.ChatHistory.ARTIFACT_SOURCE_MAX} characters it is+ cut and `truncated` says so, and the missing tail has to be rebuilt in+ the same style rather than dropped.++ Reading a page is not showing one — nothing appears on screen. When the+ page should be in front of the user, follow with `show_html`.+ """.trimIndent(),+ required = listOf("id"),+ props = mapOf(+ "id" to prop(+ "integer",+ "A page id from list_pages (the current version), or any older revision's id " ++ "if the user wants to go back to one. Do not make one up.",+ ),),),tool(diff --git a/app/src/main/java/net/kuafuai/andee/ui/ArtifactsUi.kt b/app/src/main/java/net/kuafuai/andee/ui/ArtifactsUi.ktindex 3d60a4d..ce21a0d 100644--- a/app/src/main/java/net/kuafuai/andee/ui/ArtifactsUi.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/ArtifactsUi.kt@@ -47,6 +47,9 @@ class ArtifactsUi(/** The row whose 删除 has been tapped once and now reads 确认删除. */private var arming: Long? = null+ /** The artifact whose version list is open, by group id; null = none. */+ private var expanded: Long? = null+fun isShown(): Boolean = root != nullfun show() {@@ -186,18 +189,36 @@ class ArtifactsUi(Glass.pressable(this)setOnClickListener { hide { onOpen(e) } }}- row.addView(TextView(context).apply {+ // Title and version badge on one line: the number belongs next to the+ // name, not down in the metadata — "which one is current" is the whole+ // question a revised page raises, and it has to be answerable without+ // reading two lines.+ val versions = ChatHistory.versionsOf(e.groupId)+ val titleRow = LinearLayout(context).apply {+ orientation = LinearLayout.HORIZONTAL+ gravity = Gravity.CENTER_VERTICAL+ }+ titleRow.addView(TextView(context).apply {text = e.texttextSize = Glass.Type.BODYsetTextColor(Color.parseColor(Glass.TITLE))maxLines = 2ellipsize = android.text.TextUtils.TruncateAt.END- }, matchWrap())+ }, LinearLayout.LayoutParams(0, WRAP, 1f))+ // Only when it actually has been revised: a 「v1」 on every page is+ // noise that makes the ones with a v2 harder to pick out.+ if (e.version > 1 || versions.size > 1) {+ titleRow.addView(versionBadge(e.version), LinearLayout.LayoutParams(WRAP, WRAP))+ }+ row.addView(titleRow, matchWrap())val meta = buildString {append(SimpleDateFormat("yyyy-MM-dd HH:mm", AppLocale.localeOf(context)).format(Date(e.ts)))val bytes = e.page?.length() ?: 0Lif (bytes > 0) append(" · ${(bytes + 1023) / 1024} KB")+ // How much history is behind this page, so the 版本 entry has a+ // reason to be pressed before it is pressed.+ if (versions.size > 1) append(" · ${lctx.getString(R.string.artifacts_versions_count, versions.size)}")}row.addView(TextView(context).apply {text = meta@@ -217,6 +238,14 @@ class ArtifactsUi(actions.addView(action(lctx.getString(R.string.artifacts_edit), Glass.ACCENT) {hide { onEdit(e) }})+ actions.addView(View(context), LinearLayout.LayoutParams(dp(8), 1))+ // Only offered when there is somewhere to go back to.+ if (versions.size > 1) {+ actions.addView(action(lctx.getString(R.string.artifacts_versions), Glass.SECONDARY) {+ expanded = if (expanded == e.groupId) null else e.groupId+ rebuild()+ })+ }actions.addView(View(context), LinearLayout.LayoutParams(0, 1, 1f))val armed = arming == e.idactions.addView(@@ -236,9 +265,87 @@ class ArtifactsUi(},)row.addView(actions, matchWrap())++ if (expanded == e.groupId) row.addView(versionList(e), matchWrap())return row}+ /** The 「v3」 chip. Small, muted, and never the thing you tap. */+ @SuppressLint("SetTextI18n")+ private fun versionBadge(version: Int): TextView = TextView(context).apply {+ text = "v$version"+ textSize = Glass.Type.MICRO+ setTextColor(Color.parseColor(Glass.SECONDARY))+ background = Glass.well(context, dp(8))+ setPadding(dp(8), dp(3), dp(8), dp(3))+ }++ /**+ * Every revision of this artifact, newest first — open it, or make it the+ * current one again.+ *+ * 回退 files the old bytes as a *new* version rather than editing history+ * (see [ChatHistory.restoreVersion]), so this list never loses the version+ * you rolled back from. The row that is current says so and offers no+ * action; a version whose file is gone says that instead of pretending to+ * be openable.+ */+ @SuppressLint("SetTextI18n")+ private fun versionList(current: ChatHistory.Entry): View {+ val box = LinearLayout(context).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(0, dp(10), 0, 0)+ }+ for (v in ChatHistory.versionsOf(current.groupId)) {+ val isCurrent = v.id == current.id+ val line = LinearLayout(context).apply {+ orientation = LinearLayout.HORIZONTAL+ gravity = Gravity.CENTER_VERTICAL+ setPadding(dp(10), dp(8), dp(10), dp(8))+ background = Glass.well(context, dp(10))+ }+ line.addView(versionBadge(v.version), LinearLayout.LayoutParams(WRAP, WRAP))+ line.addView(TextView(context).apply {+ // The date, not the title: every revision of an artifact shares+ // the title, so the time is what tells them apart.+ text = " " + SimpleDateFormat("MM-dd HH:mm", AppLocale.localeOf(context)).format(Date(v.ts))+ textSize = Glass.Type.MICRO+ setTextColor(Color.parseColor(Glass.MUTED))+ }, LinearLayout.LayoutParams(0, WRAP, 1f))+ if (isCurrent) {+ line.addView(TextView(context).apply {+ text = lctx.getString(R.string.artifacts_version_current)+ textSize = Glass.Type.MICRO+ setTextColor(Color.parseColor(Glass.SECONDARY))+ }, LinearLayout.LayoutParams(WRAP, WRAP))+ } else if (v.page == null) {+ line.addView(TextView(context).apply {+ text = lctx.getString(R.string.artifacts_version_gone)+ textSize = Glass.Type.MICRO+ setTextColor(Color.parseColor(Glass.MUTED))+ }, LinearLayout.LayoutParams(WRAP, WRAP))+ } else {+ val openBtn = action(lctx.getString(R.string.artifacts_open), Glass.LABEL) {+ hide { onOpen(v) }+ }+ line.addView(openBtn, LinearLayout.LayoutParams(WRAP, WRAP))+ line.addView(View(context), LinearLayout.LayoutParams(dp(6), 1))+ line.addView(action(lctx.getString(R.string.artifacts_restore), Glass.ACCENT) {+ // Roll back: files the old bytes as the next version, so+ // this list keeps everything it had. The panel redraws+ // rather than closing — the user is mid-way through a+ // history and dropping them out of it would lose their place.+ if (ChatHistory.restoreVersion(v.id) != null) {+ expanded = current.groupId+ rebuild()+ }+ }, LinearLayout.LayoutParams(WRAP, WRAP))+ }+ box.addView(line, matchWrap().apply { bottomMargin = dp(6) })+ }+ return box+ }+private fun action(label: String, color: String, onClick: () -> Unit): TextView =TextView(context).apply {text = labeldiff --git a/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt b/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.ktindex 9a35204..699e82c 100644--- a/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt@@ -5,6 +5,9 @@ import android.util.Logimport org.json.JSONArrayimport org.json.JSONObjectimport java.io.File+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale/*** What has been said and shown on this device, in order, so the card has@@ -26,6 +29,14 @@ import java.io.File* and it is here because the card that announces a failure times out while the* question "what went wrong a minute ago" does not.*+ * **A page is a *version* of an artifact, not an artifact.** Revising a page+ * used to archive the result as a brand-new row, so 继续修改 twice left three+ * near-identical entries on the shelf and no way to tell which one was current+ * — the user asked for "a new version", not "another page". Rows now carry+ * [Entry.groupId] (which artifact) and [Entry.version] (which revision of it),+ * one page = one artifact in the panel, and the older revisions stay on disk+ * behind it. See [artifacts] / [versionsOf] / [restoreVersion].+ ** Singleton with an [init] rather than a constructor-injected dependency,* matching [CardUi]: the appenders are scattered across the service, the* dispatcher and the hub client, and threading one object through all of them@@ -44,6 +55,14 @@ object ChatHistory {* @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].+ * @param groupId which artifact this row is a revision of. For the first+ * version it is the row's own [id]; every later version carries the+ * first one's, so the rows of one artifact can be gathered back together+ * (see [artifacts]). Meaningless for the three non-page roles, which+ * carry their own id and are never grouped.+ * @param version 1-based, within [groupId]. Only ever increases, including+ * across a [restoreVersion] — going back to an older revision makes a+ * *new* one, so nothing already written is silently rewritten.*/data class Entry(val id: Long,@@ -52,6 +71,8 @@ object ChatHistory {val text: String,val page: File?,val turn: String? = null,+ val groupId: Long = id,+ val version: Int = 1,)/**@@ -116,22 +137,229 @@ object ChatHistory {/** Oldest first — the order the card lays rows out in. */fun snapshot(): List<Entry> = synchronized(lock) { ArrayList(entries) }- /** Pages still on disk, newest first — what the 产物 panel lists. */+ /** How many revisions one artifact is allowed to keep. */+ private const val MAX_VERSIONS = 20++ /**+ * Fold a page list down to **one row per artifact**, newest first.+ *+ * Pure, and separated from [artifacts] / [pages] so the rule can be tested+ * without a device: the two callers differ only in what they do about a+ * revision whose file is gone, and having that difference be one argument+ * is what keeps "the panel and the brain agree about what exists" true by+ * construction rather than by review.+ *+ * @param keepMissing when true, an artifact whose every revision has lost+ * its file still gets a row — its newest revision. The brain's list wants+ * that (a page that is gone is still a page that was made); the panel+ * does not (a row that offers to open nothing is worse than an empty+ * shelf, and [artifacts] shows the newest revision *that is there*).+ */+ internal fun collapseToArtifacts(+ all: List<Entry>,+ keepMissing: Boolean,+ ): List<Entry> = all+ .filter { it.role == Role.PAGE }+ .groupBy { it.groupId }+ .values+ .mapNotNull { revs ->+ revs.filter { it.page != null }.maxByOrNull { it.version }+ ?: if (keepMissing) revs.maxByOrNull { it.version } else null+ }+ .sortedByDescending { it.ts }++ /**+ * The version number a new revision of [groupId] should get: one past the+ * highest already used, or 1 when the artifact is new.+ *+ * Pure for the same reason as [collapseToArtifacts]. Monotonic on purpose —+ * nothing here reuses a number, so [restoreVersion] can file old bytes as a+ * new version and leave the history append-only.+ */+ internal fun nextVersionOf(all: List<Entry>, groupId: Long): Int =+ all.filter { it.role == Role.PAGE && it.groupId == groupId }+ .maxOfOrNull { it.version }?.plus(1) ?: 1++ /**+ * What a `show_html` should be filed under, and the target to carry into+ * the rest of the turn.+ *+ * `explicit` is the model naming a page it wants to revise; `armed` is what+ * the turn has established so far (a `get_page`, or the panel's 继续修改).+ * Explicit wins. **Either way the target comes back cleared**, and that is+ * the load-bearing half: a target is good for *one* page, so a turn that+ * reads a page back and then draws two of them gets a revision and then a+ * new artifact — not two revisions of the same thing.+ *+ * Found the hard way: `get_page` followed by two `show_html` calls left the+ * second, unrelated page numbered 「v5」 of the first, because the target was+ * read without being consumed.+ *+ * @return the group to file under (null = a new artifact), and the target+ * the caller should keep for the next call in this turn.+ */+ internal fun resolveRevisionTarget(+ explicit: Long?,+ armed: Long?,+ ): Pair<Long?, Long?> = if (explicit != null) explicit to null else armed to null++ /**+ * One row per **artifact**, newest first — what the 产物 panel lists.+ *+ * Not one row per page file: revising a page appends a new revision rather+ * than replacing the old one, so a raw filter would show 番茄钟 three times+ * after two rounds of 继续修改, with nothing saying which is current. This+ * gathers each artifact's revisions and keeps the **newest available** one+ * — available, not merely newest, because the 100-page cap can take a+ * revision's file while an older one survives, and a panel row that offers+ * to open something which is not there is worse than one showing an older+ * revision that is.+ *+ * The row still carries its own [Entry.version], which is what the panel+ * prints as 「v3」 and what [versionsOf] takes to list the rest.+ */fun artifacts(): List<Entry> = synchronized(lock) {- entries.filter { it.role == Role.PAGE && it.page != null }.reversed()+ collapseToArtifacts(entries, keepMissing = false)}/**- * Delete one page's file and keep its row, the same end state eviction- * leaves: "you showed me a page at 3pm" stays true after the page is gone.+ * Every revision of one artifact, **newest version first**, including the+ * ones whose file is gone.+ *+ * For [net.kuafuai.andee.ui.ArtifactsUi]'s version list. Unlike [artifacts]+ * this does not drop a missing file: a version whose bytes are gone is+ * still a fact about the artifact's history, and the list has to be able to+ * say "v2 was here, it is not any more" rather than quietly skip from v3+ * to v1.+ */+ fun versionsOf(groupId: Long): List<Entry> = synchronized(lock) {+ entries.filter { it.role == Role.PAGE && it.groupId == groupId }+ .sortedByDescending { it.version }+ }++ /** The artifact's newest revision that still has bytes, or null if none do. */+ fun currentOf(groupId: Long): Entry? = synchronized(lock) {+ entries.filter { it.role == Role.PAGE && it.groupId == groupId && it.page != null }+ .maxByOrNull { it.version }+ }++ /**+ * Every page ever archived, newest first — **including the rows whose file+ * is gone**.+ *+ * [artifacts] cannot serve the brain: it filters on `page != null`, which is+ * right for a panel that offers to open one and wrong for a question about+ * what was made. A row whose file the 100-page cap has taken still records+ * that the page existed and when — the honest answer to 「上次那个番茄钟」 for+ * a page that is actually gone — and a brain that cannot see the row answers+ * "I never made that", which is a failure the user can check against the+ * panel in front of them.+ *+ * **Collapsed to one row per artifact, the newest available revision** — the+ * same shape [artifacts] gives the panel, for the same reason. The brain+ * asks "what have I made"; twelve rows of one timer's revision history is+ * not an answer to that. A superseded revision is not lost — `get_page`+ * takes any id [versionsOf] would show — but it does not crowd the list.+ */+ fun pages(): List<Entry> = synchronized(lock) {+ collapseToArtifacts(entries, keepMissing = true)+ }++ /**+ * One line per recent artifact for the per-turn user message; empty when+ * there are none.+ *+ * **Why this rides on the user message and not in the system prompt.**+ * Same reason the notebook index does (see [LocalBrain]): `LocalPrompt` is a+ * constant precisely so DeepSeek's prefix cache survives, and the system+ * message is the head of the request — anything injected there invalidates+ * the whole conversation behind it. The user message is the one part of the+ * request that is already new every turn (it carries the clock), so this+ * costs nothing that was not already being paid.+ *+ * **Why an index as well as `list_pages`.** A tool answers a question the+ * model thought to ask. The failure this is here to prevent is the one+ * where it does not think to ask — 「上次那个表格改一下」 drawing a brand new+ * table, because nothing in front of it said the old one still existed. A+ * line in the context is the difference between "there is a tool for that"+ * and knowing the thing is there.+ *+ * One line per artifact, and the version is printed: a model revising+ * 「番茄钟 (v3)」 knows it is working on a page that has already been through+ * three rounds, which is the difference between continuing someone's work+ * and starting over on top of it.+ */+ fun indexForPrompt(max: Int = 5): String {+ val recent = pages().take(max)+ if (recent.isEmpty()) return ""+ // `MM-dd HH:mm` and not `yyyy-MM-dd`: the year is noise on a shelf of+ // things made on this device, and the model reads a month-day fine.+ val fmt = SimpleDateFormat("MM-dd HH:mm", Locale.US)+ return recent.joinToString("\n") { e ->+ val bytes = e.page?.length() ?: 0L+ val state = if (bytes > 0) "${(bytes + 1023) / 1024} KB" else "file gone"+ "- #${e.id} ${e.text} (v${e.version} · ${fmt.format(Date(e.ts))} · $state)"+ }+ }++ /**+ * One page by the id [pages] reported, or null when nothing has that id.+ *+ * Filtered on [Role.PAGE] and not merely on the id: ids are shared with the+ * chatter rows, and a caller that read an id off a stale list would+ * otherwise be handed someone's sentence as if it were a page.+ *+ * **Any revision is addressable, not only the current one.** Once a+ * revision has an id the brain may hold it across turns, and the user can+ * ask for "the version before this one" — so an id that names a superseded+ * revision has to keep working rather than answer "no such page".+ */+ fun pageById(id: Long): Entry? = synchronized(lock) {+ entries.firstOrNull { it.id == id && it.role == Role.PAGE }+ }++ /**+ * How much of a page's source is handed to the brain in one go.+ *+ * Two callers, so it lives here rather than at either one: the 继续修改+ * prompt ([net.kuafuai.andee.BodyCoreService.artifactEditQuery], which+ * inlines a page so a revision is a revision) and `ui.get_page` (which+ * reads one back so the brain can revise or answer about it unaided).+ * They must not drift — the same page has to come back the same size+ * whichever door it went out of.+ *+ * A generated page is routinely 10–60 KB of inline CSS and JS, which is+ * nothing to the request; one with a base64 image can be several hundred+ * KB, which is most of a context window for a picture the brain already+ * drew and cannot usefully redraw from text.+ */+ const val ARTIFACT_SOURCE_MAX = 60_000++ /**+ * Delete one artifact — every revision of it — and keep one row behind in+ * its place, the same end state eviction leaves: "you showed me a page at+ * 3pm" stays true after the page is gone.+ *+ * **It takes a group, not a revision.** Deleting from the panel means+ * "get this off my shelf", and leaving v2 and v1 of the thing the user just+ * deleted still sitting in the version list would be the opposite of that.+ * A single revision is not something the panel offers to remove, which is+ * why this reads the group off [id] rather than trusting a caller to pass+ * the right one.*/fun deletePage(id: Long) {synchronized(lock) {- val i = entries.indexOfFirst { it.id == id }- if (i < 0) return- val e = entries[i]- e.page?.let { runCatching { it.delete() } }- entries[i] = e.copy(page = null)+ val hit = entries.firstOrNull { it.id == id && it.role == Role.PAGE } ?: return+ val group = hit.groupId+ // Newest first, so the row left standing is the current version —+ // the one whose title and date the user recognises.+ val doomed = entries.filter { it.role == Role.PAGE && it.groupId == group }+ .sortedByDescending { it.version }+ for (e in doomed) {+ e.page?.let { runCatching { it.delete() } }+ entries.remove(e)+ }+ entries.add(hit.copy(page = null, version = hit.version))save()}listener?.invoke()@@ -185,7 +413,8 @@ object ChatHistory {fun addError(text: String) = add(Role.ERROR, text, null)/**- * Archive a page the brain just composed and record it.+ * Archive a page the brain just composed and record it as a revision of an+ * artifact.** Returns the archived file for the caller to hand to [HtmlActivity], so* the copy being displayed and the copy in the history are the same bytes@@ -193,12 +422,22 @@ object ChatHistory {* for the archive) meant re-opening from history could show something* subtly different from what was on screen a minute ago.*+ * **@param groupId which artifact this is a revision of.** Omitted (or+ * null) means a brand-new artifact: the row becomes its own group and+ * starts at v1. Pass an existing artifact's group — the panel's 继续修改+ * does, and so does `ui.get_page`'s follow-up `show_html` — and this+ * lands as its next revision instead of a near-identical neighbour on the+ * shelf. Callers get the group from [Entry.groupId].+ ** Falls back to null on IO failure; the caller still has the HTML string* and can stage it itself, it just won't be in the list.*/- fun addPage(title: String, html: String): File? {+ fun addPage(title: String, html: String, groupId: Long? = null): File? {val ctx = appContext ?: return null- val id = synchronized(lock) { nextId }+ val (id, group, version) = synchronized(lock) {+ val g = groupId ?: nextId+ Triple(nextId, g, nextVersionOf(entries, g))+ }val file = runCatching {val dir = File(ctx.filesDir, "pages").apply { mkdirs() }File(dir, "page_$id.html").also { it.writeText(html) }@@ -206,18 +445,63 @@ object ChatHistory {Log.w(TAG, "history: could not archive page: ${it.message}")return null}- add(Role.PAGE, title, file)+ add(Role.PAGE, title, file, groupId = group, version = version)return file}- private fun add(role: Role, text: String, page: File?, turn: String? = null) {+ /**+ * Make an older revision current again — **as a new revision**, not by+ * rewriting the old one.+ *+ * Nothing already written is touched: the returned entry is the previous+ * version's bytes filed as the next version number, so the artifact's+ * history stays append-only and 撤销 is just another 回退. That is what+ * makes this safe to expose on a tap — a rollback that edited history in+ * place would leave no way back to the thing being rolled back from.+ *+ * Returns the new revision's file, or null when [id] names nothing, is not+ * a page, or has no bytes left to copy.+ */+ fun restoreVersion(id: Long): File? {+ val ctx = appContext ?: return null+ val source = synchronized(lock) { entries.firstOrNull { it.id == id && it.role == Role.PAGE } }+ ?: return null+ val bytes = source.page ?: return null+ val html = runCatching { bytes.readText() }.getOrNull() ?: return null+ return addPage(source.text, html, groupId = source.groupId)+ }++ private fun add(+ role: Role,+ text: String,+ page: File?,+ turn: String? = null,+ groupId: Long? = null,+ version: Int = 1,+ ) {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, turn))+ val id = nextId+++ entries.add(+ Entry(+ id = id,+ ts = System.currentTimeMillis(),+ role = role,+ text = clean,+ page = page,+ turn = turn,+ // A non-page row is never grouped, so it is its own group:+ // that keeps `groupId` a total function over the list rather+ // than a field that is meaningful for one role and garbage+ // for the other three.+ groupId = groupId ?: id,+ version = version,+ ),+ )trim()save()}@@ -226,7 +510,22 @@ object ChatHistory {/** Caller holds [lock]. */private fun trim() {- // Pages first, so one that just lost its file is an ordinary row below.+ // Versions of one artifact first: a page revised twenty times should+ // not be able to push every other artifact off the shelf, and the+ // oldest revisions are the ones nobody is coming back for. Oldest+ // first, so the current version and the one before it always survive.+ val overVersions = entries.filter { it.role == Role.PAGE }+ .groupBy { it.groupId }+ .flatMap { (_, revs) ->+ revs.sortedBy { it.version }.dropLast(MAX_VERSIONS)+ }+ for (old in overVersions) {+ val i = entries.indexOfFirst { it.id == old.id }+ if (i < 0) continue+ old.page?.let { runCatching { it.delete() } }+ entries.removeAt(i)+ }+ // Pages next, so one that just lost its file is an ordinary row below.var pages = 0for (i in entries.indices.reversed()) {val e = entries[i]@@ -271,6 +570,8 @@ object ChatHistory {.put("text", e.text).put("page", e.page?.name ?: JSONObject.NULL).put("turn", e.turn ?: JSONObject.NULL)+ .put("group", e.groupId)+ .put("version", e.version))}f.writeText(arr.toString())@@ -298,7 +599,17 @@ object ChatHistory {// 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, turn))+ // Rows written before versions existed have no `group`, and+ // reading them as absent must not regroup them under id 0 —+ // that would collapse every pre-existing page into one artifact+ // the first time the panel was opened. Absent means "its own+ // group", which is exactly what those rows are: one page each,+ // v1, because nothing could revise them back then.+ val group = if (o.has("group")) o.optLong("group") else id+ val version = if (o.has("version")) o.optInt("version", 1) else 1+ entries.add(+ Entry(id, o.optLong("ts"), role, o.optString("text"), page, turn, group, version),+ )if (id >= nextId) nextId = id + 1}}.onFailure {diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xmlindex 383f5c3..96e008b 100644--- a/app/src/main/res/values-en/strings.xml+++ b/app/src/main/res/values-en/strings.xml@@ -176,6 +176,11 @@<string name="artifacts_delete_confirm">Really delete</string><string name="artifacts_empty">Nothing here yet.\nAsk it to build you a page — say, “make me a pomodoro timer”.</string><string name="artifacts_cap_note">Only the latest 100 are kept</string>+ <string name="artifacts_versions">Versions</string>+ <string name="artifacts_versions_count">%1$d versions</string>+ <string name="artifacts_version_current">current</string>+ <string name="artifacts_version_gone">gone</string>+ <string name="artifacts_restore">Go back to this</string><string name="artifacts_edit_prompt">How should “%1$s” change? Say it or type it</string><string name="artifacts_edit_said">Revise “%1$s”: %2$s</string>@@ -419,6 +424,7 @@<string name="narrate_launch">Opening…</string><string name="narrate_system">Pressing a system key…</string><string name="narrate_show_html">Putting it on screen…</string>+ <string name="narrate_pages">Looking through what it made before…</string><string name="narrate_camera">Taking a look…</string><string name="narrate_dog">Moving a leg…</string><string name="narrate_market_search">Finding a tool…</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 9ee61cf..436fe91 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -151,6 +151,12 @@<string name="artifacts_delete_confirm">确认删除</string><string name="artifacts_empty">还没有产物。\n让它给你做个网页试试,比如「做个番茄钟」。</string><string name="artifacts_cap_note">只保留最近 100 个</string>+ <!-- 版本: a revision of an artifact. See ChatHistory.Entry.version. -->+ <string name="artifacts_versions">版本</string>+ <string name="artifacts_versions_count">%1$d 个版本</string>+ <string name="artifacts_version_current">当前</string>+ <string name="artifacts_version_gone">已清理</string>+ <string name="artifacts_restore">回到这版</string><!-- Shown on the card after 继续修改, while it waits for the change. --><string name="artifacts_edit_prompt">要怎么改「%1$s」?说出来或打字告诉我</string><!-- The scrollback row for the user's change request. -->@@ -498,6 +504,7 @@<string name="narrate_launch">打开…</string><string name="narrate_system">操作系统按键…</string><string name="narrate_show_html">把结果放到屏幕上…</string>+ <string name="narrate_pages">翻一下之前做的东西…</string><string name="narrate_camera">看一眼…</string><string name="narrate_dog">动一下腿…</string><!--diff --git a/app/src/test/java/net/kuafuai/andee/ui/ChatHistoryVersionsTest.kt b/app/src/test/java/net/kuafuai/andee/ui/ChatHistoryVersionsTest.ktnew file mode 100644index 0000000..434de66--- /dev/null+++ b/app/src/test/java/net/kuafuai/andee/ui/ChatHistoryVersionsTest.kt@@ -0,0 +1,244 @@+package net.kuafuai.andee.ui++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test+import java.io.File++/**+ * The artifact-versioning rules, tested without a device.+ *+ * This is the half of 产物 versioning that has no UI to sanity-check it by eye:+ * which rows the panel shows, which the brain is told about, and what number a+ * revision gets. Getting any of them wrong is invisible until a user has+ * revised a page twice and finds three of them on the shelf — the exact bug+ * these rules exist to prevent.+ *+ * [ChatHistory.collapseToArtifacts] / [ChatHistory.nextVersionOf] are pure and+ * `internal` for this reason; everything else in the object needs a Context.+ */+class ChatHistoryVersionsTest {++ private fun page(+ id: Long,+ group: Long,+ version: Int,+ hasFile: Boolean = true,+ ts: Long = id,+ title: String = "番茄钟",+ ) = ChatHistory.Entry(+ id = id,+ ts = ts,+ role = ChatHistory.Role.PAGE,+ text = title,+ page = if (hasFile) File("/tmp/page_$id.html") else null,+ turn = null,+ groupId = group,+ version = version,+ )++ private fun chatter(id: Long) = ChatHistory.Entry(+ id = id,+ ts = id,+ role = ChatHistory.Role.USER,+ text = "做个番茄钟",+ page = null,+ turn = null,+ groupId = id,+ version = 1,+ )++ // ---- collapseToArtifacts ----++ @Test+ fun `three revisions collapse to one row, the newest`() {+ val all = listOf(+ page(1, group = 1, version = 1),+ page(2, group = 1, version = 2),+ page(3, group = 1, version = 3),+ )+ val out = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ assertEquals(1, out.size)+ assertEquals(3L, out[0].id)+ assertEquals(3, out[0].version)+ }++ @Test+ fun `separate artifacts stay separate`() {+ val all = listOf(+ page(1, group = 1, version = 1),+ page(2, group = 1, version = 2),+ page(3, group = 3, version = 1, ts = 99),+ )+ val out = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ assertEquals(2, out.size)+ // Newest first by the surviving revision's timestamp.+ assertEquals(3L, out[0].id)+ assertEquals(2L, out[1].id)+ }++ @Test+ fun `newest first ordering`() {+ val all = listOf(+ page(1, group = 1, version = 1, ts = 100),+ page(2, group = 2, version = 1, ts = 300),+ page(3, group = 3, version = 1, ts = 200),+ )+ val out = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ assertEquals(listOf(2L, 3L, 1L), out.map { it.id })+ }++ @Test+ fun `non-page rows are ignored`() {+ val all = listOf(chatter(9), page(1, group = 1, version = 1))+ val out = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ assertEquals(1, out.size)+ assertEquals(1L, out[0].id)+ }++ @Test+ fun `a revision whose file is gone falls back to an older one that survives`() {+ // The 100-page cap took v3's file. The panel must still offer+ // *something* openable rather than a row that opens nothing.+ val all = listOf(+ page(1, group = 1, version = 1),+ page(2, group = 1, version = 2),+ page(3, group = 1, version = 3, hasFile = false),+ )+ val panel = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ assertEquals(2L, panel[0].id)+ assertEquals(2, panel[0].version)+ }++ @Test+ fun `the brain still sees an artifact whose every file is gone`() {+ // Same input, keepMissing: a page that was made and then lost is still+ // a page that was made — "I never made that" is the failure here.+ val all = listOf(+ page(1, group = 1, version = 1, hasFile = false),+ page(2, group = 1, version = 2, hasFile = false),+ )+ val panel = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ assertEquals(0, panel.size)++ val brain = ChatHistory.collapseToArtifacts(all, keepMissing = true)+ assertEquals(1, brain.size)+ assertEquals(2, brain[0].version)+ }++ @Test+ fun `empty input stays empty`() {+ assertEquals(0, ChatHistory.collapseToArtifacts(emptyList(), keepMissing = true).size)+ assertEquals(0, ChatHistory.collapseToArtifacts(emptyList(), keepMissing = false).size)+ }++ // ---- nextVersionOf ----++ @Test+ fun `a new artifact starts at version one`() {+ assertEquals(1, ChatHistory.nextVersionOf(emptyList(), groupId = 7))+ }++ @Test+ fun `the next revision is one past the highest, not the newest by id`() {+ // v2 was evicted, v1 and v3 remain: the next one is v4, and it must not+ // collide with the v3 that is still on the shelf.+ val all = listOf(+ page(1, group = 1, version = 1),+ page(3, group = 1, version = 3),+ )+ assertEquals(4, ChatHistory.nextVersionOf(all, groupId = 1))+ }++ @Test+ fun `another artifact's versions do not leak in`() {+ val all = listOf(+ page(1, group = 1, version = 1),+ page(2, group = 2, version = 9),+ )+ assertEquals(2, ChatHistory.nextVersionOf(all, groupId = 1))+ }++ @Test+ fun `nextVersionOf ignores a missing file`() {+ // A revision whose bytes are gone still occupies its number — reusing+ // it would make two different pages both claim to be v2.+ val all = listOf(page(1, group = 1, version = 1, hasFile = false))+ assertEquals(2, ChatHistory.nextVersionOf(all, groupId = 1))+ }++ // ---- the two lists agree about what exists ----++ @Test+ fun `panel and brain never disagree about a page that is still there`() {+ val all = listOf(+ page(1, group = 1, version = 1),+ page(2, group = 1, version = 2),+ page(3, group = 3, version = 1, ts = 500),+ chatter(4),+ )+ val panel = ChatHistory.collapseToArtifacts(all, keepMissing = false)+ val brain = ChatHistory.collapseToArtifacts(all, keepMissing = true)+ // Everything the panel shows, the brain shows too — under the same id.+ val brainIds = brain.map { it.id }.toSet()+ for (p in panel) assertEquals(true, p.id in brainIds)+ }++ @Test+ fun `a default-constructed entry is its own artifact at v1`() {+ // The shape `add()` builds for a page with no group given: a brand-new+ // artifact. If this ever drifts, every fresh page would join group 0.+ val e = ChatHistory.Entry(+ id = 42, ts = 0, role = ChatHistory.Role.PAGE, text = "x", page = null,+ )+ assertEquals(42L, e.groupId)+ assertEquals(1, e.version)+ assertNull(e.turn)+ }++ // ---- resolveRevisionTarget: the consume-once rule ----++ @Test+ fun `an armed target files the next page as that revision`() {+ val (group, rest) = ChatHistory.resolveRevisionTarget(explicit = null, armed = 7L)+ assertEquals(7L, group)+ // And it is spent: the next show_html in the same turn is a new artifact.+ assertNull(rest)+ }++ @Test+ fun `the second show_html in a turn does not join the first`() {+ // The regression: get_page(3) then two show_html calls must give a+ // revision AND a new artifact — not two revisions of the same page.+ var target: Long? = 3L+ val (first, r1) = ChatHistory.resolveRevisionTarget(explicit = null, armed = target)+ target = r1+ val (second, r2) = ChatHistory.resolveRevisionTarget(explicit = null, armed = target)+ assertEquals(3L, first)+ assertNull(second)+ assertNull(r2)+ }++ @Test+ fun `an explicit revise outranks an armed target`() {+ val (group, rest) = ChatHistory.resolveRevisionTarget(explicit = 9L, armed = 3L)+ assertEquals(9L, group)+ assertNull(rest)+ }++ @Test+ fun `with nothing armed or named, a page is a new artifact`() {+ val (group, rest) = ChatHistory.resolveRevisionTarget(explicit = null, armed = null)+ assertNull(group)+ assertNull(rest)+ }++ @Test+ fun `a revise that names nothing falls back to the armed target`() {+ // Callers resolve `revise` against the page list before getting here, so+ // an id that names nothing arrives as null — and the turn's own context+ // should still win rather than the page becoming a stray new artifact.+ val (group, _) = ChatHistory.resolveRevisionTarget(explicit = null, armed = 5L)+ assertEquals(5L, group)+ }+}