Skip to content

armgit / andee

Public Imported from GitHub
0

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(topics): put finished topics away, and let the user pick them back up

booboosui0474028b7550
diff --git a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
index ab17ab8..53f4531 100644
--- a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
+++ b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
@@ -100,6 +100,13 @@ class BodyCoreService : Service() {
*/
private var pendingArtifact: net.kuafuai.andee.ui.ChatHistory.Entry? = null
+ /**
+ * The folded topic the user just tapped 继续话题 on, waiting for them to say
+ * where to take it. Same lifetime as [pendingArtifact], and the two exclude
+ * each other: whichever was tapped last is what the next words are about.
+ */
+ private var pendingTopic: net.kuafuai.andee.ui.ChatHistory.Topic? = null
+
private lateinit var audio: AudioIO
private lateinit var asr: AsrController
private lateinit var tts: TtsController
@@ -414,6 +421,16 @@ class BodyCoreService : Service() {
"suggested",
)
}
+
+ override fun onTopicContinue(topic: net.kuafuai.andee.ui.ChatHistory.Topic) {
+ beginTopicContinue(topic)
+ }
+
+ /** Same path as [onTextOpen]: write a page, open it over a folded card. */
+ override fun onTopicTranscript(topic: net.kuafuai.andee.ui.ChatHistory.Topic) {
+ val file = net.kuafuai.andee.ui.TextPage.writeTopic(this@BodyCoreService, topic) ?: return
+ openPageFrom(topic.title, file)
+ }
})
// Before the card is built: FloatingWindowUi.build() reads the log to
// lay out its first rows, and registers itself as the listener.
@@ -1002,6 +1019,8 @@ class BodyCoreService : Service() {
// the brain gets that plus the page it is about.
val editing = pendingArtifact
pendingArtifact = null
+ val continuing = pendingTopic
+ pendingTopic = 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
@@ -1009,8 +1028,17 @@ class BodyCoreService : Service() {
// 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) } ?: said
- val row = if (editing != null) AppLocale.str(this, R.string.artifacts_edit_said, editing.text, said) else said
+ val row = when {
+ editing != null -> AppLocale.str(this, R.string.artifacts_edit_said, editing.text, said)
+ continuing != null -> AppLocale.str(this, R.string.topic_continue_said, continuing.title, said)
+ else -> said
+ }
+ // The brain's message opens with the row's own words: a later topic fold
+ // finds this turn's row by matching that opening line, and a brain text
+ // that began differently from its row could never be put away.
+ val forBrain = editing?.let { artifactEditQuery(it, row) }
+ ?: continuing?.let { topicContinueQuery(it, row) }
+ ?: said
net.kuafuai.andee.ui.ChatHistory.addUser(
if (images.isEmpty()) row
else "${AppLocale.str(this, R.string.input_photos_row, images.size)} $row".trim(),
@@ -1116,12 +1144,15 @@ class BodyCoreService : Service() {
* place, because the alternative is ✕完成 silently throwing them out of the
* assistant.
*/
- private fun openPageFrom(entry: net.kuafuai.andee.ui.ChatHistory.Entry, file: java.io.File) {
+ private fun openPageFrom(entry: net.kuafuai.andee.ui.ChatHistory.Entry, file: java.io.File) =
+ openPageFrom(entry.text, file)
+
+ private fun openPageFrom(title: String, file: java.io.File) {
val wasFullscreen = !window.isCompact()
dispatcher.compactForUser()
// The ball hangs off the ledge rather than sitting on the page.
window.setPagePerched(true)
- net.kuafuai.andee.ui.HtmlActivity.showFile(this, file, entry.text.take(24)) {
+ net.kuafuai.andee.ui.HtmlActivity.showFile(this, file, title.take(24)) {
window.setPagePerched(false)
if (wasFullscreen) dispatcher.expand()
}
@@ -2146,6 +2177,7 @@ class BodyCoreService : Service() {
private fun beginArtifactEdit(e: net.kuafuai.andee.ui.ChatHistory.Entry) {
if (e.page == null) return
pendingArtifact = e
+ pendingTopic = null
window.setSubtitle(
AppLocale.str(this, R.string.artifacts_edit_prompt, e.text),
FloatingWindowUi.SubtitleKind.FINAL,
@@ -2153,6 +2185,60 @@ class BodyCoreService : Service() {
if (!net.kuafuai.andee.ui.TextInputActivity.isShowing) toggleTyping()
}
+ /**
+ * 继续话题: remember which topic, then ask where to take it — the same shape
+ * as [beginArtifactEdit], for the same reason: until the user says what
+ * they want there is nothing to ask the brain.
+ */
+ private fun beginTopicContinue(t: net.kuafuai.andee.ui.ChatHistory.Topic) {
+ pendingTopic = t
+ pendingArtifact = null
+ window.setSubtitle(
+ AppLocale.str(this, R.string.topic_continue_prompt, t.title),
+ FloatingWindowUi.SubtitleKind.FINAL,
+ )
+ if (!net.kuafuai.andee.ui.TextInputActivity.isShowing) toggleTyping()
+ }
+
+ /**
+ * What the brain is given for a 继续话题: the user's words, which topic,
+ * and the topic's archived conversation inlined.
+ *
+ * Inlined rather than left to `get_topic` because the whole point of the
+ * tap is "pick up where we left off", and a model that answers from the
+ * one-line marker before thinking to read the topic back is exactly the
+ * failure the read-back exists to prevent. Capped like `get_topic`.
+ *
+ * The products are listed by title and id so a "change that timer" lands
+ * on the existing page (`get_page` → `show_html revise`) instead of a new one.
+ */
+ private fun topicContinueQuery(t: net.kuafuai.andee.ui.ChatHistory.Topic, row: String): String {
+ val cap = net.kuafuai.andee.ui.ChatHistory.TOPIC_TEXT_MAX
+ val text = net.kuafuai.andee.ui.ChatHistory.topicText(t.id)
+ val outputs = net.kuafuai.andee.ui.ChatHistory.outputsOf(t.id)
+ return buildString {
+ append(row)
+ append("\n\n(I picked this from a finished topic in our conversation, topic #")
+ append(t.id).append(" 「").append(t.title)
+ append("」, and want to carry on with it. What it came to: ").append(t.summary)
+ if (outputs.isNotEmpty()) {
+ append("\nPages made in it: ")
+ append(outputs.joinToString("; ") { "#${it.groupId} ${it.text} (v${it.version})" })
+ append(". To change one, get_page it and send the revision with show_html.")
+ }
+ if (text == null) {
+ append("\nIts full text is no longer stored — work from the summary and say so if a detail is missing.)")
+ } else {
+ val cut = text.length > cap
+ append("\nThe conversation as it happened follows")
+ if (cut) append(" — cut at $cap characters, the beginning only")
+ append(".)\n\n<<<TOPIC CONVERSATION>>>\n")
+ append(if (cut) text.take(cap) else text)
+ append("\n<<<END TOPIC CONVERSATION>>>")
+ }
+ }
+ }
+
/**
* What the brain is given for a 继续修改: the user's words, the page they
* are about, and that page's current source.
@@ -2268,9 +2354,10 @@ class BodyCoreService : Service() {
return
}
acceptBrainOutput = false
- // A 继续修改 the user walked away from must not attach itself to
- // whatever they ask next.
+ // A 继续修改 / 继续话题 the user walked away from must not attach itself
+ // to whatever they ask next.
pendingArtifact = null
+ pendingTopic = null
tts.stopSpeaking()
if (asr.isActive()) asr.stop()
// Task over from the device's point of view: whatever the brain had
@@ -2314,6 +2401,11 @@ class BodyCoreService : Service() {
dispatcher.dispatch(method, params, driving = false)
},
onSay = { text -> ui.post { submitUserTurn(text, "debug.say") } },
+ // The review path, reachable on demand. Twenty minutes of
+ // waiting to find out whether it worked is long enough that the
+ // path went unexercised; this runs the same code the alarm does.
+ onSweep = { ui.post { onSweepTimer() } },
+ onSweepForced = { ui.post { localBrain?.runSweep() } },
)
srv.start()
wsServer = srv
diff --git a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt
index e6d42de..05604f5 100644
--- a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt
+++ b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt
@@ -226,6 +226,47 @@ class LocalBrain(
*/
private var internalFromIndex = -1
+ /**
+ * Loop thread only. The topic-folds a review asked for, in the order asked.
+ *
+ * **Recorded during the turn and applied after it, never in the middle.**
+ * Folding rewrites [history] — a stretch of messages is replaced by one
+ * marker — and doing that while a turn is in flight would move every index
+ * the loop is holding: the `tool` messages still to be appended would land
+ * against the wrong `tool_call_id`, which the API answers with a 400 and
+ * the session dies mid-task. So the tool only appends here, and
+ * [applyPendingFolds] runs where the turn is already over. Several are safe
+ * together because each is found by identity, not position — applying one
+ * cannot move another.
+ */
+ private val pendingFolds = mutableListOf<PendingFold>()
+
+ /**
+ * Loop thread only. The user-turn messages the review's prompt numbered as
+ * `U0`, `U1`, …, captured when the prompt was built.
+ *
+ * Message *objects*, not positions. The prompt is built in one task on the
+ * loop thread and its turn runs in a second one, and a user turn queued in
+ * between can `trimHistory()` from the front and shift every index. A
+ * reference cannot move: a turn is found again by identity when the fold is
+ * recorded and again when it is applied, and one that has been trimmed away
+ * is simply not found — a refusal rather than a splice into the wrong place.
+ */
+ private var shownTurns: List<JSONObject> = emptyList()
+
+ /**
+ * What a review asked to fold: the user turn that opens the stretch and the
+ * user turn that opens whatever came after it. The stretch is everything
+ * from the first up to, not including, the second. See [pendingFolds].
+ */
+ private data class PendingFold(
+ val first: JSONObject,
+ val next: JSONObject,
+ val title: String,
+ val summary: String,
+ val text: String,
+ )
+
/** Loop thread only. */
private val history = mutableListOf<JSONObject>()
@@ -319,11 +360,28 @@ class LocalBrain(
busy.get() -> Log.i(TAG, "sweep skipped: a turn is running")
history.size < MIN_MESSAGES_TO_REVIEW ->
Log.i(TAG, "sweep skipped: only ${history.size} messages to review")
- else -> launch(SWEEP_INSTRUCTION, TurnKind.SWEEP)
+ else -> launch(sweepInstruction(), TurnKind.SWEEP)
}
}
}
+ /**
+ * The quiet-hour prompt with this conversation's topic candidates folded in.
+ *
+ * Built here rather than kept as one constant because the candidate list is
+ * a fact about the history at this instant — and because it has to be the
+ * *same* list [noteFold] later indexes into. [topicCandidatesForPrompt]
+ * captures it as a side effect for exactly that reason; see [shownTurns].
+ *
+ * When there is nothing to offer, the whole section is left out. A review
+ * told to consider an empty list spends a step reasoning about nothing.
+ */
+ private fun sweepInstruction(): String {
+ val candidates = topicCandidatesForPrompt()
+ if (candidates.isEmpty()) return SWEEP_INSTRUCTION
+ return SWEEP_INSTRUCTION + TOPIC_RULES.format(candidates)
+ }
+
/** Read from any thread. The service asks before queueing a wake-up. */
fun isBusy(): Boolean = busy.get()
@@ -367,6 +425,13 @@ class LocalBrain(
BrainTrace.clearTurn()
busy.set(false)
dropUnfinishedHarvest(kind)
+ // After the turn, never during it — see [pendingFolds]. A fold
+ // that succeeded leaves one message where a stretch used to be,
+ // and the splice has to happen when nothing is holding an index
+ // into the old shape. Guarded on the generation like everything
+ // else: a cancelled turn's fold belongs to a conversation that
+ // is no longer the current one.
+ if (gen == generation.get()) applyPendingFolds() else pendingFolds.clear()
if (kind == TurnKind.SWEEP) onSweepSpent(turnTokens)
if (gen == generation.get()) {
drainWakes()
@@ -519,6 +584,10 @@ class LocalBrain(
// 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()
+ // And the conversations that have been put away. Same position, same
+ // reasoning as the three above; the fourth is that this one is about
+ // an ABSENCE — see the note where it is appended.
+ val topics = net.kuafuai.andee.ui.ChatHistory.topicsForPrompt()
// 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()
@@ -573,6 +642,23 @@ class LocalBrain(
"\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"
+ } +
+ // And the conversations that have been put away. The same
+ // position and the same reason as the other three, plus
+ // one of its own: what is NOT here is the point. A topic
+ // that was folded is gone from this conversation, so a
+ // model with no index answers 「上次那个比价」 from a
+ // one-line summary it half-remembers — or says it never
+ // happened. Seeing the title is what makes it go and read
+ // the real thing instead.
+ if (topics.isEmpty()) {
+ ""
+ } else {
+ "\n\n(conversations you have finished and put away; the newest " +
+ "few, `#id title (date · N msgs)`. These are NOT in front of you and the " +
+ "summary you may have of one is not the whole story — read it back with " +
+ "get_topic before answering about a detail, and never say it did not " +
+ "happen)\n$topics"
},
)
}
@@ -719,6 +805,22 @@ class LocalBrain(
tc.id,
"The arguments were not valid JSON, so I did not run it. Raw: ${tc.argumentsRaw.take(300)}",
)
+ // Folding is intercepted here rather than dispatched, and the reason
+ // is that it is the one `note.*` call whose subject is *this*
+ // object's state: it names a stretch of [history] and rewrites it,
+ // and the dispatcher has no history to name or rewrite. Handling it
+ // in [CommandDispatcher] would mean threading a reference to this
+ // brain through the service and back, to reach the two fields —
+ // [shownTurns] and [pendingFolds] — that only exist here.
+ //
+ // The gate comes with it: folding is for reviews only. A live turn
+ // must not fold, because folding is irreversible from the model's
+ // side and a user turn is not the moment to spend it. That check
+ // lives beside the state it protects rather than in the schema,
+ // which is static and cannot tell one turn kind from another.
+ if (ToolSchemas.methodOf(tc.name) == "note.fold" || tc.name == "note.fold") {
+ return toolMessage(tc.id, noteFold(args))
+ }
// Same two-name translation BodyWsClient does, and the same
// fallback: an extension registered its tool under one name and
// that name goes straight through to the dispatcher.
@@ -791,6 +893,241 @@ class LocalBrain(
.put("tool_call_id", id)
.put("content", content)
+ // ------------------------------------------------------------------
+ // topics: putting a finished stretch of conversation away
+ // ------------------------------------------------------------------
+
+ /**
+ * The user's turns, numbered, for the review prompt — or empty when there is
+ * nothing a fold could be made of.
+ *
+ * The numbers are the whole interface: the model names a first and a last
+ * turn and that is all it says about *where*. [shownTurns] is captured at
+ * the same instant so `U3` in the prompt and index 3 there are the same
+ * message. Long silences are marked between the lines as a hint — a person
+ * who walked away for an hour probably came back to something else — but a
+ * change of subject one minute later is just as foldable.
+ */
+ private fun topicCandidatesForPrompt(): String {
+ val idx = TopicSplitter.userTurns(history)
+ shownTurns = idx.map { history[it] }
+ // One turn has nothing after it, so nothing in it can be shown to be over.
+ if (idx.size < 2) return ""
+ val fmt = java.text.SimpleDateFormat("MM-dd HH:mm", java.util.Locale.US)
+ val sb = StringBuilder()
+ for ((n, i) in idx.withIndex()) {
+ val m = history[i]
+ if (n > 0 && TopicSplitter.isSeam(history[idx[n - 1]], m)) {
+ sb.append(" — a long silence here —\n")
+ }
+ val at = TopicSplitter.stampOf(m)
+ val said = TopicSplitter.anchorText(m).replace('\n', ' ').take(60)
+ sb.append("- U").append(n).append(" ")
+ .append(if (at > 0) fmt.format(java.util.Date(at)) else " ? ")
+ .append(" ").append(said)
+ if (n == idx.size - 1) sb.append(" (the latest — a topic must end before this)")
+ sb.append('\n')
+ }
+ return sb.toString().trimEnd()
+ }
+
+ /**
+ * Handle `note.fold`: a review saying "turns U[from]..U[to] were one topic,
+ * and it is over — put it away".
+ *
+ * Returns the JSON the model reads, and **every refusal says which gate it
+ * hit**. A review told "no" with no reason tries again next time with the
+ * same input and gets the same answer, and there is nobody watching to
+ * notice the loop.
+ *
+ * The gates are mechanical on purpose. `TOPIC_RULES` asks the model to judge
+ * whether a stretch has ended; these are the half that does not depend on it
+ * agreeing:
+ *
+ * 1. **Only the quiet-hour review may fold** — not a user turn, and not the
+ * harvest, which is silent too but is writing a summary, was never shown
+ * the turn list, and rewrites [history] itself.
+ * 2. **Both numbers come from the list shown**, and the stretch is then found
+ * in [history] by the identity of those messages, so nothing that moved
+ * the indices in between can point the fold at the wrong place.
+ * 3. **Some turn must come after it.** This is "another topic has started
+ * since" as arithmetic: the latest turn has nothing after it, so nothing
+ * shows that it ended. Without this the review would in time fold the
+ * conversation it is standing in.
+ * 4. **Nothing in it may be still waiting** — an unanswered tool call means
+ * the stretch was interrupted, not finished.
+ * 5. **It must not already be folded, in this review or an earlier one.**
+ * 6. **No scene may be active.** While the user is in a scene they are, by
+ * definition, doing one thing.
+ */
+ private fun noteFold(args: JSONObject): String {
+ fun no(reason: String) = JSONObject().put("folded", false).put("reason", reason).toString()
+ if (currentKind != TurnKind.SWEEP) {
+ return no("Only the quiet-hour review puts topics away; this turn is not one. Do not try again — just carry on.")
+ }
+ if (net.kuafuai.andee.config.VoiceConfig.activeScene(appContext) != null) {
+ return no("A scene is active, so this is all one piece of work. Nothing to fold.")
+ }
+ if (pendingFolds.size >= MAX_FOLDS_PER_REVIEW) {
+ return no("That is $MAX_FOLDS_PER_REVIEW topics for this review already. Leave the rest for next time.")
+ }
+ val a = args.optInt("from_turn", -1)
+ val b = args.optInt("to_turn", -1)
+ val last = shownTurns.size - 1
+ if (a !in 0..last || b !in 0..last) {
+ return no("U$a..U$b is not in the turn list you were given (U0..U$last). Use numbers from that list; do not invent one.")
+ }
+ if (b < a) return no("to_turn ($b) comes before from_turn ($a).")
+ if (b >= last) {
+ return no(
+ "U$b is the latest turn — nothing has started after it, so there is no way to tell this topic " +
+ "ended. A topic must end before the latest turn; leave it for a later review.",
+ )
+ }
+ val first = shownTurns[a]
+ val next = shownTurns[b + 1]
+ val from = history.indexOfFirst { it === first }
+ val until = history.indexOfFirst { it === next }
+ if (from < 1 || until <= from) {
+ return no("Those turns are no longer in the conversation, so there is nothing left to put away.")
+ }
+ if (history.subList(from, until).any { isFoldMarker(it) }) {
+ return no("Part of U$a..U$b was already put away in an earlier review. Fold only turns that are still here.")
+ }
+ val clash = pendingFolds.any { p ->
+ val pf = history.indexOfFirst { it === p.first }
+ val pu = history.indexOfFirst { it === p.next }
+ from < pu && pf < until
+ }
+ if (clash) return no("U$a..U$b overlaps a topic you already put away in this review.")
+ if (until - from < TopicSplitter.MIN_SEGMENT_MESSAGES) {
+ return no("U$a..U$b is too short to be worth putting away. Leave it.")
+ }
+ if (TopicSplitter.hasDanglingCall(history, from, until)) {
+ return no("Something in U$a..U$b is still waiting on an answer, so it was interrupted rather than finished. Leave it.")
+ }
+ val title = args.optString("title").trim()
+ val summary = args.optString("summary").trim()
+ if (title.isEmpty() || summary.isEmpty()) return no("A topic needs both a title and a summary.")
+ pendingFolds += PendingFold(
+ first = first,
+ next = next,
+ title = title,
+ summary = summary.take(MAX_TOPIC_SUMMARY_CHARS),
+ text = renderTopicText(history, from, until),
+ )
+ return JSONObject()
+ .put("folded", true)
+ .put("turns", "U$a..U$b")
+ .put("title", title)
+ .put("note", "It goes away when this review ends. Do not fold these turns again.")
+ .toString()
+ }
+
+ /** The one-line stand-in [applyPendingFolds] leaves where a topic was. */
+ private fun isFoldMarker(m: JSONObject): Boolean =
+ m.optString("role") == "assistant" &&
+ (m.opt("content") as? String)?.startsWith(FOLD_MARKER_PREFIX) == true
+
+ /** Every fold the review asked for, oldest request first. See [applyOneFold]. */
+ private fun applyPendingFolds() {
+ val folds = pendingFolds.toList()
+ pendingFolds.clear()
+ for (f in folds) applyOneFold(f)
+ shownTurns = emptyList()
+ }
+
+ /**
+ * Put away one stretch, and swap it in [history] for a marker that says
+ * where it went.
+ *
+ * Runs after the turn is over — see [pendingFolds]. The two halves are
+ * different jobs and both are needed:
+ *
+ * * **[ChatHistory.foldTopic]** is the device's record: it marks the rows so
+ * the conversation list collapses them, and writes the verbatim text to
+ * its own file so `get_topic` can read it back later.
+ * * **the swap here** is the context's saving: the stretch is the most
+ * expensive thing in the request and the least likely to be needed again,
+ * so it becomes one line saying what it was and how to get it back.
+ *
+ * Both ends are found again by identity. **Which device rows the stretch
+ * covers is anchored on the same two user sentences** — see
+ * [TopicSplitter.locateRows]; the clock only breaks ties, because the
+ * brain's `[now …]` is to the minute while a row's `ts` is milliseconds.
+ */
+ private fun applyOneFold(fold: PendingFold) {
+ val from = history.indexOfFirst { it === fold.first }
+ val until = history.indexOfFirst { it === fold.next }
+ if (from < 1 || until <= from) {
+ Log.w(TAG, "fold of 「${fold.title}」 finished with no live range; dropped")
+ return
+ }
+ val firstSaid = TopicSplitter.anchorText(fold.first)
+ val nextSaid = TopicSplitter.anchorText(fold.next)
+ val all = net.kuafuai.andee.ui.ChatHistory.snapshot()
+ val keys = all.map {
+ TopicSplitter.RowKey(
+ isUser = it.role == net.kuafuai.andee.ui.ChatHistory.Role.USER,
+ text = it.text,
+ ts = it.ts,
+ )
+ }
+ val range = TopicSplitter.locateRows(
+ keys,
+ firstSaid, TopicSplitter.stampOf(fold.first),
+ nextSaid, TopicSplitter.stampOf(fold.next),
+ )
+ val rows = range?.let { all.subList(it.first, it.last + 1) }.orEmpty()
+ if (rows.isEmpty() || rows.any { it.topicId != null }) {
+ Log.w(
+ TAG,
+ "fold of 「${fold.title}」 could not be matched to the device rows " +
+ "(first=${firstSaid.take(20)}, next=${nextSaid.take(20)}, rows=${rows.size}); kept as it was",
+ )
+ return
+ }
+ // Written first, and the swap happens only if it landed: a marker saying
+ // "you can read this back" over a topic that was never written is worse
+ // than not folding, because nothing will ever notice the difference.
+ val topic = runCatching {
+ net.kuafuai.andee.ui.ChatHistory.foldTopic(
+ title = fold.title,
+ summary = fold.summary,
+ rows = rows,
+ text = fold.text,
+ parentId = null,
+ )
+ }.getOrNull()
+ if (topic == null) {
+ Log.w(TAG, "fold produced no topic; the conversation is kept as it was")
+ return
+ }
+ val marker = JSONObject()
+ .put("role", "assistant")
+ .put(
+ "content",
+ "$FOLD_MARKER_PREFIX「${topic.title}」 (topic #${topic.id}). It is finished and has been put " +
+ "away; the back-and-forth is not in front of you any more. What it came to: " +
+ "${topic.summary} If you need the details, read it back with `get_topic` — do " +
+ "not answer about it from this summary alone, and do not say it never happened.)",
+ )
+ val saved = until - from
+ val kept = ArrayList<JSONObject>(history.size - saved + 1)
+ kept.addAll(history.subList(0, from))
+ kept.add(marker)
+ kept.addAll(history.subList(until, history.size))
+ history.clear()
+ history.addAll(kept)
+ // The image tracking lists hold references to messages that are gone —
+ // the same cleanup [applyHarvest] does, for the same reason: a stale
+ // entry would later make [trimImages] drop a live message.
+ imageMessages.retainAll { m -> history.any { it === m } }
+ photoMessages.retainAll { m -> history.any { it === m } }
+ if (internalFromIndex > until) internalFromIndex -= (saved - 1)
+ Log.i(TAG, "topic put away: 「${topic.title}」 — $saved msgs, ${rows.size} rows → 1 marker, history now ${history.size}")
+ }
+
// ------------------------------------------------------------------
// images
// ------------------------------------------------------------------
@@ -1155,6 +1492,8 @@ class LocalBrain(
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 == "get_topic" || toolName == "list_topics" ->
+ AppLocale.str(appContext, R.string.narrate_topics)
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)
@@ -1260,6 +1599,45 @@ class LocalBrain(
If this conversation genuinely produced nothing new, record nothing — ending empty-handed is allowed. Forcing one in just dirties the notebook."""
+ /**
+ * Putting finished topics away. Appended to the sweep only — a harvest
+ * already replaces what it folds, so it has nothing to add here.
+ *
+ * **The model marks the topics; the device only offers the places they
+ * can start and end** — the user's turns, numbered. A topic change one
+ * minute later is as foldable as one after an hour, which is what the
+ * gap-only version could not do and why it looked broken on the tablet.
+ *
+ * The latest turn can never be inside a fold, since nothing has started
+ * after it. Folding is therefore always a little behind the
+ * conversation, and that is the design rather than a delay to tune away.
+ * See [noteFold] for the mechanical half.
+ */
+ private const val TOPIC_RULES = """
+
+PUTTING FINISHED TOPICS AWAY — the user's turns in this conversation, numbered:
+%s
+
+A conversation often holds several topics: he had you build a timer, then asked about the weather, then about a trip.
+A topic that is clearly over is worth putting away: it stops costing room, and it can be read back word for word later.
+Decide where each topic begins and ends, and for each one that is finished call `fold_topic` with:
+- `from_turn` / `to_turn` — the first and the last U-number of that topic (inclusive). Use the numbers above;
+ everything you and the tools said in between goes with them.
+- `title` — what it was about, in his words where you have them. 「番茄钟」「三款扫地机器人比价」, not 「用户询问产品信息」.
+- `summary` — four short lines, and the last one is not optional:
+ What it was about / where it got to / how it ended / **what you have left out**.
+ The last line is the door: it tells future-you the summary is not the whole story, so a question about
+ a detail gets answered by reading it back with `get_topic` instead of from this paragraph.
+
+Fold a topic when:
+- the subject clearly CHANGED after it — a different request, not a follow-up to the same one
+ (「做个番茄钟」→「改好看点」 is ONE topic; 「做个番茄钟」→「今天天气怎么样」 is two);
+- and nothing in it is still hanging — an unanswered question, a request you did not finish.
+
+Never fold the latest turn: nothing has started after it, so you cannot tell it is over.
+When unsure whether something is finished, leave it — leaving it costs a little room, folding something live loses it.
+Up to three topics per review. If `fold_topic` refuses, the reason names the condition; do not retry the same numbers."""
+
/** The quiet-hour review. Fired by [Scheduler.armSweepIn]. */
private const val SWEEP_INSTRUCTION =
"(to yourself · this conversation has been quiet for a while, the user has probably gone)\n" +
@@ -1282,7 +1660,17 @@ If this conversation genuinely produced nothing new, record nothing — ending e
"write \"what future-you must know in order to take over\".\n" +
"Finish items 1-6 first, and write that summary last."
+ /** How long a topic summary may be. Long enough to carry "where it got to". */
+ private const val MAX_TOPIC_SUMMARY_CHARS = 1200
+
+ /** See [noteFold]: enough to tidy a long morning, few enough to read. */
+ private const val MAX_FOLDS_PER_REVIEW = 3
+
+ /** How the stand-in for a folded topic begins; see [isFoldMarker]. */
+ private const val FOLD_MARKER_PREFIX = "(earlier in this conversation — "
+
private const val DEFAULT_TOOL_TIMEOUT_MS = 60_000L
+
private const val TIMEOUT_SLACK_MS = 10_000L
}
}
diff --git a/app/src/main/java/net/kuafuai/andee/brain/TopicSplitter.kt b/app/src/main/java/net/kuafuai/andee/brain/TopicSplitter.kt
new file mode 100644
index 0000000..124b55d
--- /dev/null
+++ b/app/src/main/java/net/kuafuai/andee/brain/TopicSplitter.kt
@@ -0,0 +1,318 @@
+package net.kuafuai.andee.brain
+
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * Where a conversation *can* be cut into topics, **on the device**.
+ *
+ * The split between the two halves of topic-folding is the whole design: the
+ * model decides *which stretch is a finished topic*, and the device decides
+ * *what that stretch is made of*. The model never names a message range — it
+ * cannot count messages, and a range it invents can start inside a tool call,
+ * which the API answers with a 400. It names two numbers from a list this file
+ * builds: the user turns. Every cut lands on a user message, so no turn is ever
+ * cut in half.
+ *
+ * An earlier version cut only at long silences (≥ [GAP_MS]) and a change of day,
+ * and offered the model just those stretches. On the tablet that meant a person
+ * who made a timer and then asked about the weather a minute later had one
+ * stretch, nothing to fold, and a feature that looked broken. A change of
+ * subject is a judgement about content, and content is the model's job; the gap
+ * survives only as a hint printed in the list.
+ *
+ * Pure: no Android, no state, so the rules can be tested directly; see
+ * `TopicSplitterTest`.
+ */
+internal object TopicSplitter {
+
+ /**
+ * A silence at least this long is marked in the turn list as a likely seam.
+ * A hint for the model, never a cut by itself.
+ */
+ const val GAP_MS = 15 * 60_000L
+
+ /**
+ * Fewer messages than this is not worth folding: a two-message exchange
+ * folded into a summary saves nothing and costs the same call.
+ */
+ const val MIN_SEGMENT_MESSAGES = 4
+
+ /**
+ * Indices in [history] of the messages the user actually said, oldest first
+ * — the only places a topic may start or end.
+ *
+ * A user message counts only when it carries the device's `[now …]` stamp.
+ * The other `user`-role messages are the device talking (a page was closed, a
+ * meeting transcript arrived): they have no row of their own on the device,
+ * so the fold could not find them there, and they are not where a person
+ * changed the subject.
+ */
+ fun userTurns(history: List<JSONObject>): List<Int> =
+ (1 until history.size).filter {
+ isBoundary(history[it]) && (history[it].opt("content") as String).startsWith("[now ")
+ }
+
+ /** Whether a silence long enough to mark sits between two stamped messages. */
+ fun isSeam(prev: JSONObject, next: JSONObject): Boolean {
+ val a = stampOf(prev)
+ val b = stampOf(next)
+ if (a <= 0 || b <= 0) return false
+ return b - a >= GAP_MS || dayOf(a) != dayOf(b)
+ }
+
+ /**
+ * Whether [history] contains a message the brain asked a question into and
+ * never got an answer for — an unclosed tool call.
+ *
+ * A stretch is only foldable when nothing in it is still waiting. This is
+ * the mechanical half of "明确话题已经结束": a `tool_calls` with no matching
+ * `tool` result behind it means the turn was interrupted, and folding a
+ * stretch whose last act was an unanswered call would bury the one thing the
+ * next turn needs to see.
+ *
+ * Counted rather than paired, because the only two states that matter are
+ * "every call answered" and "not every call answered".
+ */
+ fun hasDanglingCall(history: List<JSONObject>, from: Int, until: Int): Boolean {
+ var open = 0
+ for (i in from.coerceAtLeast(0) until until.coerceAtMost(history.size)) {
+ val m = history[i]
+ when (m.optString("role")) {
+ "assistant" -> open += (m.optJSONArray("tool_calls")?.length() ?: 0)
+ "tool" -> open--
+ }
+ }
+ return open > 0
+ }
+
+ /**
+ * The `[now …]` clock out of a user message, or 0.
+ *
+ * The one place a wall-clock time exists in the history is that bracket —
+ * see [LocalBrain.stamp] — and **it is not in a fixed format**: the stamp is
+ * `yyyy-MM-dd EEE HH:mm` rendered in the *interface language*
+ * (`AppLocale.localeOf`), so a Chinese device writes `2026-10-15 周四 18:30`
+ * and an English one `2026-10-15 Thu 18:30`, and the weekday is three
+ * characters of whatever the locale says. Parsing it with one pattern is
+ * therefore wrong on half the installs, which is the kind of bug that only
+ * shows up as "topics never split" on someone else's tablet.
+ *
+ * So only the two locale-independent fields are read: the `yyyy-MM-dd` date
+ * and the `HH:mm` clock. Both are fixed-width and fixed-position, which makes
+ * the split mechanical; the weekday between them is skipped by index rather
+ * than understood.
+ */
+ fun stampOf(message: JSONObject): Long = stampOfText(message.opt("content") as? String)
+
+ fun stampOfText(text: String?): Long {
+ if (text.isNullOrEmpty()) return 0L
+ val open = text.indexOf("[now ")
+ if (open < 0) return 0L
+ val close = text.indexOf(']', open)
+ if (close < 0) return 0L
+ // `2026-10-15 周四 18:30` / `2026-10-15 Thu 18:30`, optionally followed
+ // by ` · ui-language zh`.
+ val body = text.substring(open + 5, close)
+ val date = body.substringBefore(' ').trim()
+ val d = DATE_RE.matchEntire(date) ?: return 0L
+ // The weekday sits between the date and the clock in every locale the
+ // stamp is rendered in; dropping the first token of the remainder gets
+ // past it without having to know what language it is in.
+ val clock = body.removePrefix(date).trim()
+ .substringAfter(' ', "")
+ .trim()
+ .substringBefore(" · ")
+ .trim()
+ if (clock.length != 5 || clock[2] != ':') return 0L
+ val cal = java.util.Calendar.getInstance()
+ cal.clear()
+ cal.set(
+ d.groupValues[1].toInt(),
+ d.groupValues[2].toInt() - 1,
+ d.groupValues[3].toInt(),
+ clock.substring(0, 2).toInt(),
+ clock.substring(3, 5).toInt(),
+ 0,
+ )
+ return cal.timeInMillis
+ }
+
+ private val DATE_RE = Regex("(\\d{4})-(\\d{2})-(\\d{2})")
+
+ private fun dayOf(stamp: Long): Int {
+ if (stamp <= 0) return -1
+ val cal = java.util.Calendar.getInstance()
+ cal.timeInMillis = stamp
+ return cal.get(java.util.Calendar.YEAR) * 1000 + cal.get(java.util.Calendar.DAY_OF_YEAR)
+ }
+
+ private fun isBoundary(msg: JSONObject): Boolean =
+ msg.optString("role") == "user" && msg.opt("content") is String
+
+ /**
+ * Opening words of every index section the device appends to a user message.
+ *
+ * Used by [anchorText] to cut them off. Kept in one place because a new
+ * section that forgets to register here would silently become part of an
+ * anchor and stop a fold from matching — a failure with no symptom until
+ * someone notices a conversation was never put away.
+ */
+ private val INDEX_MARKERS = listOf(
+ "(what your notebook holds",
+ "(scenes you can enter",
+ "(pages you have made",
+ "(conversations you have finished",
+ )
+
+ /**
+ * The words of a message with the device's own decorations stripped — the
+ * one thing the brain's history and the device's row list have in common.
+ *
+ * **Why a fold needs this at all.** The two records of one conversation
+ * share no id, no length and no clock: the brain's history carries tool
+ * traffic the device never saw, and its timestamp rides in the message text
+ * as `[now …]` rendered only to the minute while a row carries
+ * `System.currentTimeMillis()`. The first version of the fold matched them
+ * on those timestamps and silently found nothing, which is how it was found:
+ * the tool reported success and no conversation was ever put away. The text
+ * is the only field that means the same thing on both sides.
+ *
+ * Public and pure rather than private in `LocalBrain` so it can be tested;
+ * see `TopicAnchorTest` for the matching it exists to make possible.
+ */
+ fun anchorText(message: JSONObject): String = anchorText(message.opt("content") as? String)
+
+ fun anchorText(raw: String?): String =
+ spokenText(raw).lineSequence().firstOrNull { it.isNotBlank() }?.trim().orEmpty()
+
+ /**
+ * Everything the user said in a message, with the device's decorations — the
+ * `[now …]` stamp and the index sections appended after the words — removed.
+ * Unlike [anchorText] it keeps every line; it is what a folded topic keeps.
+ */
+ fun spokenText(raw: String?): String {
+ if (raw.isNullOrEmpty()) return ""
+ var t: String = raw.trim()
+ if (t.startsWith("[now ")) {
+ val close = t.indexOf(']')
+ if (close >= 0) t = t.substring(close + 1)
+ }
+ // Everything from the first index section on is ours, not theirs.
+ for (marker in INDEX_MARKERS) {
+ val i = t.indexOf(marker)
+ if (i >= 0) t = t.substring(0, i)
+ }
+ return t.trim()
+ }
+
+ /**
+ * What the matcher needs of a device row, and nothing more — kept apart from
+ * `ChatHistory.Entry` so [locateRows] stays pure and testable.
+ */
+ data class RowKey(val isUser: Boolean, val text: String, val ts: Long)
+
+ /**
+ * How far a row's clock may sit from the `[now …]` of the message it
+ * corresponds to. The stamp is floored to the minute and is taken a little
+ * after the row was written, so exact equality can never hold; five minutes
+ * is generous for that and still far below [GAP_MS], so two neighbouring
+ * stretches cannot be mistaken for each other.
+ */
+ const val MATCH_TOLERANCE_MS = 5 * 60_000L
+
+ private const val ANCHOR_LEN = 40
+
+ /**
+ * Which device rows a stretch of the brain's history covers, as an index
+ * range into [rows] — or null when it cannot be said with confidence.
+ *
+ * **Only the two *user* messages that bound the stretch are looked up:** the
+ * one that opens it ([firstSaid]) and the one that opens the stretch after
+ * it ([nextSaid]). Everything between them is the stretch. That is the whole
+ * trick, and the reason it is not "first message to last message": the last
+ * thing said in a stretch is usually the assistant's 「好的。」, a sentence
+ * that occurs all over a conversation. Searching for it matches the final
+ * one anywhere — in later stretches, in the one still going — and the fold
+ * would mark live rows as belonging to the topic. A user sentence is far
+ * more distinctive, and a pair of them bracketing the span leaves nothing to
+ * search for in the middle.
+ *
+ * A user sentence can still repeat (「继续」, 「好的」), so ties are broken by
+ * the clock: the row nearest the stamp, within [MATCH_TOLERANCE_MS]. With no
+ * clock to go on ([firstAt]/[nextAt] ≤ 0, e.g. an unstamped note) the match
+ * is accepted only when it is unique.
+ *
+ * Null is the safe answer and the caller treats it as "leave the
+ * conversation as it was". A wrong range is not recoverable by anyone.
+ */
+ fun locateRows(
+ rows: List<RowKey>,
+ firstSaid: String,
+ firstAt: Long,
+ nextSaid: String,
+ nextAt: Long,
+ ): IntRange? {
+ val start = pickUserRow(rows, firstSaid, firstAt, 0) ?: return null
+ val next = pickUserRow(rows, nextSaid, nextAt, start + 1) ?: return null
+ val end = next - 1
+ return if (end >= start) start..end else null
+ }
+
+ private fun pickUserRow(rows: List<RowKey>, said: String, at: Long, from: Int): Int? {
+ if (said.isEmpty()) return null
+ val head = said.take(ANCHOR_LEN)
+ val hits = (from until rows.size).filter { rows[it].isUser && rows[it].text.startsWith(head) }
+ if (hits.isEmpty()) return null
+ if (at <= 0) return hits.singleOrNull()
+ val best = hits.minByOrNull { kotlin.math.abs(rows[it].ts - at) } ?: return null
+ return if (kotlin.math.abs(rows[best].ts - at) <= MATCH_TOLERANCE_MS) best else null
+ }
+}
+
+/**
+ * Render [from] until [until] of a history as the text a topic keeps.
+ *
+ * Plain and complete on purpose: this is what `get_topic` hands back when the
+ * user returns to a finished conversation, so it carries the words and nothing
+ * else — no tool call ids, no JSON, no role prefixes the reader would have to
+ * skip past. Tool traffic is summarised as a bracketed line because "it looked
+ * something up here" is worth knowing and the arguments are not: they are
+ * device chatter, and a screenshot payload inside a folded topic would be a
+ * megabyte of base64 with the user's sentence nowhere in it.
+ */
+internal fun renderTopicText(history: List<JSONObject>, from: Int, until: Int): String {
+ val sb = StringBuilder()
+ for (i in from.coerceAtLeast(0) until until.coerceAtMost(history.size)) {
+ val m = history[i]
+ when (m.optString("role")) {
+ "user" -> sb.append("我:").append(TopicSplitter.spokenText(m.opt("content") as? String)).append('\n')
+ "assistant" -> {
+ val text = m.opt("content") as? String
+ if (!text.isNullOrBlank()) sb.append("他:").append(text.trim()).append('\n')
+ val calls = m.optJSONArray("tool_calls")
+ if (calls != null && calls.length() > 0) {
+ val names = (0 until calls.length()).mapNotNull {
+ calls.optJSONObject(it)?.optJSONObject("function")?.optString("name")
+ }.filter { it.isNotBlank() }
+ if (names.isNotEmpty()) sb.append("(用了:").append(names.joinToString("、")).append(")\n")
+ }
+ }
+ "tool" -> {
+ // Deliberately not the content: a tool result may be a base64
+ // image or 24 000 characters of screen dump.
+ val c = m.opt("content")
+ val len = when (c) {
+ is String -> c.length
+ is JSONArray -> (0 until c.length()).sumOf { k ->
+ c.optJSONObject(k)?.optString("text")?.length ?: 0
+ }
+ else -> 0
+ }
+ if (len > 0) sb.append("(工具返回 ").append(len).append(" 字)\n")
+ }
+ }
+ sb.append('\n')
+ }
+ return sb.toString().trim()
+}
diff --git a/app/src/main/java/net/kuafuai/andee/net/BodyWsServer.kt b/app/src/main/java/net/kuafuai/andee/net/BodyWsServer.kt
index 5d6ce7f..4ec548d 100644
--- a/app/src/main/java/net/kuafuai/andee/net/BodyWsServer.kt
+++ b/app/src/main/java/net/kuafuai/andee/net/BodyWsServer.kt
@@ -67,6 +67,21 @@ class BodyWsServer(
* API key.
*/
private val onSay: (text: String) -> Unit = {},
+
+ /**
+ * `debug.sweep` — run the quiet-hour review now instead of waiting out the
+ * silence timer. Loopback only, like [onSay].
+ *
+ * Goes through `BodyCoreService.onSweepTimer`, so every gate the timer
+ * applies still applies (silence, the daily budget, a running turn) and what
+ * gets exercised is the real path. `onSweepForced` is the same thing with
+ * the silence requirement lifted, for driving a test with the conversation
+ * still warm.
+ */
+ private val onSweep: () -> Unit = {},
+
+ /** `debug.sweep {"skip":true}` — the review with the silence gate bypassed. */
+ private val onSweepForced: () -> Unit = {},
) : WebSocketServer(InetSocketAddress(bindHost, port)) {
/** Driver connections only — the ones broadcasts go to. Extensions never join. */
@@ -135,6 +150,27 @@ class BodyWsServer(
require(text.isNotEmpty()) { "debug.say needs {\"text\": …}" }
onSay(text)
JSONObject().put("submitted", text)
+ } else if (method == "debug.sweep") {
+ // The quiet-hour review, on demand. Same reason as
+ // [onSay] and the same loopback rule: the review fires off
+ // an AlarmManager timer twenty minutes after the user stops
+ // talking, which makes "did that path work" a twenty-minute
+ // question every time. This is the same call the alarm
+ // makes, so what it exercises is the real thing rather than
+ // a rehearsal — the gates inside `onSweepTimer` still apply,
+ // including the silence check, and `skip` is there for the
+ // case where the caller is deliberately testing the path
+ // with the conversation still warm.
+ if (conn.remoteSocketAddress?.address?.isLoopbackAddress != true) {
+ throw IllegalStateException("debug.sweep is loopback only — use adb forward")
+ }
+ if (params?.optBoolean("skip", false) == true) {
+ onSweepForced()
+ JSONObject().put("started", true).put("forced", true)
+ } else {
+ onSweep()
+ JSONObject().put("started", true).put("forced", false)
+ }
} else {
onCommand(method, params)
}
diff --git a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
index 0c3ad9a..603df25 100644
--- a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
+++ b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
@@ -1055,6 +1055,100 @@ class CommandDispatcher(
}
}
+ // ---- ui.* : the finished conversations, read back ---------------
+ //
+ // The shelf the folded topics are on. Like the page readers above,
+ // these are deliberately outside the `screen.` prefix — reading a
+ // file neither folds the card nor is worth blocking at a lock
+ // screen — and like them they draw nothing.
+ "ui.list_topics" -> {
+ val arr = org.json.JSONArray()
+ for (t in net.kuafuai.andee.ui.ChatHistory.topics()) {
+ arr.put(
+ JSONObject()
+ .put("id", t.id)
+ .put("title", t.title)
+ .put("ended", Scheduler.formatLocal(t.endedAt))
+ .put("messages", net.kuafuai.andee.ui.ChatHistory.rowCountOf(t.id))
+ .put("available", net.kuafuai.andee.ui.ChatHistory.topicText(t.id) != null),
+ )
+ }
+ JSONObject()
+ .put("items", arr)
+ .put("count", arr.length())
+ .put(
+ "note",
+ when {
+ arr.length() == 0 ->
+ "No conversations have been put away yet. Nothing is missing — " +
+ "everything you have done together is either in front of you or " +
+ "was never folded."
+ else ->
+ "Newest first. These are FINISHED conversations, put away to save room; " +
+ "the one-line summary in your context is not the whole story. Read " +
+ "one back with get_topic before answering a question about a detail."
+ },
+ )
+ }
+
+ "ui.get_topic" -> {
+ val id = params?.optLong("id", Long.MIN_VALUE)?.takeIf { it != Long.MIN_VALUE }
+ ?: throw IllegalArgumentException(
+ "ui.get_topic requires integer id, from list_topics",
+ )
+ val topic = net.kuafuai.andee.ui.ChatHistory.topicById(id)
+ val text = net.kuafuai.andee.ui.ChatHistory.topicText(id)
+ when {
+ // Three failures, and they are different: an id that names
+ // nothing (invented, or the list is stale), a topic whose file
+ // is gone, and a topic that exists but was never written. Each
+ // gets its own sentence because the honest next move differs.
+ 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 from the summary " +
+ "or from impression.",
+ )
+
+ else -> {
+ val cut = text.length > net.kuafuai.andee.ui.ChatHistory.TOPIC_TEXT_MAX
+ JSONObject()
+ .put("found", true)
+ .put("id", topic.id)
+ .put("title", topic.title)
+ .put("ended", Scheduler.formatLocal(topic.endedAt))
+ .put("truncated", cut)
+ .put(
+ "text",
+ if (cut) text.take(net.kuafuai.andee.ui.ChatHistory.TOPIC_TEXT_MAX) else text,
+ )
+ .put(
+ "note",
+ "The conversation as it happened. This call showed the user nothing." +
+ if (cut) {
+ " Cut at ${net.kuafuai.andee.ui.ChatHistory.TOPIC_TEXT_MAX} " +
+ "characters — what you have is the beginning; say so if the " +
+ "answer is not in it."
+ } 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.kt
index db52d46..0cf0cf6 100644
--- a/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt
+++ b/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt
@@ -1589,6 +1589,85 @@ object ToolSchemas {
"filter" to propEnum("Used with list", listOf("pending", "all", "cron")),
),
),
+ tool(
+ localOnly = true,
+ name = "fold_topic",
+ method = "note.fold",
+ description = """
+ Put a finished topic of this conversation away, so it stops costing context and can be read
+ back later with `get_topic`.
+
+ **Reviews only.** This is offered to the quiet-hour review, and any other turn that calls it is
+ refused — folding is irreversible from your side, and a request is not the moment to spend it.
+ The review's prompt lists the user's turns as U0, U1, …; a normal turn has no such list.
+
+ - `from_turn` / `to_turn`: the first and last U-number of the topic, inclusive, from that list.
+ **Use those numbers.** Do not describe a range of messages and do not count them — everything
+ said between those two turns, yours and the tools', goes with them.
+ - `title`: what it was about, in the user's words where you have them.
+ - `summary`: what it was about / where it got to / how it ended / **what you left out**.
+ The last line is the point. It is what tells future-you that this paragraph is not the whole
+ story, so a question about a detail gets answered by reading the topic back instead of from
+ memory. A summary that reads complete is one whose details are lost.
+
+ The device refuses, with a reason, when: a number is not in the list; `to_turn` is the latest
+ turn (nothing has started after it, so there is no way to tell it ended); something in it is
+ still waiting on an answer; it overlaps a topic already put away; it is too short; or a scene is
+ active. The reason names the condition — do not retry the same numbers.
+
+ Up to three topics per review. They are put away when the review ends, not when you call this.
+ """.trimIndent(),
+ required = listOf("from_turn", "to_turn", "title", "summary"),
+ props = mapOf(
+ "from_turn" to prop("integer", "The U-number of the topic's first turn"),
+ "to_turn" to prop("integer", "The U-number of the topic's last turn; must come before the latest turn"),
+ "title" to prop("string", "What this was about, ≤40 characters"),
+ "summary" to prop("string", "Four lines: what it was / where it got to / how it ended / what you left out"),
+ ),
+ ),
+ tool(
+ localOnly = true,
+ name = "list_topics",
+ method = "ui.list_topics",
+ description = """
+ The conversations that have been finished and put away, newest first.
+
+ A topic is a stretch of talking that ended — not a page (see `list_pages`) and not a way of
+ working (see `list_scenes`). When the user refers to something you did together earlier
+ (「上次那个比价」「我们之前聊的那个」) and it is not in the conversation in front of you, it is
+ probably here: it was folded away to save context, and one line of it is all that is left
+ in front of you.
+
+ Each entry carries the id, the title, when it ended, and how many messages it covers.
+ Use `get_topic` to read one back — **do not answer a question about a folded topic from its
+ one-line summary alone**, and never say it did not happen.
+ """.trimIndent(),
+ required = emptyList(),
+ props = emptyMap<String, JSONObject>(),
+ ),
+ tool(
+ localOnly = true,
+ name = "get_topic",
+ method = "ui.get_topic",
+ description = """
+ Read a folded conversation back, in full, by the id from `list_topics`.
+
+ This is the door out of a summary. A summary says what a topic came to and what it left out;
+ when the user asks about a detail — "which model was cheapest", "what did I say about the
+ budget" — that detail is here and not in the summary. Read it rather than guessing, and
+ rather than telling them it is no longer available.
+
+ The whole back-and-forth comes back as plain text, which may be long. Past
+ ${net.kuafuai.andee.ui.ChatHistory.TOPIC_TEXT_MAX} characters it is cut and `truncated` says so.
+
+ Reading is not showing: nothing appears on screen. If the user should see the conversation,
+ write it into a page with `show_html`.
+ """.trimIndent(),
+ required = listOf("id"),
+ props = mapOf(
+ "id" to prop("integer", "A topic id from list_topics. Do not make one up."),
+ ),
+ ),
// ------------------------------------------------------------------
// Scenes — `scene.*`, localOnly.
diff --git a/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt b/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt
index 699e82c..5b80b8e 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/ChatHistory.kt
@@ -63,6 +63,11 @@ object ChatHistory {
* @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.
+ * @param topicId the topic this row has been folded into, or null while it
+ * still stands on its own. Set only by [foldTopic]; the conversation list
+ * reads it to decide what to collapse. Orthogonal to [groupId]: a page
+ * drawn while talking about something belongs both to its own artifact
+ * and to that conversation.
*/
data class Entry(
val id: Long,
@@ -73,6 +78,42 @@ object ChatHistory {
val turn: String? = null,
val groupId: Long = id,
val version: Int = 1,
+ val topicId: Long? = null,
+ )
+
+ /**
+ * A stretch of conversation that has finished and been put away.
+ *
+ * **The other half of the 产物 idea, on the time axis.** An artifact groups
+ * the revisions of one *thing*; a topic groups a stretch of *talking*. They
+ * are orthogonal on purpose — a page drawn while planning a trip belongs to
+ * its own artifact and to that conversation at once.
+ *
+ * The point of folding is the context window, not tidiness: a finished
+ * conversation is the most expensive thing in the request and the least
+ * likely to be needed again, so it is replaced by [summary] and the brain
+ * reads the whole thing back with `get_topic` when the user actually
+ * returns to it. `artifact`'s `get_page` is the same trade.
+ *
+ * @param summary what the brain wrote when it folded: where it got to, what
+ * was left, and **what was left out** — that last part is what keeps the
+ * read-back door in use instead of merely available. See `TOPIC_RULES`.
+ * @param startedAt/[endedAt] the stretch this covers, which is also how the
+ * conversation list decides which rows to collapse.
+ * @param parentId the topic this one continues, or null. Continuing a
+ * finished topic starts a *new* one rather than reopening it — a topic
+ * that has ended is a fact about the past, and a chain ("we went back to
+ * the price comparison three times") reads better as three than as one
+ * endless thread.
+ */
+ data class Topic(
+ val id: Long,
+ val title: String,
+ val summary: String,
+ val startedAt: Long,
+ val endedAt: Long,
+ val createdAt: Long,
+ val parentId: Long? = null,
)
/**
@@ -117,6 +158,41 @@ object ChatHistory {
private val entries = ArrayList<Entry>()
private var nextId = 1L
+ /**
+ * Folded conversations, oldest first.
+ *
+ * Held here rather than in the notebook, and deliberately **not** encrypted:
+ * a topic points at a stretch of [entries], the rows it covers live in this
+ * file, and splitting the two across two stores would guarantee they drift
+ * — the same reasoning that put the artifact `group`/`version` keys in this
+ * file. The text a topic folds is the plaintext conversation that was
+ * already here, so a second layer over the copy would protect nothing the
+ * original did not already expose.
+ */
+ private val topics = ArrayList<Topic>()
+ private var nextTopicId = 1L
+
+ /**
+ * A folded stretch's conversation, verbatim, as the brain will read it back.
+ *
+ * **A snapshot in its own file, not a reference to row ids.** The rows it was
+ * folded from are ordinary [entries] and are subject to [MAX_ENTRIES] — the
+ * oldest are dropped as the conversation grows. Reconstructing the text from
+ * ids would therefore work right up until the day it silently returned half a
+ * conversation, which is the worst possible failure for the feature the
+ * read-back door exists to serve. The file is the record; the rows in the
+ * list are the *view* of it.
+ *
+ * **`files/topics/topic_<id>.txt`, exactly like `files/pages/page_<id>.html`.**
+ * It was briefly going to live inside `chat_history.json` with the rest, and
+ * that was wrong for a measurable reason: that file is rewritten in full on
+ * *every* append, and a folded conversation can be a few hundred KB. One big
+ * blob per topic, written once when it folds and read only when someone asks
+ * for it, is the shape that was already proven here for generated pages.
+ */
+ private fun topicFile(id: Long): File? =
+ appContext?.let { File(File(it.filesDir, "topics").apply { mkdirs() }, "topic_$id.txt") }
+
/** Notified on every change; the card re-reads [snapshot] and redraws. */
@Volatile
private var listener: (() -> Unit)? = null
@@ -265,6 +341,138 @@ object ChatHistory {
collapseToArtifacts(entries, keepMissing = true)
}
+ // ---- topics: finished stretches of conversation ----
+
+ /** How much of a folded conversation `get_topic` hands over in one go. */
+ const val TOPIC_TEXT_MAX = 40_000
+
+ /** How many folded conversations are kept. Oldest files go first. */
+ private const val MAX_TOPICS = 60
+
+ /** Every folded topic, **newest first** — how `list_topics` and the panel read them. */
+ fun topics(): List<Topic> = synchronized(lock) { topics.sortedByDescending { it.endedAt } }
+
+ /** One topic by id, or null. */
+ fun topicById(id: Long): Topic? = synchronized(lock) { topics.firstOrNull { it.id == id } }
+
+ /**
+ * The verbatim conversation a topic covers, or null when its file is gone.
+ *
+ * Never throws and never guesses: a missing file is reported as missing, the
+ * same way `get_page` reports a page whose bytes the 100-page cap took.
+ * Reconstructing it from the rows still in the list would be worse than
+ * failing — it would hand back a plausible, partial conversation.
+ */
+ fun topicText(id: Long): String? =
+ topicFile(id)?.takeIf { it.exists() }?.let { f -> runCatching { f.readText() }.getOrNull() }
+
+ /**
+ * How many rows carry [topicId] — what the conversation list collapses.
+ *
+ * Read off the live rows rather than stored on the topic, because rows are
+ * dropped by [MAX_ENTRIES] as the conversation grows and a stored count
+ * would drift away from what is actually on screen.
+ */
+ fun rowCountOf(topicId: Long): Int = synchronized(lock) {
+ entries.count { it.topicId == topicId }
+ }
+
+ /** Rows belonging to one topic, oldest first. */
+ fun rowsOf(topicId: Long): List<Entry> = synchronized(lock) {
+ entries.filter { it.topicId == topicId }
+ }
+
+ /**
+ * The artifacts made during a topic, one per artifact, newest first — the
+ * topic card's 产出物 list.
+ *
+ * Each is the artifact's **current** version, wherever it was made: a page
+ * started in this topic and revised later is still this topic's output, and
+ * reopening the version from back then would show the user something they
+ * have since changed. Only artifacts with a file left are listed — a row that
+ * offers to open nothing is worse than a shorter list.
+ */
+ fun outputsOf(topicId: Long): List<Entry> = synchronized(lock) {
+ val groups = entries.filter { it.topicId == topicId && it.role == Role.PAGE }.map { it.groupId }.toSet()
+ collapseToArtifacts(entries.filter { it.groupId in groups }, keepMissing = false)
+ }
+
+ /**
+ * Put a finished stretch of conversation away.
+ *
+ * Marks the rows with [Topic.id] (which is what makes the list collapse
+ * them, and is why the rows are not deleted — the user still scrolls past
+ * "we talked about this at 3pm") and writes the conversation to its own file
+ * so `get_topic` can read it back verbatim later.
+ *
+ * **@param rows the entries this covers, oldest first**, already decided by
+ * the caller — the device decides *which* rows, the model only decided
+ * that the stretch had ended. See the topic-folding notes on
+ * `note.fold`.
+ * **@param text the conversation verbatim**, as the brain will read it
+ * back. Passed in rather than rebuilt from [rows] because the brain's own
+ * history is the real one — the rows here are the device's summary view of
+ * it, with each message already capped at [MAX_TEXT].
+ *
+ * Returns the new topic, or null when there is nothing to fold.
+ */
+ fun foldTopic(
+ title: String,
+ summary: String,
+ rows: List<Entry>,
+ text: String,
+ parentId: Long? = null,
+ ): Topic? {
+ if (rows.isEmpty()) return null
+ val ctx = appContext ?: return null
+ val now = System.currentTimeMillis()
+ val topic = synchronized(lock) {
+ val id = nextTopicId++
+ runCatching {
+ val dir = File(ctx.filesDir, "topics").apply { mkdirs() }
+ File(dir, "topic_$id.txt").writeText(text)
+ }.onFailure {
+ Log.w(TAG, "history: could not archive topic: ${it.message}")
+ return null
+ }
+ val t = Topic(
+ id = id,
+ title = title.trim().ifEmpty { rows.first().text.take(40) },
+ summary = summary.trim(),
+ startedAt = rows.first().ts,
+ endedAt = rows.last().ts,
+ createdAt = now,
+ parentId = parentId,
+ )
+ topics.add(t)
+ // Stamp the rows so the list collapses them and the panel can count.
+ val ids = rows.map { it.id }.toSet()
+ for (i in entries.indices) {
+ if (entries[i].id in ids) entries[i] = entries[i].copy(topicId = id)
+ }
+ evictTopics()
+ save()
+ t
+ }
+ listener?.invoke()
+ return topic
+ }
+
+ /** Caller holds [lock]. Oldest topics — and their files — go first. */
+ private fun evictTopics() {
+ while (topics.size > MAX_TOPICS) {
+ val gone = topics.minByOrNull { it.endedAt } ?: return
+ topics.remove(gone)
+ topicFile(gone.id)?.let { runCatching { it.delete() } }
+ // Its rows stay, but they are no longer covered by anything — read
+ // as "never folded" rather than as a topic id that resolves to
+ // nothing, which the list would render as an empty collapse.
+ for (i in entries.indices) {
+ if (entries[i].topicId == gone.id) entries[i] = entries[i].copy(topicId = null)
+ }
+ }
+ }
+
/**
* One line per recent artifact for the per-turn user message; empty when
* there are none.
@@ -318,6 +526,29 @@ object ChatHistory {
entries.firstOrNull { it.id == id && it.role == Role.PAGE }
}
+ /**
+ * One line per recent topic for the per-turn user message; empty when there
+ * are none.
+ *
+ * Same position and same reason as [indexForPrompt]: this list changes the
+ * moment anything folds, and the system prompt is the one place it must never
+ * go. `list_topics` has the full list; this is the newest few, and its whole
+ * job is to make the shelf *visible* — 「上次那个比价」 answered from memory
+ * is the failure, and a model that can see the topic knows to read it back.
+ *
+ * The counts are printed for the reason the version is printed on a page: it
+ * tells the model how much is behind the door before it decides to open it.
+ */
+ fun topicsForPrompt(max: Int = 5): String {
+ val recent = topics().take(max)
+ if (recent.isEmpty()) return ""
+ val fmt = SimpleDateFormat("MM-dd HH:mm", Locale.US)
+ return recent.joinToString("\n") { t ->
+ val rows = rowCountOf(t.id)
+ "- #${t.id} ${t.title} (${fmt.format(Date(t.endedAt))} · $rows msgs)"
+ }
+ }
+
/**
* How much of a page's source is handed to the brain in one go.
*
@@ -379,11 +610,17 @@ object ChatHistory {
fun wipe(context: Context) {
synchronized(lock) {
entries.clear()
+ topics.clear()
nextId = 1L
+ nextTopicId = 1L
}
runCatching {
File(context.filesDir, "chat_history.json").delete()
File(context.filesDir, "pages").deleteRecursively()
+ // Under the same lock and the same call as the rows: a topic file
+ // that outlived a factory reset would be a conversation the user
+ // asked to be rid of, sitting on disk with nothing pointing at it.
+ File(context.filesDir, "topics").deleteRecursively()
}.onFailure { Log.w(TAG, "history: wipe failed: ${it.message}") }
listener?.invoke()
}
@@ -556,6 +793,18 @@ object ChatHistory {
private fun file(): File? = appContext?.let { File(it.filesDir, "chat_history.json") }
+ /**
+ * The shape on disk.
+ *
+ * It used to be a bare array of rows. It is an object with `entries` and
+ * `topics` now, because a topic is not a row and cannot be expressed as one
+ * — but **the bare-array form is still read** ([load] sniffs which it has),
+ * so a device updating from a build that predates topics opens its
+ * conversation instead of an empty one.
+ */
+ private const val KEY_ENTRIES = "entries"
+ private const val KEY_TOPICS = "topics"
+
/** Caller holds [lock]. */
private fun save() {
val f = file() ?: return
@@ -572,9 +821,23 @@ object ChatHistory {
.put("turn", e.turn ?: JSONObject.NULL)
.put("group", e.groupId)
.put("version", e.version)
+ .put("topic", e.topicId ?: JSONObject.NULL)
+ )
+ }
+ val tarr = JSONArray()
+ for (t in topics) {
+ tarr.put(
+ JSONObject()
+ .put("id", t.id)
+ .put("title", t.title)
+ .put("summary", t.summary)
+ .put("started", t.startedAt)
+ .put("ended", t.endedAt)
+ .put("created", t.createdAt)
+ .put("parent", t.parentId ?: JSONObject.NULL)
)
}
- f.writeText(arr.toString())
+ f.writeText(JSONObject().put(KEY_ENTRIES, arr).put(KEY_TOPICS, tarr).toString())
}.onFailure { Log.w(TAG, "history: save failed: ${it.message}") }
}
@@ -584,7 +847,15 @@ object ChatHistory {
if (!f.exists()) return
runCatching {
val dir = File(appContext!!.filesDir, "pages")
- val arr = JSONArray(f.readText())
+ val raw = f.readText().trim()
+ // Two shapes on disk: the bare array everything up to the topics
+ // change wrote, and the `{entries, topics}` object written since.
+ // Sniffed rather than versioned — a device that has never folded
+ // anything has no topics to lose, and rewriting every existing file
+ // just to add an empty list would be a migration for nobody.
+ val bare = if (raw.startsWith("[")) JSONArray(raw) else null
+ val root = if (bare == null) JSONObject(raw) else null
+ val arr = bare ?: root!!.optJSONArray(KEY_ENTRIES) ?: JSONArray()
for (i in 0 until arr.length()) {
val o = arr.optJSONObject(i) ?: continue
val role = runCatching { Role.valueOf(o.optString("role")) }.getOrNull() ?: continue
@@ -607,14 +878,49 @@ object ChatHistory {
// 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
+ // Null and absent are the same thing here and both mean "not
+ // folded", so there is no default to get wrong.
+ val topic = if (o.has("topic")) o.optLong("topic", -1L).takeIf { it > 0 } else null
entries.add(
- Entry(id, o.optLong("ts"), role, o.optString("text"), page, turn, group, version),
+ Entry(
+ id, o.optLong("ts"), role, o.optString("text"), page, turn,
+ group, version, topic,
+ ),
)
if (id >= nextId) nextId = id + 1
}
+ val tarr = root?.optJSONArray(KEY_TOPICS) ?: JSONArray()
+ for (i in 0 until tarr.length()) {
+ val o = tarr.optJSONObject(i) ?: continue
+ val tid = o.optLong("id")
+ if (tid <= 0) continue
+ topics.add(
+ Topic(
+ id = tid,
+ title = o.optString("title"),
+ summary = o.optString("summary"),
+ startedAt = o.optLong("started"),
+ endedAt = o.optLong("ended"),
+ createdAt = o.optLong("created"),
+ parentId = if (o.has("parent")) o.optLong("parent", -1L).takeIf { it > 0 } else null,
+ ),
+ )
+ if (tid >= nextTopicId) nextTopicId = tid + 1
+ }
+ // A row may name a topic that is no longer on the list — its file
+ // was deleted, or it was evicted. Clear it here, at load, so the
+ // list never collapses around a heading it cannot draw. Skipping
+ // this would leave a stale id on disk forever, and every open would
+ // have to re-decide the same thing.
+ val live = topics.map { it.id }.toSet()
+ for (i in entries.indices) {
+ val t = entries[i].topicId
+ if (t != null && t !in live) entries[i] = entries[i].copy(topicId = null)
+ }
}.onFailure {
Log.w(TAG, "history: load failed, starting empty: ${it.message}")
entries.clear()
+ topics.clear()
}
}
}
diff --git a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt
index 6663f01..c1759f5 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt
@@ -253,6 +253,18 @@ class FloatingWindowUi(
* name one thing and send another.
*/
fun onSuggestionClick(name: String, title: String, example: String)
+
+ /**
+ * 继续话题 on a folded topic's card. Handed out because it starts a turn,
+ * and a turn has one way in — see [onSuggestionClick].
+ */
+ fun onTopicContinue(topic: ChatHistory.Topic)
+
+ /**
+ * 对话记录 on a folded topic's card: the conversation, fullscreen. Handed
+ * out for the same reason as [onTextOpen] — the card folds first.
+ */
+ fun onTopicTranscript(topic: ChatHistory.Topic)
}
private val wm: WindowManager =
@@ -2318,6 +2330,8 @@ class FloatingWindowUi(
onSuggestionClick = { name, title, example ->
listeners.onSuggestionClick(name, title, example)
}
+ onTopicContinue = { listeners.onTopicContinue(it) }
+ onTopicTranscript = { listeners.onTopicTranscript(it) }
}
historyView = history
root.addView(
diff --git a/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt b/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt
index ef82072..1e4c76e 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/HistoryListView.kt
@@ -99,6 +99,15 @@ class HistoryListView(private val context: Context) : ScrollView(context) {
*/
var onSuggestionClick: ((name: String, title: String, example: String) -> Unit)? = null
+ /**
+ * 继续话题 on a topic card. A turn — so, like a suggestion, it is handed out:
+ * only the service starts turns. See `BodyCoreService.beginTopicContinue`.
+ */
+ var onTopicContinue: ((ChatHistory.Topic) -> Unit)? = null
+
+ /** 对话记录 on a topic card — a fullscreen page, so the card folds first. */
+ var onTopicTranscript: ((ChatHistory.Topic) -> Unit)? = null
+
/**
* The rows themselves.
*
@@ -141,6 +150,22 @@ class HistoryListView(private val context: Context) : ScrollView(context) {
/** Laid rows drawn as re-openable pages; one losing its file forces a relayout. */
private val laidOpen = HashSet<Long>()
+ /**
+ * The topic rows currently in the view tree, by topic id — the
+ * across-refresh ledger [refresh] checks so a topic is drawn once.
+ * [openTopics] is the separate question of which cards have their outputs
+ * list open.
+ *
+ * A folded stretch is drawn as **one row where its messages used to be** —
+ * not at the foot of the list, not in a separate screen. That is the whole
+ * point: the conversation keeps its shape, and the part that is over reads
+ * as over. The rows are still in [ChatHistory] (they are the record, and the
+ * user still scrolls past "we talked about this at 3pm"); this is what
+ * decides which of them are drawn.
+ */
+ private val laidTopics = HashSet<Long>()
+ private val openTopics = HashSet<Long>()
+
/**
* Shown only when there is nothing to suggest either — a conversation that
* has not started and a build with no presets. The ordinary empty state is
@@ -290,28 +315,62 @@ class HistoryListView(private val context: Context) : ScrollView(context) {
val ids = all.map { it.id }.toSet()
val open = all.filter { it.page != null }.map { it.id }.toSet()
- if (laid.any { it !in ids } || laidOpen.any { it !in open }) {
- // A row we laid out is gone from the history — evicted from the
- // middle, or the whole list wiped. Cheaper and less error-prone to
- // start over than to reconcile. This deliberately does not also
- // require something to have been *added*: 清空聊天记录 removes
- // every row and adds none, and pairing the two conditions left the
- // card scrolling a conversation that no longer existed.
+ val topicIds = ChatHistory.topics().map { it.id }.toSet()
+ // The shape changed, do not try to patch it, when:
+ // * a row we laid out is gone from the history — evicted from the
+ // middle, or the whole list wiped;
+ // * a row we laid out as an ordinary message has since been folded into
+ // a topic. This is the moment of the fold itself: the rows are still
+ // in the history (so the check above stays quiet) but must leave the
+ // view, and the topic row has to stand where they were rather than at
+ // the foot. Topic entries never enter `laid`, so after a rebuild this
+ // is false until the next fold;
+ // * a topic we drew is no longer on the list (evicted).
+ // A topic merely *added* with no laid rows under it needs no rebuild.
+ val foldedUnderUs = all.any { it.topicId != null && it.id in laid }
+ if (laid.any { it !in ids } || laidOpen.any { it !in open } || foldedUnderUs ||
+ laidTopics.any { it !in topicIds }
+ ) {
column.removeAllViews()
column.addView(empty)
column.addView(suggest)
column.addView(live)
laid.clear()
laidOpen.clear()
+ laidTopics.clear()
}
// Inserted above the live row rather than appended, so a settled entry
// lands behind the thing that is still in progress.
+ //
+ // A folded stretch contributes exactly one row — the topic — drawn where
+ // its *first* message stood, and its messages are skipped. Drawing them
+ // as well would make the fold a lie; drawing the topic at the foot would
+ // put it out of the part of the conversation it belongs to.
+ //
+ // `laidTopics` is the across-refresh ledger of which topic rows are
+ // already in the view tree; using a *local* set here instead would redraw
+ // every topic on every refresh after a fold, because the view tree is
+ // only cleared on a shape change — a bug caught by the next tap after a
+ // fold stacking a second copy under the first.
for (e in all) {
+ val t = e.topicId
+ if (t != null) {
+ if (laidTopics.add(t)) {
+ val topic = ChatHistory.topicById(t) ?: continue
+ column.addView(buildTopicRow(topic), column.indexOfChild(live))
+ }
+ continue
+ }
if (laid.add(e.id)) {
if (e.page != null) laidOpen.add(e.id)
column.addView(buildRow(e), column.indexOfChild(live))
}
}
+ // A topic whose rows have all aged out of [MAX_ENTRIES] is never drawn:
+ // the heading stands where its first row stood, and with no rows left
+ // there is no such place — at the foot it would read as a stray card.
+ // It stays reachable through `list_topics`, which is where a finished
+ // conversation belongs once the rows it summarised are gone.
post { fullScroll(FOCUS_DOWN) }
}
@@ -496,6 +555,170 @@ class HistoryListView(private val context: Context) : ScrollView(context) {
return row
}
+ /**
+ * One finished topic, standing where its messages stood.
+ *
+ * **Its own kind of card, open by default.** The summary is what is left of
+ * that stretch in the scrollback, so it is shown, not hidden behind a tap; a
+ * folded row the user has to open to learn what it was is a row they stop
+ * opening. It spans the full width (no speaker's shoulder — nobody "said"
+ * it) and is tinted with the accent and edged with it, so it never reads as
+ * one more message.
+ *
+ * Three actions, all handed out: continuing is a turn, which only the service
+ * starts; the transcript is a fullscreen page, which needs the card folded
+ * first; and the outputs list opens in place, each one a page row that
+ * [onPageClick] already knows how to reopen.
+ */
+ private fun buildTopicRow(t: ChatHistory.Topic): View {
+ val accent = Color.parseColor(Glass.ACCENT)
+ fun withAlpha(c: Int, a: Float) = Color.argb((a * 255).toInt(), Color.red(c), Color.green(c), Color.blue(c))
+ val box = LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(16), dp(12), dp(16), dp(10))
+ background = GradientDrawable().apply {
+ cornerRadius = dp(18).toFloat()
+ setColor(withAlpha(accent, 0.10f))
+ setStroke(dp(1), withAlpha(accent, 0.45f))
+ }
+ }
+
+ val head = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ head.addView(
+ TextView(context).apply {
+ text = lctx.getString(R.string.history_topic_label)
+ textSize = Glass.Type.MICRO
+ letterSpacing = 0.05f
+ setTextColor(accent)
+ setTypeface(typeface, android.graphics.Typeface.BOLD)
+ setPadding(dp(8), dp(2), dp(8), dp(2))
+ background = GradientDrawable().apply {
+ cornerRadius = dp(10).toFloat()
+ setColor(withAlpha(accent, 0.18f))
+ }
+ },
+ )
+ head.addView(
+ TextView(context).apply {
+ text = t.title
+ textSize = Glass.Type.BODY
+ setTextColor(Color.parseColor(Glass.TITLE))
+ setTypeface(typeface, android.graphics.Typeface.BOLD)
+ maxLines = 1
+ ellipsize = android.text.TextUtils.TruncateAt.END
+ setPadding(dp(8), 0, dp(8), 0)
+ },
+ LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f),
+ )
+ head.addView(
+ TextView(context).apply {
+ // Counted off the live rows: this row is rebuilt on every
+ // relayout and must not read a file to draw.
+ text = lctx.getString(
+ R.string.history_topic_meta,
+ clock.format(Date(t.endedAt)),
+ ChatHistory.rowCountOf(t.id),
+ )
+ textSize = Glass.Type.MICRO
+ setTextColor(Color.parseColor(Glass.SECONDARY))
+ },
+ )
+ box.addView(head, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
+
+ box.addView(
+ TextView(context).apply {
+ text = t.summary
+ textSize = Glass.Type.BODY
+ setTextColor(Color.parseColor(Glass.LABEL))
+ setLineSpacing(dp(3).toFloat(), 1f)
+ setPadding(0, dp(10), 0, 0)
+ },
+ LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT),
+ )
+
+ val outputs = ChatHistory.outputsOf(t.id)
+ val showOutputs = t.id in openTopics && outputs.isNotEmpty()
+ val actions = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ setPadding(0, dp(8), 0, 0)
+ }
+ fun action(label: String, onTap: () -> Unit) = TextView(context).apply {
+ text = label
+ textSize = Glass.Type.CAPTION
+ setTextColor(accent)
+ setPadding(dp(4), dp(8), dp(14), dp(6))
+ isClickable = true
+ setOnClickListener { onTap() }
+ }
+ actions.addView(action(lctx.getString(R.string.history_topic_continue)) { onTopicContinue?.invoke(t) })
+ actions.addView(action(lctx.getString(R.string.history_topic_transcript)) { onTopicTranscript?.invoke(t) })
+ if (outputs.isNotEmpty()) {
+ actions.addView(
+ action(
+ lctx.getString(
+ if (showOutputs) R.string.history_topic_outputs_hide else R.string.history_topic_outputs,
+ outputs.size,
+ ),
+ ) {
+ if (!openTopics.add(t.id)) openTopics.remove(t.id)
+ relayoutAll()
+ },
+ )
+ }
+ box.addView(actions, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
+
+ if (showOutputs) {
+ for (p in outputs) {
+ box.addView(
+ TextView(context).apply {
+ text = lctx.getString(R.string.history_topic_output_item, p.text, p.version)
+ textSize = Glass.Type.CAPTION
+ setTextColor(Color.parseColor(Glass.LABEL))
+ setPadding(dp(12), dp(9), dp(12), dp(9))
+ maxLines = 1
+ ellipsize = android.text.TextUtils.TruncateAt.END
+ background = RippleDrawable(
+ ColorStateList.valueOf(ripple()),
+ Glass.well(context, dp(12)),
+ null,
+ )
+ isClickable = true
+ setOnClickListener { onPageClick?.invoke(p) }
+ },
+ LinearLayout.LayoutParams(MATCH, WRAP).apply { topMargin = dp(6) },
+ )
+ }
+ }
+
+ // Full width, and spaced off its neighbours more than two messages are
+ // from each other: a topic is a break in the conversation, and a card
+ // glued to the bubble above it read as part of that bubble.
+ return LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ layoutParams = LinearLayout.LayoutParams(MATCH, WRAP).apply {
+ topMargin = dp(16)
+ bottomMargin = dp(8)
+ }
+ addView(box, LinearLayout.LayoutParams(MATCH, WRAP))
+ }
+ }
+
+ /** Re-lay every row: an outputs list opened or closed, and rows are built once. */
+ private fun relayoutAll() {
+ column.removeAllViews()
+ column.addView(empty)
+ column.addView(suggest)
+ column.addView(live)
+ laid.clear()
+ laidOpen.clear()
+ laidTopics.clear()
+ refresh()
+ }
+
private fun buildRow(e: ChatHistory.Entry): View {
val mine = e.role == ChatHistory.Role.USER
val bad = e.role == ChatHistory.Role.ERROR
diff --git a/app/src/main/java/net/kuafuai/andee/ui/TextPage.kt b/app/src/main/java/net/kuafuai/andee/ui/TextPage.kt
index e0047a8..d644240 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/TextPage.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/TextPage.kt
@@ -70,8 +70,46 @@ object TextPage {
return "$who · $when_"
}
+ /**
+ * A folded topic's conversation as one page — 对话记录 on the topic card.
+ *
+ * Built from the device's own rows, which are what the user saw and said,
+ * rather than from the brain's archived text, which carries tool chatter and
+ * reads like a log. Rows age out under the history cap, though, so when none
+ * are left the archived text is shown instead; it is still the conversation.
+ */
+ fun writeTopic(context: Context, topic: ChatHistory.Topic): File? = runCatching {
+ val lctx = AppLocale.wrap(context)
+ val fmt = SimpleDateFormat("MM-dd HH:mm", AppLocale.localeOf(context))
+ val rows = ChatHistory.rowsOf(topic.id)
+ val cards = if (rows.isNotEmpty()) {
+ rows.joinToString("\n") { e ->
+ val who = when (e.role) {
+ ChatHistory.Role.USER -> lctx.getString(R.string.textpage_role_you)
+ ChatHistory.Role.ASSISTANT -> lctx.getString(R.string.textpage_role_assistant)
+ ChatHistory.Role.ERROR -> lctx.getString(R.string.textpage_role_error)
+ ChatHistory.Role.PAGE -> lctx.getString(R.string.textpage_role_page)
+ }
+ val cls = if (e.role == ChatHistory.Role.USER) "card mine" else "card"
+ " <p class=\"who\">${esc(who)} · ${esc(fmt.format(Date(e.ts)))}</p>\n" +
+ " <div class=\"$cls\">\n${body(e.text)}\n </div>"
+ }
+ } else {
+ val text = ChatHistory.topicText(topic.id) ?: lctx.getString(R.string.textpage_topic_gone)
+ " <div class=\"card\">\n${body(text)}\n </div>"
+ }
+ val head = lctx.getString(R.string.textpage_topic_head, topic.title)
+ File(dir(context), "topic_${topic.id}.html").also { it.writeText(page(head, cards)) }
+ }.getOrElse {
+ Log.w(TAG, "topic page: could not write: ${it.message}")
+ null
+ }
+
/** The whole document. Exposed for the tests that read it back. */
- fun html(who: String, text: String): String = """
+ fun html(who: String, text: String): String =
+ page(who, " <div class=\"card\">\n${body(text)}\n </div>")
+
+ private fun page(head: String, content: String): String = """
<!doctype html>
<html><head>
<meta charset="utf-8">
@@ -83,18 +121,18 @@ object TextPage {
/* 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 + .who { margin-top:20px; }
.card { background:#1E293B; border:1px solid rgba(148,163,184,.18);
border-radius:14px; padding:20px; }
+ .card.mine { background:#1E2B45; }
p { margin:0 0 16px; word-break:break-word; }
p:last-child { margin-bottom:0; }
p.gap { margin:0; height:8px; }
</style>
</head><body>
<div class="wrap">
- <p class="who">${esc(who)}</p>
- <div class="card">
-${body(text)}
- </div>
+ <p class="who">${esc(head)}</p>
+$content
</div>
</body></html>
""".trimIndent()
diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml
index 96e008b..515b701 100644
--- a/app/src/main/res/values-en/strings.xml
+++ b/app/src/main/res/values-en/strings.xml
@@ -295,6 +295,17 @@
<string name="history_role_assistant">Andee · %1$s</string>
<string name="history_role_error">Error · %1$s</string>
<string name="history_role_page_open">Page · %1$s · Tap to reopen</string>
+ <string name="history_topic_label">Topic</string>
+ <string name="history_topic_meta">%1$s · %2$d messages</string>
+ <string name="history_topic_continue">Continue</string>
+ <string name="history_topic_transcript">Transcript</string>
+ <string name="history_topic_outputs">Made here (%1$d)</string>
+ <string name="history_topic_outputs_hide">Hide made here</string>
+ <string name="history_topic_output_item">%1$s · v%2$d</string>
+ <string name="topic_continue_prompt">Continue “%1$s”: what next? Say it or type it</string>
+ <string name="topic_continue_said">Continue “%1$s”: %2$s</string>
+ <string name="textpage_topic_head">Topic · %1$s</string>
+ <string name="textpage_topic_gone">The full text of this conversation has been cleared; only the summary on the topic card is left.</string>
<string name="history_role_page_cleared">Page · %1$s · Cleared</string>
<string name="html_default_title">AI page</string>
<string name="textpage_role_you">You</string>
@@ -425,6 +436,7 @@
<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_topics">Looking back at where we got to…</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.xml
index 436fe91..88b4c35 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -278,6 +278,18 @@
<string name="history_role_assistant">Andee · %1$s</string>
<string name="history_role_error">出错 · %1$s</string>
<string name="history_role_page_open">界面 · %1$s · 点击重新打开</string>
+ <!-- 话题: a finished stretch of conversation, folded into one card. -->
+ <string name="history_topic_label">话题</string>
+ <string name="history_topic_meta">%1$s · %2$d 条</string>
+ <string name="history_topic_continue">继续话题</string>
+ <string name="history_topic_transcript">对话记录</string>
+ <string name="history_topic_outputs">产出物(%1$d)</string>
+ <string name="history_topic_outputs_hide">收起产出物</string>
+ <string name="history_topic_output_item">%1$s · v%2$d</string>
+ <string name="topic_continue_prompt">继续「%1$s」:接下来想做什么?说出来或打字告诉我</string>
+ <string name="topic_continue_said">继续「%1$s」:%2$s</string>
+ <string name="textpage_topic_head">话题 · %1$s</string>
+ <string name="textpage_topic_gone">这段对话的原文已经清理,只剩话题卡片上的摘要。</string>
<string name="history_role_page_cleared">界面 · %1$s · 已清理</string>
<string name="html_default_title">AI 界面</string>
<string name="textpage_role_you">你</string>
@@ -505,6 +517,7 @@
<string name="narrate_system">操作系统按键…</string>
<string name="narrate_show_html">把结果放到屏幕上…</string>
<string name="narrate_pages">翻一下之前做的东西…</string>
+ <string name="narrate_topics">回想一下之前聊到哪儿了…</string>
<string name="narrate_camera">看一眼…</string>
<string name="narrate_dog">动一下腿…</string>
<!--
diff --git a/app/src/test/java/net/kuafuai/andee/brain/TopicAnchorTest.kt b/app/src/test/java/net/kuafuai/andee/brain/TopicAnchorTest.kt
new file mode 100644
index 0000000..1b54122
--- /dev/null
+++ b/app/src/test/java/net/kuafuai/andee/brain/TopicAnchorTest.kt
@@ -0,0 +1,187 @@
+package net.kuafuai.andee.brain
+
+import net.kuafuai.andee.ui.ChatHistory
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Matching a brain message to the device row it corresponds to.
+ *
+ * The two records of one conversation do **not** share an id, a length, or a
+ * clock: the brain's history carries tool traffic the device never saw, and its
+ * timestamp rides in the message text as `[now …]` to the minute while a row
+ * carries milliseconds. The first version of the fold matched the two on
+ * timestamps and silently found nothing — the fold reported success and no
+ * conversation was ever put away.
+ *
+ * These tests pin down the anchor that does work: **the words**.
+ */
+class TopicAnchorTest {
+
+ /**
+ * The real implementation, not a copy. It lives in [TopicSplitter] as a
+ * public pure function for exactly this reason — the assertions below are
+ * about the production behaviour, and a duplicated version would pass while
+ * the shipped one drifted.
+ */
+ private fun anchor(raw: String?): String = TopicSplitter.anchorText(raw)
+
+ /** What a device row holds, for contrast: the sentence and nothing else. */
+ private fun deviceRowText(said: String) = said
+
+ @Test
+ fun `a plain user message reduces to the sentence`() {
+ assertEquals("帮我做个番茄钟", anchor("[now 2026-10-15 周四 18:54] 帮我做个番茄钟"))
+ }
+
+ @Test
+ fun `it matches what the device row holds`() {
+ // The property the fold depends on: strip the chrome and the two records
+ // agree on the text.
+ val said = "帮我做个番茄钟"
+ assertEquals(deviceRowText(said), anchor("[now 2026-10-15 周四 18:54] $said"))
+ }
+
+ @Test
+ fun `index sections are not part of the sentence`() {
+ val brain = "[now 2026-10-15 周四 18:54] 改成深蓝色\n\n" +
+ "(what your notebook holds, for reference; use recall for detail)\n- 咖啡:不加糖"
+ assertEquals("改成深蓝色", anchor(brain))
+ }
+
+ @Test
+ fun `all four index sections are cut, not just the first`() {
+ val brain = "[now 2026-10-15 周四 18:54] 再加个铃声\n\n" +
+ "(scenes you can enter — see §11)\n- x\n\n" +
+ "(pages you have made on this device — §7)\n- #1 y\n\n" +
+ "(conversations you have finished and put away)\n- #2 z"
+ assertEquals("再加个铃声", anchor(brain))
+ }
+
+ @Test
+ fun `the language tag does not leak into the anchor`() {
+ val withTag = anchor("[now 2026-10-15 周四 18:54 · ui-language zh] 好了谢谢")
+ val without = anchor("[now 2026-10-15 周四 18:54] 好了谢谢")
+ assertEquals(without, withTag)
+ }
+
+ @Test
+ fun `a message with no stamp still yields its sentence`() {
+ assertEquals("你好,能听见吗?", anchor("你好,能听见吗?"))
+ }
+
+ @Test
+ fun `an assistant message is its own answer`() {
+ // Assistant rows carry no `[now …]`; the device row holds the same text.
+ assertEquals("好的。", anchor("好的。"))
+ }
+
+ @Test
+ fun `tool traffic has no words and is therefore skippable`() {
+ // A tool message carries a JSON object as its content, not a String —
+ // the fold must step over these rather than anchor on them.
+ val toolMsg = JSONObject().put("role", "tool")
+ .put("content", JSONObject().put("shown", true))
+ assertEquals("", TopicSplitter.anchorText(toolMsg))
+ }
+
+ // ---- locating a stretch among the device's rows ----
+
+ private val MIN = 60_000L
+
+ /** A row as the matcher sees it. `at` is minutes from an arbitrary epoch. */
+ private fun user(text: String, at: Long) = TopicSplitter.RowKey(true, text, at * MIN)
+ private fun bot(text: String, at: Long) = TopicSplitter.RowKey(false, text, at * MIN)
+
+ /**
+ * The shape the bug lived in: the stretch's last words are 「好的。」, which
+ * the assistant also says at the end of every later stretch. Anchoring on the
+ * last spoken line matched the *final* 「好的。」 in the whole conversation and
+ * folded the live rows into the topic.
+ */
+ @Test
+ fun `a stretch ending in a common reply does not swallow the later ones`() {
+ val rows = listOf(
+ user("帮我做个番茄钟", 0), bot("好的。", 1),
+ user("改成深蓝色", 2), bot("好的。", 3),
+ // — a long gap: the next stretch —
+ user("帮我比比三款扫地机器人", 60), bot("好的。", 61),
+ user("还有别的吗", 62), bot("好的。", 63),
+ )
+ val range = TopicSplitter.locateRows(
+ rows,
+ firstSaid = "帮我做个番茄钟", firstAt = 0,
+ nextSaid = "帮我比比三款扫地机器人", nextAt = 60 * MIN,
+ )
+ assertEquals(0..3, range)
+ }
+
+ @Test
+ fun `tool traffic and replies between the two anchors belong to the stretch`() {
+ val rows = listOf(
+ user("a 做个页面", 0), bot("我看一下", 0), bot("好了", 1), user("b 加个按钮", 2), bot("加好了", 3),
+ user("c 新话题", 90),
+ )
+ assertEquals(0..4, TopicSplitter.locateRows(rows, "a 做个页面", 0, "c 新话题", 90 * MIN))
+ }
+
+ @Test
+ fun `a repeated opener is told apart by the clock`() {
+ // 「继续」 opens both stretches. The one nearest the stamp is the one meant.
+ val rows = listOf(
+ user("继续", 0), bot("好", 1), user("再来", 2),
+ user("继续", 120), bot("好", 121), user("下一个话题", 240),
+ )
+ val range = TopicSplitter.locateRows(rows, "继续", 120 * MIN, "下一个话题", 240 * MIN)
+ assertEquals(3..4, range)
+ }
+
+ @Test
+ fun `a row within the tolerance still matches a minute-floored stamp`() {
+ // The stamp is floored to the minute and taken after the row was written.
+ val rows = listOf(user("开始", 10), bot("好", 11), user("结束", 100))
+ assertEquals(
+ 0..1,
+ TopicSplitter.locateRows(rows, "开始", 10 * MIN - 30_000, "结束", 100 * MIN - 30_000),
+ )
+ }
+
+ @Test
+ fun `a clock too far from every candidate is no match`() {
+ val rows = listOf(user("开始", 0), bot("好", 1), user("结束", 100))
+ assertNull(TopicSplitter.locateRows(rows, "开始", 50 * MIN, "结束", 100 * MIN))
+ }
+
+ @Test
+ fun `without a clock only a unique match is accepted`() {
+ val unique = listOf(user("开始", 0), bot("好", 1), user("结束", 100))
+ assertEquals(0..1, TopicSplitter.locateRows(unique, "开始", 0, "结束", 0))
+ val ambiguous = listOf(user("开始", 0), user("开始", 5), bot("好", 6), user("结束", 100))
+ assertNull(TopicSplitter.locateRows(ambiguous, "开始", 0, "结束", 100 * MIN))
+ }
+
+ @Test
+ fun `an assistant row is never mistaken for an opener`() {
+ // Same words, wrong speaker: only a user row can open a stretch.
+ val rows = listOf(bot("开始", 0), user("别的", 1), user("结束", 100))
+ assertNull(TopicSplitter.locateRows(rows, "开始", 0, "结束", 100 * MIN))
+ }
+
+ @Test
+ fun `nothing found, or nothing after, is null rather than a guess`() {
+ val rows = listOf(user("开始", 0), bot("好", 1))
+ assertNull(TopicSplitter.locateRows(rows, "没说过", 0, "结束", 100 * MIN))
+ assertNull(TopicSplitter.locateRows(rows, "开始", 0, "结束", 100 * MIN))
+ assertNull(TopicSplitter.locateRows(rows, "", 0, "结束", 100 * MIN))
+ }
+
+ @Test
+ fun `a truncated row still matches the head of the sentence`() {
+ val said = "帮我做一个可以倒计时二十五分钟并且到点会响铃的番茄钟应用"
+ val rows = listOf(user(said, 0), bot("好", 1), user("下一个", 100))
+ assertEquals(0..1, TopicSplitter.locateRows(rows, said, 0, "下一个", 100 * MIN))
+ }
+}
diff --git a/app/src/test/java/net/kuafuai/andee/brain/TopicSplitterTest.kt b/app/src/test/java/net/kuafuai/andee/brain/TopicSplitterTest.kt
new file mode 100644
index 0000000..d7613eb
--- /dev/null
+++ b/app/src/test/java/net/kuafuai/andee/brain/TopicSplitterTest.kt
@@ -0,0 +1,220 @@
+package net.kuafuai.andee.brain
+
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Where the seams are, and why they have to be found mechanically.
+ *
+ * A wrong seam is not a wrong label: the stretch it names gets replaced by a
+ * summary in the live context, and a range that lands inside a turn orphans a
+ * `tool` message and the API answers 400. So the rules are pinned down here
+ * rather than trusted to review.
+ *
+ * The two locale hazards are covered on purpose — the stamp is rendered in the
+ * interface language, so a parser that reads `MM-dd HH:mm` works on this
+ * machine and fails on a Chinese tablet, which is exactly the bug that would
+ * survive every local test.
+ */
+class TopicSplitterTest {
+
+ /** A user message carrying the device's own `[now …]` stamp. */
+ private fun user(stamp: String, text: String = "做个番茄钟"): JSONObject =
+ JSONObject().put("role", "user").put("content", "[now $stamp] $text")
+
+ private fun assistant(text: String): JSONObject =
+ JSONObject().put("role", "assistant").put("content", text)
+
+ private fun system(): JSONObject =
+ JSONObject().put("role", "system").put("content", "you are andee")
+
+ /** An assistant turn that called a tool, plus the result it got back. */
+ private fun toolCall(name: String = "show_html"): List<JSONObject> = listOf(
+ JSONObject().put("role", "assistant")
+ .put("content", JSONObject.NULL)
+ .put(
+ "tool_calls",
+ JSONArray().put(
+ JSONObject().put("id", "c1").put(
+ "function",
+ JSONObject().put("name", name).put("arguments", "{}"),
+ ),
+ ),
+ ),
+ JSONObject().put("role", "tool").put("tool_call_id", "c1").put("content", "{\"shown\":true}"),
+ )
+
+ /** Six messages: a conversation big enough to be worth folding. */
+ private fun stretch(stamp: String, tag: String): List<JSONObject> = listOf(
+ user(stamp, "帮我$tag"),
+ assistant("好"),
+ assistant("做完了"),
+ user(stamp, "再改一下$tag"),
+ assistant("改好了"),
+ assistant("还有别的吗"),
+ )
+
+ // ---- the turns a topic may start and end on ----
+
+ @Test
+ fun `every stamped user message is a turn, oldest first`() {
+ val h = listOf(system()) +
+ stretch("2026-10-15 周四 10:00", "甲") +
+ stretch("2026-10-15 周四 10:01", "乙")
+ val turns = TopicSplitter.userTurns(h)
+ assertEquals(listOf(1, 4, 7, 10), turns)
+ assertTrue(turns.all { h[it].optString("role") == "user" })
+ }
+
+ /**
+ * The case that looked broken on the tablet: a timer, then the weather a
+ * minute later. Two topics, no silence between them — both turns must be
+ * offered, so the model can say where one topic ends.
+ */
+ @Test
+ fun `a change of subject with no silence still yields separate turns`() {
+ val h = listOf(system()) +
+ listOf(user("2026-10-16 周五 10:10", "帮我做一个番茄钟"), assistant("做好了")) +
+ listOf(user("2026-10-16 周五 10:10", "做得美观一些"), assistant("改好了")) +
+ listOf(user("2026-10-16 周五 10:11", "今天天气怎么样?"), assistant("晴"))
+ assertEquals(3, TopicSplitter.userTurns(h).size)
+ }
+
+ @Test
+ fun `device notes in the user role are not turns`() {
+ // A page closed, a transcript arrived: no stamp, no row on the device,
+ // and not where the person changed the subject.
+ val h = listOf(system()) +
+ user("2026-10-15 周四 10:00", "甲") +
+ JSONObject().put("role", "user").put("content", "(the user closed the page)") +
+ user("2026-10-15 周四 10:02", "乙")
+ assertEquals(listOf(1, 3), TopicSplitter.userTurns(h))
+ }
+
+ @Test
+ fun `the system prompt and tool traffic are never turns`() {
+ val h = listOf(system()) + user("2026-10-15 周四 10:00") + toolCall()
+ assertEquals(listOf(1), TopicSplitter.userTurns(h))
+ }
+
+ @Test
+ fun `a long silence is a seam and a short one is not`() {
+ val a = user("2026-10-15 周四 10:00")
+ assertTrue(TopicSplitter.isSeam(a, user("2026-10-15 周四 14:00")))
+ assertFalse(TopicSplitter.isSeam(a, user("2026-10-15 周四 10:05")))
+ }
+
+ @Test
+ fun `a change of day is a seam even without a long silence`() {
+ assertTrue(TopicSplitter.isSeam(user("2026-10-15 周四 23:55"), user("2026-10-16 周五 00:05")))
+ }
+
+ @Test
+ fun `two unknown clocks are not a seam`() {
+ // Zero means "unknown", and two unknowns must not read as a huge gap.
+ assertFalse(TopicSplitter.isSeam(user(""), user("")))
+ }
+
+ // ---- the stamp, in both interface languages ----
+
+ @Test
+ fun `reads a Chinese stamp`() {
+ val t = TopicSplitter.stampOfText("[now 2026-10-15 周四 18:30] 做个番茄钟")
+ assertTrue("expected a real instant, got $t", t > 0)
+ }
+
+ @Test
+ fun `reads an English stamp`() {
+ val zh = TopicSplitter.stampOfText("[now 2026-10-15 周四 18:30] x")
+ val en = TopicSplitter.stampOfText("[now 2026-10-15 Thu 18:30] x")
+ // Same instant either way — this is the whole point of not parsing with
+ // one locale's pattern.
+ assertEquals(zh, en)
+ }
+
+ @Test
+ fun `reads the stamp when the language tag follows it`() {
+ val plain = TopicSplitter.stampOfText("[now 2026-10-15 Thu 18:30] hi")
+ val tagged = TopicSplitter.stampOfText("[now 2026-10-15 Thu 18:30 · ui-language en] hi")
+ assertEquals(plain, tagged)
+ }
+
+ @Test
+ fun `a message with no stamp reads as no time, not as 1970`() {
+ assertEquals(0L, TopicSplitter.stampOfText("(the user sent 2 photo(s) with no words)"))
+ assertEquals(0L, TopicSplitter.stampOfText(null))
+ assertEquals(0L, TopicSplitter.stampOfText(""))
+ }
+
+ // ---- dangling calls ----
+
+ @Test
+ fun `an answered tool call is not dangling`() {
+ val h = listOf(system()) + toolCall()
+ assertFalse(TopicSplitter.hasDanglingCall(h, 1, h.size))
+ }
+
+ @Test
+ fun `an unanswered tool call is`() {
+ // The turn was interrupted mid-call. Folding this would bury the one
+ // thing the next turn has to see.
+ val h = listOf(system()) +
+ JSONObject().put("role", "assistant")
+ .put("content", JSONObject.NULL)
+ .put(
+ "tool_calls",
+ JSONArray().put(
+ JSONObject().put("id", "c9")
+ .put("function", JSONObject().put("name", "show_html").put("arguments", "{}")),
+ ),
+ )
+ assertTrue(TopicSplitter.hasDanglingCall(h, 1, h.size))
+ }
+
+ @Test
+ fun `the range given is the range checked`() {
+ val h = listOf(system()) + toolCall() + toolCall()
+ // Only the first call is inside this window.
+ assertFalse(TopicSplitter.hasDanglingCall(h, 1, 3))
+ }
+
+ // ---- rendering the text the brain reads back ----
+
+ @Test
+ fun `the rendered text is the words, without the stamps`() {
+ val h = listOf(system()) + stretch("2026-10-15 周四 10:00", "番茄钟")
+ val text = renderTopicText(h, 1, h.size)
+ assertTrue(text.contains("帮我番茄钟"))
+ assertFalse("a stamp is device chrome, not something anyone said", text.contains("[now "))
+ assertFalse(text.contains("you are andee"))
+ }
+
+ @Test
+ fun `the rendered text leaves out the index sections the device appended`() {
+ // Caught on the tablet: get_topic handed back the notebook index as if
+ // the user had said it.
+ val h = listOf(system()) +
+ JSONObject().put("role", "user").put(
+ "content",
+ "[now 2026-10-16 周五 10:50] 帮我做一个番茄钟的应用\n\n" +
+ "(what your notebook holds, for reference; use recall for detail)\n- 位置:常驻北京",
+ )
+ val text = renderTopicText(h, 1, h.size)
+ assertTrue(text.contains("帮我做一个番茄钟的应用"))
+ assertFalse(text.contains("notebook"))
+ assertFalse(text.contains("常驻北京"))
+ }
+
+ @Test
+ fun `tool traffic is noted by name, not pasted in`() {
+ val h = listOf(system()) + toolCall("show_html")
+ val text = renderTopicText(h, 1, h.size)
+ assertTrue(text.contains("show_html"))
+ // The result body is device chatter and can be 24 000 characters.
+ assertFalse(text.contains("shown"))
+ }
+}