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(desktop): show_html, list_pages, get_page — the artifact shelf
booboosuiadd34dea0d27
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.ktindex b537af4..68e85f5 100644--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt@@ -75,7 +75,7 @@ class DesktopBrainHost()}- override fun pagesIndex(): String = ""+ override fun pagesIndex(): String = Pages.indexForPrompt()override fun topicsIndex(): String = Scrollback.topicsIndex()override fun foldTopic(title: String, summary: String, rows: List<ScrollRow>, text: String): FoldedTopic? {diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Pages.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Pages.ktnew file mode 100644index 0000000..d69f2e2--- /dev/null+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Pages.kt@@ -0,0 +1,157 @@+package net.kuafuai.andee.desktop++import net.kuafuai.andee.util.Log+import org.json.JSONArray+import org.json.JSONObject+import java.io.File+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++/**+ * The desktop's pages — the phone's `ChatHistory` artifact shelf, the page half.+ *+ * `show_html` builds a page and the device keeps it, versioned the same way:+ * one artifact = one [groupId], each revision a monotonically increasing+ * [version], append-only (even a rollback is filed as the next version). The+ * newest 20 revisions of an artifact and the newest 100 page files survive;+ * a row whose file is gone is still a fact (the brain must say "it was made,+ * the bytes are not there", never "I never made that").+ *+ * Ownership of "which artifact is this a revision of" is decided here, never by+ * the model — the same rule as the phone. `get_page` arms the target, `show_html`+ * consumes it (explicit `revise` wins), and a turn boundary clears it, 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 first.+ */+object Pages {++ private const val TAG = "Pages"+ private const val MAX_PAGES = 100+ private const val MAX_VERSIONS = 20++ data class Page(val id: Long, val ts: Long, val title: String, val groupId: Long, val version: Int, val file: File?)++ private val lock = Any()+ private val entries = mutableListOf<Page>()+ private var nextId = 1L++ private val dir get() = File(AppDirs.root, "pages").apply { mkdirs() }+ private val indexFile get() = AppDirs.file("pages.json")++ init { load() }++ /** The id a `show_html` in this turn should file under; null = new artifact. Set by get_page, cleared each turn. */+ @Volatile private var armedGroup: Long? = null++ fun beginTurn() { armedGroup = null }+ fun armGroup(id: Long) { armedGroup = id }++ /** The phone's resolveRevisionTarget: explicit wins, and either way the target is consumed. */+ fun armOrResolve(explicit: Long?): Long? = resolve(explicit)++ /** The phone's resolveRevisionTarget: explicit wins, and either way the target is consumed. */+ private fun resolve(explicit: Long?): Long? {+ val g = explicit ?: armedGroup+ armedGroup = null+ return g+ }++ fun add(title: String, html: String, groupId: Long?): Page? {+ val (id, group, version) = synchronized(lock) {+ val g = groupId ?: nextId+ Triple(nextId, g, nextVersionOf(g))+ }+ val file = runCatching { File(dir, "page_$id.html").also { it.writeText(html) } }.getOrElse {+ Log.w(TAG, "could not archive page: ${it.message}")+ return null+ }+ synchronized(lock) {+ entries.add(Page(id, System.currentTimeMillis(), title.trim(), group, version, file))+ trim()+ save()+ }+ return Page(id, System.currentTimeMillis(), title, group, version, file)+ }++ /** One row per artifact, newest available revision first — the model's list. */+ fun pages(): List<Page> = synchronized(lock) {+ entries.groupBy { it.groupId }.values+ .mapNotNull { revs -> revs.filter { it.file != null }.maxByOrNull { it.version } ?: revs.maxByOrNull { it.version } }+ .sortedByDescending { it.ts }+ }++ /** Any revision is addressable, not just the current one. */+ fun pageById(id: Long): Page? = synchronized(lock) { entries.firstOrNull { it.id == id } }++ fun versionsOf(groupId: Long): List<Page> = synchronized(lock) {+ entries.filter { it.groupId == groupId }.sortedByDescending { it.version }+ }++ fun currentOf(groupId: Long): Page? = synchronized(lock) {+ entries.filter { it.groupId == groupId && it.file != null }.maxByOrNull { it.version }+ }++ private fun nextVersionOf(groupId: Long): Int = synchronized(lock) {+ entries.filter { it.groupId == groupId }.maxOfOrNull { it.version }?.plus(1) ?: 1+ }++ fun indexForPrompt(max: Int = 5): String {+ val recent = pages().take(max)+ if (recent.isEmpty()) return ""+ val fmt = SimpleDateFormat("MM-dd HH:mm", Locale.US)+ return recent.joinToString("\n") { e ->+ val bytes = e.file?.length() ?: 0L+ val state = if (bytes > 0) "${(bytes + 1023) / 1024} KB" else "file gone"+ "- #${e.id} ${e.title} (v${e.version} · ${fmt.format(Date(e.ts))} · $state)"+ }+ }++ /** Caller holds [lock]. */+ private fun trim() {+ val overVersions = entries.groupBy { it.groupId }+ .flatMap { (_, revs) -> revs.sortedBy { it.version }.dropLast(MAX_VERSIONS) }+ for (old in overVersions) {+ old.file?.let { runCatching { it.delete() } }+ entries.removeIf { it.id == old.id }+ }+ var pages = 0+ for (i in entries.indices.reversed()) {+ val e = entries[i]+ if (e.file == null) continue+ pages+++ if (pages > MAX_PAGES) {+ runCatching { e.file.delete() }+ entries[i] = e.copy(file = null)+ }+ }+ }++ private fun save() = synchronized(lock) {+ val arr = JSONArray()+ for (e in entries) arr.put(+ JSONObject().put("id", e.id).put("ts", e.ts).put("title", e.title)+ .put("group", e.groupId).put("version", e.version).put("file", e.file != null),+ )+ runCatching {+ val tmp = File(indexFile.parentFile, "${indexFile.name}.tmp")+ tmp.writeText(JSONObject().put("pages", arr).put("next", nextId).toString())+ tmp.renameTo(indexFile)+ }.onFailure { Log.w(TAG, "save failed: ${it.message}") }+ }++ private fun load() {+ if (!indexFile.exists()) return+ runCatching {+ val o = JSONObject(indexFile.readText())+ val arr = o.optJSONArray("pages") ?: JSONArray()+ for (i in 0 until arr.length()) {+ val e = arr.getJSONObject(i)+ val id = e.getLong("id")+ val file = if (e.optBoolean("file")) File(dir, "page_$id.html").takeIf { it.exists() } else null+ entries.add(Page(id, e.getLong("ts"), e.getString("title"), e.getLong("group"), e.optInt("version", 1), file))+ }+ nextId = maxOf(o.optLong("next", 1L), (entries.maxOfOrNull { it.id } ?: 0L) + 1)+ }.onFailure { Log.e(TAG, "could not read the page shelf; starting empty", it) }+ }+}diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.ktindex ae52c36..50f2e16 100644--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt@@ -42,9 +42,16 @@ import java.util.concurrent.TimeUnit*/class UiTools : DesktopBrainHost.ToolProvider {- override fun handles(method: String) = method == "ui.ask" || method == "ui.alert"+ override fun handles(method: String) = method.startsWith("ui.")++ override fun turnStarted(kind: String) = Pages.beginTurn()override fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any? = when (method) {+ "ui.show_html" -> showHtml(p)+ "ui.list_pages" -> listPages()+ "ui.get_page" -> getPage(p)+ "ui.list_topics" -> listTopics()+ "ui.get_topic" -> getTopic(p)"ui.ask" -> {val question = p.optString("question").trim().ifEmpty { throw IllegalArgumentException("ui.ask requires question") }// Caller-supplied buttons pass through untouched — those are the model's@@ -73,6 +80,116 @@ class UiTools : DesktopBrainHost.ToolProvider {}else -> throw IllegalArgumentException("unknown method $method")}++ // ---- pages: the artifacts it made --------------------------------------++ private fun showHtml(p: JSONObject): JSONObject {+ val html = p.optString("html").ifEmpty { throw IllegalArgumentException("ui.show_html requires html") }+ val defaultTitle = if (Strings.lang() == "zh") "AI 界面" else "AI page"+ val title = p.optString("title").ifEmpty { defaultTitle }+ // Ownership is decided here, never by the model: get_page armed a group,+ // an explicit `revise` wins, and either way the target is consumed.+ val group = Pages.armOrResolve(p.optString("revise").trim().ifEmpty { null }?.toLongOrNull())+ val page = Pages.add(title, html, group) ?: throw IllegalStateException("the page could not be saved")+ // The phone renders in an in-app WebView; the Mac's honest first cut opens+ // the page in the default browser. The shelf (list_pages / get_page / the+ // per-turn index) is what the model reads back, and that works the same.+ runCatching { net.kuafuai.andee.desktop.mac.Bridge.open(page.file!!.absolutePath) }+ .onFailure { Log.w("UiTools", "could not open the page: ${it.message}") }+ Scrollback.add(Scrollback.Role.ASSISTANT, "📄 ${title}")+ return JSONObject().put("opened", true).put("id", page.id).put("title", title)+ .put("version", page.version).put("closed", false)+ }++ private fun listPages(): JSONObject {+ val arr = org.json.JSONArray()+ for (e in Pages.pages()) {+ arr.put(+ JSONObject().put("id", e.id).put("title", e.title)+ .put("created", LocalTime.format(e.ts)).put("bytes", e.file?.length() ?: 0L)+ .put("available", e.file != null).put("version", e.version)+ .put("versions", Pages.versionsOf(e.groupId).size),+ )+ }+ return JSONObject().put("items", arr).put("count", arr.length()).put(+ "note",+ when {+ arr.length() == 0 -> "No pages have been made 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. available:false means the page's file is gone. Use get_page for the source of one you are going to change."+ },+ )+ }++ private fun getPage(p: JSONObject): JSONObject {+ val id = p.optLong("id", Long.MIN_VALUE).takeIf { it != Long.MIN_VALUE }+ ?: throw IllegalArgumentException("ui.get_page requires integer id, from list_pages")+ val entry = Pages.pageById(id)+ val file = entry?.file+ return when {+ 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.title)+ .put("note", "That page was made, but its file is gone — 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 {+ // Reading back has one purpose: the show_html that follows is the revision.+ Pages.armGroup(entry.groupId)+ val cap = net.kuafuai.andee.ui.ScrollbackLimits.ARTIFACT_SOURCE_MAX+ val cut = html.length > cap+ JSONObject().put("found", true).put("id", entry.id).put("title", entry.title)+ .put("created", LocalTime.format(entry.ts)).put("truncated", cut)+ .put("version", entry.version).put("versions", Pages.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." + if (cut) " Cut at $cap characters; rebuild the missing tail in the same style." else "")+ }+ }+ }+ }++ // ---- topics: the finished conversations, read back ----------------------++ private fun listTopics(): JSONObject {+ val arr = org.json.JSONArray()+ for (t in Scrollback.topics()) {+ arr.put(+ JSONObject().put("id", t.id).put("title", t.title).put("ended", LocalTime.format(t.endedAt))+ .put("messages", Scrollback.snapshot().count { it.topicId == t.id })+ .put("available", Scrollback.topicText(t.id) != null),+ )+ }+ return JSONObject().put("items", arr).put("count", arr.length()).put(+ "note",+ when {+ arr.length() == 0 -> "No conversations have been put away yet. Nothing is missing."+ else -> "Newest first. These are FINISHED conversations; the one-line summary in your context is not the whole story. Read one back with get_topic before answering about a detail."+ },+ )+ }++ private fun getTopic(p: JSONObject): JSONObject {+ val id = p.optLong("id", Long.MIN_VALUE).takeIf { it != Long.MIN_VALUE }+ ?: throw IllegalArgumentException("ui.get_topic requires integer id, from list_topics")+ val topic = Scrollback.topics().firstOrNull { it.id == id }+ val text = Scrollback.topicText(id)+ return when {+ topic == null -> JSONObject().put("found", false)+ .put("note", "No topic has that id. list_topics shows what there is — take an id from there, and do not make one up.")+ text == null -> JSONObject().put("found", false).put("id", topic.id).put("title", topic.title)+ .put("note", "That topic exists — 「${topic.title}」 — but its text could not be read, so the details are gone. Say so; do not reconstruct it.")+ else -> {+ val cap = net.kuafuai.andee.ui.ScrollbackLimits.TOPIC_TEXT_MAX+ val cut = text.length > cap+ JSONObject().put("found", true).put("id", topic.id).put("title", topic.title)+ .put("ended", LocalTime.format(topic.endedAt)).put("truncated", cut)+ .put("text", if (cut) text.take(cap) else text)+ .put("note", "The conversation as it happened. This call showed the user nothing." + if (cut) " Cut at $cap characters." else "")+ }+ }+ }}/**