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、支持任意模型,记忆和密码绝不离开设备。

fix: a quiet afternoon is one review row, not eighteen — both bodies

booboosui6667338f6a05
diff --git a/CLAUDE.md b/CLAUDE.md
index 9cba716..8f1969c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -681,7 +681,7 @@ meetings, gear, friends) and lists exactly the tools some provider handles. What
- **Notifications come from `usernoted`'s SQLite store, and where it is depends on the macOS version** (`notifCandidates` in `AndeeMac.swift`): macOS 15 keeps it in `~/Library/Group Containers/group.com.apple.usernoted/db2`, earlier systems under `confstr(_CS_DARWIN_USER_DIR)` + `com.apple.notificationcenter/db2` (never derive that from `$TMPDIR` — the JVM replaces it). Only the first was tried, and a store that was not there was reported as missing Full Disk Access, so the user granted it and was told the same thing forever. `andee_notif_latest_id` now answers -2 for "no store anywhere" (`State.NOT_FOUND`, no permission button) and -1 for "exists but refuses us" (`NO_ACCESS`), and reads in process through `libsqlite3` (read-only, busy timeout, since `usernoted` is writing the WAL) instead of forking `/usr/bin/sqlite3`, which swallowed the reason.
- **`type_text` pastes even when the front app reports no focused element** (`MacScreen.typeBlind`). Mac WeChat answers `focused: false` to accessibility, and refusing there sent the model to the shell (`osascript` + ⌘V), which a notification's turn may not use — so a message Andee could read, it could not answer. The blind path sends ⌘V only (no ⌘A: with focus unknown, select-all may take the chat history), refuses when Andee's own window is active, and returns `unverified` with a note to check the screenshot and not to reach for the shell. Verified in WeChat's 文件传输助手 by reading the box back with ⌘A ⌘C. The pasteboard is still not restored afterwards — that was a deliberate choice (see `andee_set_pasteboard`).
- **A click on an inactive app only activates it, so every click brings its app forward first** (`MacScreen.click` → `andee_activate_at`; keystrokes → `andee_activate_target`). Measured 2026-10-28 in Chrome with Finder in front: one click left focus on the page (`AXWebArea`), the second focused the text box. In the trace that turned into a sidebar click that "did nothing" and a `type_text` that pasted into the page and reported success — the task stalled on a box the model concluded it "cannot type into". Not verified end-to-end after the fix (the test window was the user's live Chrome).
-- **The main page is 动态 (Timeline), not a chat.** Besides what was said, it shows what happened as one quiet line each: a todo waking it, the review, topics folded, its writes to its own record (diary, self, wiki, a person, a care, a memory, a todo, the plan), a heartbeat's thought and its work turns, bubbles, notifications it let pass and why, meetings, the camera, a vault fill, shell commands. Two sources end in one place: the brain emits `BrainEvent` through `BrainHost.event` (core), and the body adds its own (`TimelineEvents`); both write `Scrollback.Role.EVENT` rows. **The phone does the same** (`ui/PhoneTimeline.kt` → `ChatHistory.Role.EVENT`, drawn by `HistoryListView.buildEventRow`; 全部 / 只看对话 is the key at the ball's lower left, mirroring 朗读), and `AndroidBrainHost.scrollback` filters those rows the same way. A notification stopped at a gate (a task running, the hourly cap) also leaves a row on both, since otherwise it looks like the device did not react. **Those rows are never given back to the brain** (`DesktopBrainHost.scrollback` filters them) — a review summary must not return as something said — and they fold with the topic they sit inside. A heartbeat that decided to sleep writes nothing. 全部 / 只看对话 in the header hides them (`timeline_events`).
+- **The main page is 动态 (Timeline), not a chat.** Besides what was said, it shows what happened as one quiet line each: a todo waking it, the review, topics folded, its writes to its own record (diary, self, wiki, a person, a care, a memory, a todo, the plan), a heartbeat's thought and its work turns, bubbles, notifications it let pass and why, meetings, the camera, a vault fill, shell commands. Two sources end in one place: the brain emits `BrainEvent` through `BrainHost.event` (core), and the body adds its own (`TimelineEvents`); both write `Scrollback.Role.EVENT` rows. **The phone does the same** (`ui/PhoneTimeline.kt` → `ChatHistory.Role.EVENT`, drawn by `HistoryListView.buildEventRow`; 全部 / 只看对话 is the key at the ball's lower left, mirroring 朗读), and `AndroidBrainHost.scrollback` filters those rows the same way. A notification stopped at a gate (a task running, the hourly cap) also leaves a row on both, since otherwise it looks like the device did not react. **A review is one row** (`BrainEvent.Kind.REVIEWED` with `items`; `LocalBrain.reviewItems` gathers its writes) and a review that wrote nothing shows nothing; a write that changed nothing (`unchanged` in the tool result) is no event, and a rewrite of something already there says 更新 / 改写 (`BrainEvent.updated`, from `overwrote` / `replaced`). A harvest straight after a sweep only summarises (`HARVEST_SUMMARY_ONLY`), because going through the review rules again wrote everything twice. The Mac's "this silence was already reviewed" is on disk (`last_sweep_attempt`), like the phone's `Notebook.lastSweepAt` — in memory it was forgotten by every restart and the same stretch was reviewed again. **Those rows are never given back to the brain** (`DesktopBrainHost.scrollback` filters them) — a review summary must not return as something said — and they fold with the topic they sit inside. A heartbeat that decided to sleep writes nothing. 全部 / 只看对话 in the header hides them (`timeline_events`).
- **A prompt card appears beside the ball** (`PromptWindow`), which may be on a screen the user is not looking
at. A friend's request therefore plays a sound and waves the ball first — the first one timed out unseen.
diff --git a/app/src/main/java/net/kuafuai/andee/ui/PhoneTimeline.kt b/app/src/main/java/net/kuafuai/andee/ui/PhoneTimeline.kt
index f289d1d..b5e877a 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/PhoneTimeline.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/PhoneTimeline.kt
@@ -22,14 +22,27 @@ object PhoneTimeline {
private fun s(c: Context, id: Int, vararg a: Any) = AppLocale.str(c, id, *a)
fun brain(c: Context, e: BrainEvent) {
+ val detail = when (e.kind) {
+ // A review is one row; what it wrote is the detail, one line each.
+ BrainEvent.Kind.REVIEWED -> e.items.joinToString("\n") { "- " + line(c, it) }
+ BrainEvent.Kind.CARE -> ""
+ BrainEvent.Kind.TODO -> e.detail.takeIf { it.isNotBlank() }?.let { s(c, R.string.tl_todo_at, it) }.orEmpty()
+ else -> e.detail
+ }
+ ChatHistory.addEvent(e.kind.name, line(c, e), detail, e.ref)
+ }
+
+ /** One event in words. An [BrainEvent.updated] write says so, so a rewrite does not read as something new. */
+ private fun line(c: Context, e: BrainEvent): String {
val x = e.subject
- val text = when (e.kind) {
+ val u = e.updated
+ return when (e.kind) {
BrainEvent.Kind.WOKE -> s(c, R.string.tl_woke, x)
BrainEvent.Kind.NOTIFIED -> s(c, R.string.tl_notified)
BrainEvent.Kind.FRIEND_TASK -> s(c, R.string.tl_friend_task)
- BrainEvent.Kind.REVIEWED -> if (x == "0" || x.isEmpty()) s(c, R.string.tl_reviewed_none) else s(c, R.string.tl_reviewed, x)
+ BrainEvent.Kind.REVIEWED -> s(c, R.string.tl_reviewed, x)
BrainEvent.Kind.FOLDED -> s(c, R.string.tl_folded, x)
- BrainEvent.Kind.DIARY -> s(c, R.string.tl_diary)
+ BrainEvent.Kind.DIARY -> s(c, if (u) R.string.tl_diary_updated else R.string.tl_diary)
BrainEvent.Kind.SELF -> s(c, R.string.tl_self)
BrainEvent.Kind.WIKI -> s(c, R.string.tl_wiki, x)
BrainEvent.Kind.WIKI_READ -> s(c, R.string.tl_wiki_read, x)
@@ -40,16 +53,18 @@ object PhoneTimeline {
"done" -> s(c, R.string.tl_care_done)
else -> s(c, R.string.tl_care_drop)
}
- BrainEvent.Kind.MEMORY -> s(c, R.string.tl_memory, x)
+ BrainEvent.Kind.MEMORY -> s(c, if (u) R.string.tl_memory_updated else R.string.tl_memory, x)
BrainEvent.Kind.TODO -> s(c, R.string.tl_todo, x)
- BrainEvent.Kind.PLAN -> s(c, if (x == "tomorrow") R.string.tl_plan_tomorrow else R.string.tl_plan_today)
- }
- val detail = when (e.kind) {
- BrainEvent.Kind.CARE -> ""
- BrainEvent.Kind.TODO -> e.detail.takeIf { it.isNotBlank() }?.let { s(c, R.string.tl_todo_at, it) }.orEmpty()
- else -> e.detail
+ BrainEvent.Kind.PLAN -> s(
+ c,
+ when {
+ x == "tomorrow" && u -> R.string.tl_plan_tomorrow_updated
+ x == "tomorrow" -> R.string.tl_plan_tomorrow
+ u -> R.string.tl_plan_today_updated
+ else -> R.string.tl_plan_today
+ },
+ )
}
- ChatHistory.addEvent(e.kind.name, text, detail, e.ref)
}
fun body(kind: Body, text: String, detail: String = "") = ChatHistory.addEvent(kind.name, text, detail)
diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml
index 82a7389..1df385f 100644
--- a/app/src/main/res/values-en/strings.xml
+++ b/app/src/main/res/values-en/strings.xml
@@ -484,7 +484,6 @@
<string name="tl_woke">Reminder due: %1$s</string>
<string name="tl_notified">A notification was worth acting on</string>
<string name="tl_friend_task">Another Andee handed over a task</string>
- <string name="tl_reviewed_none">Reviewed the conversation; nothing to keep</string>
<string name="tl_reviewed">Reviewed the conversation; kept %1$s things</string>
<string name="tl_folded">Put away a topic: %1$s</string>
<string name="tl_diary">Wrote today\'s diary</string>
@@ -511,6 +510,10 @@
<string name="tl_morning">Thought out today\'s plan this morning</string>
<string name="tl_held">A notification from %1$s came in while busy; kept for later</string>
<string name="tl_capped">A notification from %1$s came in past the hourly limit; kept for later</string>
+ <string name="tl_diary_updated">Rewrote today\'s diary</string>
+ <string name="tl_memory_updated">Updated a memory: %1$s</string>
+ <string name="tl_plan_today_updated">Revised today\'s plan</string>
+ <string name="tl_plan_tomorrow_updated">Revised tomorrow\'s plan</string>
<string name="tl_open">Open ›</string>
<string name="tl_show_all">Everything</string>
<string name="tl_show_talk">Talk only</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 277e632..32358fc 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -508,7 +508,6 @@
<string name="tl_woke">提醒到点:%1$s</string>
<string name="tl_notified">一条通知值得处理,开始做</string>
<string name="tl_friend_task">另一台设备的 Andee 交来一件事</string>
- <string name="tl_reviewed_none">复盘了一遍,没有要记的</string>
<string name="tl_reviewed">复盘了一遍,记下 %1$s 处</string>
<string name="tl_folded">收起了一个话题:%1$s</string>
<string name="tl_diary">写了今天的日记</string>
@@ -535,6 +534,10 @@
<string name="tl_morning">早上想好了今天的打算</string>
<string name="tl_held">收到 %1$s 的通知,正在忙,先放着</string>
<string name="tl_capped">收到 %1$s 的通知,这个小时看得太多了,先放着</string>
+ <string name="tl_diary_updated">改写了今天的日记</string>
+ <string name="tl_memory_updated">更新了记忆:%1$s</string>
+ <string name="tl_plan_today_updated">改了今天的打算</string>
+ <string name="tl_plan_tomorrow_updated">改了明天的打算</string>
<string name="tl_open">打开 ›</string>
<string name="tl_show_all">全部</string>
<string name="tl_show_talk">只看对话</string>
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainEvent.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainEvent.kt
index ea787c4..dd5477c 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainEvent.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainEvent.kt
@@ -19,6 +19,10 @@ data class BrainEvent(
val detail: String = "",
/** What the row opens, when there is something to open: a wiki article's id. */
val ref: String = "",
+ /** It rewrote something that was already there (a memory of the same name, today's diary, a day's plan). */
+ val updated: Boolean = false,
+ /** [Kind.REVIEWED] only: what the review wrote, one event each — the row's detail. */
+ val items: List<BrainEvent> = emptyList(),
) {
enum class Kind {
/** A todo came due and woke it. */
@@ -45,6 +49,13 @@ data class BrainEvent(
*/
fun fromTool(method: String, args: JSONObject, result: Any?): BrainEvent? {
val r = result as? JSONObject
+ // A rewrite that changed nothing is not an event: the timeline is for what happened.
+ if (r?.optBoolean("unchanged") == true) return null
+ val upd = r?.optBoolean("overwrote") == true || r?.optBoolean("replaced") == true
+ return fromToolInner(method, args, r)?.copy(updated = upd)
+ }
+
+ private fun fromToolInner(method: String, args: JSONObject, r: JSONObject?): BrainEvent? {
fun ok(key: String) = r == null || !r.has(key) || r.optBoolean(key)
val action = args.optString("action")
return when (method) {
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
index 6e63251..b346c2c 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
@@ -508,7 +508,8 @@ class LocalBrain(
busy.set(true)
currentKind = kind
aimMisses = 0
- turnRecords = 0
+ reviewItems = if (kind.silent) mutableListOf() else null
+ if (!kind.silent) justSwept = false
when (kind) {
TurnKind.WAKE -> emit(BrainEvent(BrainEvent.Kind.WOKE, WakeText.what(text)))
TurnKind.NOTIFY -> emit(BrainEvent(BrainEvent.Kind.NOTIFIED, detail = text.take(400)))
@@ -567,7 +568,13 @@ class LocalBrain(
// is no longer the current one.
if (gen == generation.get()) applyPendingFolds() else pendingFolds.clear()
if (kind == TurnKind.SWEEP) onSweepSpent(turnTokens)
- if (kind.silent && gen == generation.get()) emit(BrainEvent(BrainEvent.Kind.REVIEWED, turnRecords.toString()))
+ // One row per review, listing what it wrote; nothing at all when it wrote nothing.
+ val reviewed = reviewItems
+ reviewItems = null
+ if (reviewed != null && reviewed.isNotEmpty() && gen == generation.get()) {
+ emit(BrainEvent(BrainEvent.Kind.REVIEWED, reviewed.count { it.kind != BrainEvent.Kind.WIKI_READ }.toString(), items = reviewed))
+ }
+ if (kind == TurnKind.SWEEP) justSwept = true
if (gen == generation.get()) {
drainWakes()
maybeHarvest()
@@ -634,8 +641,19 @@ class LocalBrain(
/** Loop thread only. The closing words of a [TurnKind.WORK] turn; read by [work]'s callback. Never spoken. */
private var workSummary: String? = null
- /** Loop thread only. Writes to its own record this turn, for the review's summary event. Reset per turn. */
- private var turnRecords = 0
+ /**
+ * Loop thread only. While a review runs, its writes are gathered here instead of each becoming a row: a review
+ * is one thing that happened, and ten rows of it drowned everything else in the timeline. Null when not in a
+ * review. Folds land after the turn's body, so this lives until the summary row is emitted.
+ */
+ private var reviewItems: MutableList<BrainEvent>? = null
+
+ /**
+ * Loop thread only. The last turn was a sweep and nothing has been said since. A harvest that follows at once
+ * — the sweep's own rebuilt history is often what puts the context over budget — then only summarises: the
+ * notebook was just brought up to date, and going through the same rules again wrote everything twice.
+ */
+ private var justSwept = false
/** Loop thread only. Coordinate taps in a row whose screen did not change; see [AimHints]. Reset per turn. */
private var aimMisses = 0
@@ -1196,7 +1214,7 @@ class LocalBrain(
val result = dispatchWithTimeout(method, args, tc.id, silent, untrusted)
if (currentKind == TurnKind.WORK) workCalls += WorkCall(method, args.optString("action"), tc.id, landed(result))
- BrainEvent.fromTool(method, args, result)?.let { if (it.kind != BrainEvent.Kind.WIKI_READ && it.kind != BrainEvent.Kind.WIKI_SHOWN) turnRecords++; emit(it) }
+ BrainEvent.fromTool(method, args, result)?.let(::emit)
if (AimHints.isTap(method) && result is JSONObject) {
val missed = result.has("screen_changed") && !result.optBoolean("screen_changed", true)
aimMisses = if (method == "screen.tap" || method == "screen.long_press") { if (missed) aimMisses + 1 else 0 } else if (missed) aimMisses else 0
@@ -1229,7 +1247,11 @@ class LocalBrain(
return NOT_DONE_KEYS.none { o.has(it) && o.opt(it) == false }
}
- private fun emit(e: BrainEvent) = runCatching { host.event(e) }.onFailure { host.logWarn(TAG, "event ${e.kind} not shown", it) }
+ private fun emit(e: BrainEvent) {
+ // Inside a review: gather it for the review's one row. Reading during a review is not worth a line.
+ reviewItems?.let { if (e.kind != BrainEvent.Kind.WIKI_READ) it += e; return }
+ runCatching { host.event(e) }.onFailure { host.logWarn(TAG, "event ${e.kind} not shown", it) }
+ }
private fun dispatchWithTimeout(method: String, params: JSONObject, callId: String, silent: Boolean, untrusted: Boolean): Any? {
val declared = params.optLong("timeout_ms", 0L)
@@ -1719,7 +1741,7 @@ class LocalBrain(
"reviewing before trimming",
)
lastHarvestAtSize = history.size
- launch(HARVEST_INSTRUCTION, TurnKind.HARVEST)
+ launch(if (justSwept) HARVEST_SUMMARY_ONLY else HARVEST_INSTRUCTION, TurnKind.HARVEST)
}
/**
@@ -2042,6 +2064,16 @@ Up to three topics per review. If `fold_topic` refuses, the reason names the con
"write \"what future-you must know in order to take over\".\n" +
"Finish items 1-6 first, and write that summary last."
+ /** [HARVEST_INSTRUCTION] right after a sweep: the notebook is current, so only the summary is asked for. */
+ private const val HARVEST_SUMMARY_ONLY =
+ "(to yourself · the context is nearly full, time to wrap up)\n" +
+ "You are not facing the user now, and nobody is watching you. You reviewed this conversation a moment ago and the " +
+ "notebook is up to date, so write nothing to it now.\n" +
+ "Do not reply to the user, make no sound, do not touch the device.\n\n" +
+ "Write only a summary of no more than 300 words: what has happened so far, how far it got, what the next step is, " +
+ "and whether anything is hanging without an answer. The conversation above is about to be deleted from the " +
+ "context, leaving only your summary, so write \"what future-you must know in order to take over\"."
+
/** How long a topic summary may be. Long enough to carry "where it got to". */
private const val MAX_TOPIC_SUMMARY_CHARS = 1200
diff --git a/core/src/main/kotlin/net/kuafuai/andee/config/LifeTools.kt b/core/src/main/kotlin/net/kuafuai/andee/config/LifeTools.kt
index 2245925..f7693b4 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/LifeTools.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/LifeTools.kt
@@ -48,9 +48,13 @@ class LifeTools(
private fun selfNote(a: JSONObject): JSONObject = when (a.optString("action", "get")) {
"get" -> self.narrative()?.let { JSONObject().put("text", it.text).put("version", it.version).put("by_user", it.byUser) }
?: JSONObject().put("text", "").put("note", "You have not written yourself down yet. Do it once you know what you are doing here.")
- "write" -> self.setNarrative(a.optString("text"), byUser = false)
- ?.let { JSONObject().put("written", false).put("reason", it) }
- ?: JSONObject().put("written", true).put("version", self.narrative()!!.version)
+ "write" -> {
+ val before = self.narrative()?.text?.trim()
+ self.setNarrative(a.optString("text"), byUser = false)
+ ?.let { JSONObject().put("written", false).put("reason", it) }
+ ?: JSONObject().put("written", true).put("version", self.narrative()!!.version)
+ .put("replaced", before != null).put("unchanged", before == a.optString("text").trim())
+ }
else -> throw IllegalArgumentException("action is get or write")
}
@@ -96,9 +100,12 @@ class LifeTools(
"read" -> JSONObject().put("pages", JSONArray().apply {
self.diary(a.optInt("limit", 3).coerceIn(1, 14)).forEach { put(JSONObject().put("date", it.date).put("text", it.text)) }
})
- "write" -> self.writeDiary(a.optString("text"), callIdsToday())
- ?.let { JSONObject().put("written", false).put("reason", it) }
- ?: JSONObject().put("written", true)
+ "write" -> {
+ val before = self.diary(1).firstOrNull()?.takeIf { it.date == self.today() }?.text?.trim()
+ self.writeDiary(a.optString("text"), callIdsToday())
+ ?.let { JSONObject().put("written", false).put("reason", it) }
+ ?: JSONObject().put("written", true).put("replaced", before != null).put("unchanged", before == a.optString("text").trim())
+ }
else -> throw IllegalArgumentException("action is read or write")
}
diff --git a/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt b/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
index 79e88ec..6ae9c75 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
@@ -287,7 +287,11 @@ class Plans(
val d = Day(date, intent, kept + fresh, quiet, clock(), dropped)
putDay(root, d)
save(root)
+ // Whether this write changed anything — the timeline shows an unchanged rewrite as nothing.
+ val unchanged = old != null && old.intent == d.intent && old.quiet == d.quiet &&
+ old.items.filter { it.status == "planned" }.map { Triple(it.time, it.slot, it.what) } == fresh.map { Triple(it.time, it.slot, it.what) }
JSONObject().put("written", true).put("date", date).put("items", fresh.size).put("refused", refused)
+ .put("replaced", old != null).put("unchanged", unchanged)
.put(
"note",
(if (interrupting > bubblesPerDay) "The user's setting allows $bubblesPerDay bubbles a day; the rest will be skipped. " else "") +
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt
new file mode 100644
index 0000000..caf8272
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt
@@ -0,0 +1,87 @@
+package net.kuafuai.andee.brain
+
+import com.sun.net.httpserver.HttpServer
+import net.kuafuai.andee.config.BrainConfig
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+import java.lang.reflect.Proxy
+import java.net.InetSocketAddress
+import java.util.Locale
+import java.util.concurrent.TimeUnit
+
+/**
+ * A review is one row in the timeline, not one per write (10-29: a sweep and the harvest after it made eighteen
+ * rows out of one quiet afternoon). Rewrites that changed nothing are not events at all.
+ */
+class ReviewEventsTest {
+
+ @Test fun anUnchangedRewriteIsNotAnEventAndARewriteSaysSo() {
+ assertNull(BrainEvent.fromTool("note.diary", JSONObject().put("action", "write"), JSONObject().put("written", true).put("unchanged", true)))
+ val upd = BrainEvent.fromTool("note.remember", JSONObject().put("name", "x"), JSONObject().put("saved", true).put("overwrote", true))!!
+ assertTrue(upd.updated)
+ val fresh = BrainEvent.fromTool("note.remember", JSONObject().put("name", "y"), JSONObject().put("saved", true).put("overwrote", false))!!
+ assertEquals(false, fresh.updated)
+ }
+
+ private val requests = mutableListOf<JSONObject>()
+ private val events = mutableListOf<BrainEvent>()
+ private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
+ createContext("/chat/completions") { ex ->
+ val n = synchronized(requests) { requests += JSONObject(ex.requestBody.readBytes().toString(Charsets.UTF_8)); requests.size }
+ fun call(id: String, args: String) = JSONObject().put("id", id).put("type", "function")
+ .put("function", JSONObject().put("name", "remember").put("arguments", args))
+ val msg = if (n == 1) {
+ JSONObject().put("role", "assistant").put("content", "")
+ .put("tool_calls", JSONArray().put(call("a", """{"name":"m1"}""")).put(call("b", """{"name":"m2"}""")))
+ } else JSONObject().put("role", "assistant").put("content", "done")
+ val out = JSONObject().put("choices", JSONArray().put(JSONObject().put("message", msg)))
+ .put("usage", JSONObject().put("prompt_tokens", 1).put("completion_tokens", 1)).toString().toByteArray()
+ ex.sendResponseHeaders(200, out.size.toLong())
+ ex.responseBody.use { it.write(out) }
+ }
+ start()
+ }
+ private val trace = File.createTempFile("trace", "").also { it.delete(); it.mkdirs() }
+ private val rows = (1..6).map { i -> ScrollRow(isUser = i % 2 == 1, isAssistant = i % 2 == 0, text = "line $i", ts = 1_000L * i, topicId = null, handle = i) }
+
+ private val host = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(BrainHost::class.java)) { _, m, args ->
+ when (m.name) {
+ "text" -> (args[0] as BrainText).name
+ "locale" -> Locale.ENGLISH
+ "maxSteps" -> 10
+ "persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex" -> ""
+ "scrollback" -> rows
+ "toolLists" -> listOf(JSONArray().put(JSONObject().put("name", "remember").put("method", "note.remember").put("description", "r")
+ .put("parameters", JSONObject().put("type", "object").put("properties", JSONObject()))))
+ "methodOf" -> "note.remember"
+ "dispatch" -> JSONObject().put("saved", true).put("overwrote", false)
+ "event" -> { synchronized(events) { events += args[0] as BrainEvent }; null }
+ "traceDir" -> trace
+ else -> null
+ }
+ } as BrainHost
+
+ private val brain = LocalBrain(
+ BrainConfig(BrainConfig.BRAIN_LOCAL, "key", "http://127.0.0.1:${server.address.port}", "m", false, "low"),
+ host, onProgress = {}, onFinal = {},
+ )
+
+ @After fun tearDown() { brain.stop(); server.stop(0) }
+
+ @Test fun aReviewIsOneRowListingWhatItWrote() {
+ brain.runSweep()
+ val until = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(20)
+ while (synchronized(events) { events.isEmpty() } && System.currentTimeMillis() < until) Thread.sleep(50)
+ Thread.sleep(300)
+ val e = synchronized(events) { events.toList() }
+ assertEquals(listOf(BrainEvent.Kind.REVIEWED), e.map { it.kind })
+ assertEquals(listOf("m1", "m2"), e.single().items.map { it.subject })
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Sweep.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Sweep.kt
index 9202587..40de1a9 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Sweep.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Sweep.kt
@@ -36,7 +36,14 @@ object Sweep {
private val metaFile get() = AppDirs.file("sweep.json")
private val lock = Any()
- @Volatile private var lastAttemptAt = 0L
+ /**
+ * On disk, like the phone's `Notebook.lastSweepAt`: kept in memory only, it was forgotten by every restart, and the
+ * first tick after one reviewed a conversation that had already been reviewed — measured 10-29, the same stretch
+ * gone over twice, every write in it made again.
+ */
+ private var lastAttemptAt: Long
+ get() = runCatching { AppDirs.file("last_sweep_attempt").readText().trim().toLong() }.getOrDefault(0L)
+ set(v) { runCatching { AppDirs.file("last_sweep_attempt").writeText(v.toString()) } }
fun enabled(): Boolean = Settings.get("sweep").lowercase() != "off"
private fun quietMs(): Long =
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/TimelineEvents.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/TimelineEvents.kt
index 1a60208..046adc9 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/TimelineEvents.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/TimelineEvents.kt
@@ -22,15 +22,27 @@ object TimelineEvents {
private fun t(z: String, e: String) = if (zh) z else e
fun brain(e: BrainEvent) {
+ val detail = when (e.kind) {
+ // A review is one row; what it wrote is the detail, one line each.
+ BrainEvent.Kind.REVIEWED -> e.items.joinToString("\n") { "- " + line(it) }
+ BrainEvent.Kind.CARE -> ""
+ BrainEvent.Kind.TODO -> e.detail.takeIf { it.isNotBlank() }?.let { t("时间:$it", "At: $it") }.orEmpty()
+ else -> e.detail
+ }
+ Scrollback.event(e.kind.name, line(e), detail, e.ref)
+ }
+
+ /** One event in words. An [BrainEvent.updated] write says so, so a rewrite does not read as something new. */
+ private fun line(e: BrainEvent): String {
val s = e.subject
- val text = when (e.kind) {
+ val u = e.updated
+ return when (e.kind) {
BrainEvent.Kind.WOKE -> t("提醒到点:$s", "Reminder due: $s")
BrainEvent.Kind.NOTIFIED -> t("一条通知值得处理,开始做", "A notification was worth acting on")
BrainEvent.Kind.FRIEND_TASK -> t("另一台设备的 Andee 交来一件事", "Another Andee handed over a task")
- BrainEvent.Kind.REVIEWED -> if (s == "0" || s.isEmpty()) t("复盘了一遍,没有要记的", "Reviewed the conversation; nothing to keep")
- else t("复盘了一遍,记下 $s 处", "Reviewed the conversation; kept $s things")
+ BrainEvent.Kind.REVIEWED -> t("复盘了一遍,记下 $s 处", "Reviewed the conversation; kept $s things")
BrainEvent.Kind.FOLDED -> t("收起了一个话题:$s", "Put away a topic: $s")
- BrainEvent.Kind.DIARY -> t("写了今天的日记", "Wrote today's diary")
+ BrainEvent.Kind.DIARY -> if (u) t("改写了今天的日记", "Rewrote today's diary") else t("写了今天的日记", "Wrote today's diary")
BrainEvent.Kind.SELF -> t("改写了自我描述", "Rewrote who it is")
BrainEvent.Kind.WIKI -> t("写进维基:$s", "Wrote to the wiki: $s")
BrainEvent.Kind.WIKI_READ -> t("翻出了维基:$s", "Opened a wiki article: $s")
@@ -41,16 +53,13 @@ object TimelineEvents {
"done" -> t("一件在意的事做完了", "A care is done")
else -> t("放下了一件在意的事", "Let a care go")
}
- BrainEvent.Kind.MEMORY -> t("记住了:$s", "Remembered: $s")
+ BrainEvent.Kind.MEMORY -> if (u) t("更新了记忆:$s", "Updated a memory: $s") else t("记住了:$s", "Remembered: $s")
BrainEvent.Kind.TODO -> t("排了一件待办:$s", "Set a todo: $s")
- BrainEvent.Kind.PLAN -> t("写了${if (s == "tomorrow") "明天" else "今天"}的打算", "Wrote ${if (s == "tomorrow") "tomorrow's" else "today's"} plan")
- }
- val detail = when (e.kind) {
- BrainEvent.Kind.CARE -> ""
- BrainEvent.Kind.TODO -> e.detail.takeIf { it.isNotBlank() }?.let { t("时间:$it", "At: $it") }.orEmpty()
- else -> e.detail
+ BrainEvent.Kind.PLAN -> {
+ val day = if (s == "tomorrow") t("明天", "tomorrow's") else t("今天", "today's")
+ if (u) t("改了${day}的打算", "Revised $day plan") else t("写了${day}的打算", "Wrote $day plan")
+ }
}
- Scrollback.event(e.kind.name, text, detail, e.ref)
}
fun body(kind: Body, text: String, detail: String = "") = Scrollback.event(kind.name, text, detail)