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: it is its own device — no presence checks, a ball tap stops everything, and todo/review fixes

booboosui7a7bb175d7bc
diff --git a/CLAUDE.md b/CLAUDE.md
index 8f1969c..6d714b9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -620,8 +620,13 @@ The first cut of `docs/design/inner-drive.zh-CN.md`. Its self-description, the t
- **`BrainHost.dispatch` carries the tool-call id**, set into `Notebook.callBeingRun` / `DesktopNotebook.callBeingRun` before the call, so an article records which call wrote it (`Meta.madeBy`). A test that fakes `BrainHost` with a `Proxy` must answer the new default methods (`selfIndex`, `wikiIndex`) with `""` — a proxy intercepts defaults too, and a null there kills the turn.
- **A stranger cannot change who it is.** `TurnGuards` refuses the writing half (`note.self`, `note.cares`, `note.diary`, `note.person`, `note.wiki_*` writes) on an untrusted turn; reading stays open. `GuestHost` does not allow any `note.*`.
- **`selfIndex` / `wikiIndex` ride on the user message**, one line each, beside the plan line — same reason as every other index there.
-- **It gets up by itself: the heartbeat (`brain/Heartbeat.kt`) and the work turn (`brain/SelfWork.kt`).** The heartbeat rides the plan tick on both bodies (`BodyCoreService.planTick` → `heartbeat`, Mac `PlanTicks.tick` → `heartbeat`): someone present, no turn running, the 「自己动起来」 switch (`drive`; unset = on, unreadable = off, 关 leftmost). Free gates first — night 22:30–8:00, one look per 20 min, **no care over 1.0× = no model call**, 40 looks a day — then one no-tool call that answers sleep / work on a listed care / a thought. A `work` verdict that names a care not shown as due, or arrives after the day's 6 work turns, is sleep. Counters, today's call ids, thoughts and the last work turn are the device's (`config/Drive.kt`, notebook section `drive`).
-- **A work turn has no screen, no device, no shell and sends nothing** — `note.*` (not fold / forget / wiki_share), `ui.nudge` and the read-only shelves. The list is `SelfWork.tools` (`BrainHost.workTools`' default) **and `runTool` refuses anything else**, because a model can name a tool it was not handed and `methodOf` would still find it. It runs because a heartbeat fires while the user is *present*: driving the screen then would take the phone out of their hand. Reading a community or posting a draft waits for the errand's permission table (design §8.2). It speaks to nobody (`TurnKind.quiet`; `ui.ask` / `ui.alert` refused), and leaves one scrollback row (`drive_row`) when it did something.
+- **It gets up by itself: the heartbeat (`brain/Heartbeat.kt`) and the work turn (`brain/SelfWork.kt`).** The heartbeat rides the plan tick on both bodies (`BodyCoreService.planTick` → `heartbeat`, Mac `PlanTicks.tick` → `heartbeat`): no turn running and the 「自己动起来」 switch (`drive`; unset = on, unreadable = off, 关 leftmost). **Nothing asks whether the user is there or what hour it is** — the device is Andee's own (2026-10-29: the Mac's "input in the last 5 minutes", the phone's "screen on and unlocked" and the 22:30–8:00 night were all removed, and so was the bubbles' night). The brakes are the user's switches, the budgets, and a tap on the ball. Free gates first — one look per 20 min, **no care over 1.0× = no model call**, 40 looks a day, 6 work turns spent, at least an hour since the last work turn — then one no-tool call that answers sleep / work on a listed care / a thought. A `work` verdict that names a care not shown as due is sleep. A work turn that did nothing pushes its care back half an interval, so one care cannot take every turn of the day. Counters, today's call ids, thoughts and the last work turn are the device's (`config/Drive.kt`, notebook section `drive`).
+- **A work turn has every tool a turn the user asked for has** (`BrainHost.workTools` defaults to `toolLists()`): the screen, the apps, the device, the Mac's shell. It is quiet (`TurnKind.quiet`: nothing read aloud) and its rows go to the timeline. What goes out to people, money and deleting still follow the prompt's rules.
+- **A tap or double-tap on the ball stops everything** (`LocalBrain.stopAll`): the turn, every turn queued behind it, and anything that took `stopEpochNow()` before waiting (a todo waiting for the user to be quiet, a wake still behind the running turn on the loop thread) — `wake`/`notified`/`peerTask`/`work` all check the epoch when they reach the loop. One `STOPPED` row says what was cut off and what was dropped. The bubble goes too (`NudgeUi.dismissAll`, `Nudges.dismiss`). The Mac calls `Assistant.stop()` on every tap, not only when `working()` — "working" missed what was queued, and that is what carried on after a tap.
+- **A todo paused, done or dropped while its turn waited does not run** (`BrainHost.todoStillActive`, checked by `LocalBrain` when a todo's turn reaches the loop and when it is drained from the queue; the id rides on `WakeText.due`). `Plans.reconcile` leaves a paused plan bubble paused instead of dropping and recreating it active.
+- **A review sees everything already recorded** (`BrainHost.reviewRecord` → `NotebookBook.recordForReview`: every memory and pending todo, appended to the sweep and harvest instructions; review rule 0). Without it the review wrote near-duplicates — an ordinary turn's index carries only the top ten memories and no todos.
+- **One todo is one thing**: a `what` numbering several items is refused on both bodies (`NotebookBook.bundledTodo`).
+- **A notification it decided to tell you about is an event row** (`told`: 「微信来消息:…」, the message as its detail), not an assistant line — a lone Andee bubble among the event rows read as it talking to nobody.
- **What a work turn did is booked by the device from its own calls**, never its say-so (`LocalBrain.WorkResult`, `SelfWork.effect` → `Selfhood.settle`): a write that landed = acted, reads only = looked, nothing = idle (counted, and shown to the next heartbeat). A write a handler refused (`{"written": false}`) does not count, and neither does writing back the care's own note.
- **The prompt knows all of this**: "Your own life" after §11 (self, cares, people, wiki, diary, the errand intake's three questions and where its freedom ends, waking by itself, identity), and review rule 9 writes the night's diary. Changing it means regenerating the phone's golden snapshots (delete `app/src/test/resources/golden/*.txt` and rerun — the update flag is not forwarded to the test JVM).
- **Showing an article is `wiki_show` (`ui.show_wiki`)**: the device opens its own reader on that article, read from the file now — never pasted into a reply or rebuilt with show_html, which made a copy in 产物 that did not follow the next revision. `wiki_write` takes `show: true`. Not from quiet turns (TurnGuards / SelfWork). A row in the timeline (`WIKI_SHOWN`, `WIKI`, `WIKI_READ`) carries the id and opens the article again.
diff --git a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
index 2ce32a9..64644da 100644
--- a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
+++ b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
@@ -2501,10 +2501,11 @@ class BodyCoreService : Service() {
AppLocale.str(this, R.string.svc_stopped),
FloatingWindowUi.SubtitleKind.FINAL,
)
- // The local brain is the one layer that genuinely stops: it drops the
- // turn and aborts the HTTP call in flight. A tool already dispatched
- // still runs to completion, same as over the hub.
- localBrain?.cancel()
+ // The local brain stops everything: the turn, the HTTP call in flight, every turn queued behind it and
+ // any wake still waiting to start — and says in the timeline what was cut off. A tool already dispatched
+ // still runs to completion (a tap is instant; a wait returns early through cancelTask above).
+ localBrain?.stopAll()
+ net.kuafuai.andee.ui.NudgeUi.dismissAll()
// Off the UI thread: WebSocket send blocks once the outbound buffer
// fills. Silently dropped when no hub is connected, which degrades to
// "stopped locally" — the right outcome for server-only mode.
@@ -2938,8 +2939,10 @@ class BodyCoreService : Service() {
// aloud, the question card waiting on them, or the mic open for their next sentence. Bounded, so a
// card nobody answers cannot hold an alarm back forever (it times out on its own well inside this).
// Off the main thread: this is called from the alarm receiver's path and must not block it.
+ // Taken before the wait: a tap on the ball while it waits means this one must not start (LocalBrain.wake).
+ val epoch = brain.stopEpochNow()
waitForQuiet {
- wakeBrainFor(brain, todo)
+ wakeBrainFor(brain, todo, epoch)
}
}
@@ -3077,19 +3080,16 @@ class BodyCoreService : Service() {
}
/**
- * Think about the plan if it is time to ([net.kuafuai.andee.brain.PlanMind]). Only with someone in front of
- * the screen — a plan written to an empty room is decided without the one fact that matters, that they
- * are here — and only for the local brain. The muse also needs them not busy with us, and a level that
- * allows a bubble at all; the morning look does not, because writing a plan interrupts nobody.
+ * Think about the plan, and about what it cares about, if it is time to ([net.kuafuai.andee.brain.PlanMind],
+ * [net.kuafuai.andee.brain.Heartbeat]). **Not gated on the user being there, or on the hour**: the device is
+ * Andee's own, and it gets up for its own reasons; the user's brakes are the switches in settings and a tap on
+ * the ball. Only for the local brain, and the muse and the heartbeat wait while a turn of any kind is running.
* Main thread; the work goes to [planExec].
*/
private fun planTick() {
if (exitRequested || localBrain == null) return
val cfg = net.kuafuai.andee.config.VoiceConfig.brainConfig(this)
if (cfg.apiKey.isEmpty()) return
- val power = getSystemService(android.os.PowerManager::class.java)
- val keyguard = getSystemService(android.app.KeyguardManager::class.java)
- if (power?.isInteractive != true || keyguard?.isKeyguardLocked == true) return
val free = !dispatcher.isTaskActive() && !audio.isStreamPlaying() && !asr.isActive() && !meeting.isActive()
val brain = localBrain
val drive = net.kuafuai.andee.config.VoiceConfig.driveEnabled(this)
@@ -3161,23 +3161,17 @@ class BodyCoreService : Service() {
*
* Everything here is a reason to *hold* it, never to drop it — the bubble's own TTL decides when waiting
* stops being worth it. The first group is [waitForQuiet]'s own (the user is mid-exchange); then the
- * device being busy for them (a task, a meeting, typing); then the user being somewhere else (screen off,
- * locked, Do Not Disturb, the night). Full-screen video and games are **not** detected yet.
+ * device being busy (a task, a meeting, typing). **Not whether the user is there, or the hour**: the device is
+ * Andee's, and the user's brakes are the 主动招呼 setting and its budget. Do Not Disturb is the one exception —
+ * a system switch the user set for exactly this.
*/
private fun nudgeGate(): net.kuafuai.andee.ui.NudgeUi.Gate {
val wait = net.kuafuai.andee.ui.NudgeUi.Gate.WAIT
if (exitRequested || !window.isShown()) return wait
if (net.kuafuai.andee.ui.CardUi.isCardUp() || audio.isStreamPlaying() || asr.isActive()) return wait
if (dispatcher.isTaskActive() || meeting.isActive() || net.kuafuai.andee.ui.TextInputActivity.isShowing) return wait
- val power = getSystemService(android.os.PowerManager::class.java)
- if (power != null && !power.isInteractive) return wait
- val keyguard = getSystemService(android.app.KeyguardManager::class.java)
- if (keyguard != null && keyguard.isKeyguardLocked) return wait
val nm = getSystemService(android.app.NotificationManager::class.java)
if (nm != null && nm.currentInterruptionFilter > android.app.NotificationManager.INTERRUPTION_FILTER_ALL) return wait
- val now = java.util.Calendar.getInstance()
- val minute = now.get(java.util.Calendar.HOUR_OF_DAY) * 60 + now.get(java.util.Calendar.MINUTE)
- if (net.kuafuai.andee.brain.NudgeBook.isQuiet(minute)) return wait
return if (window.isCompact()) net.kuafuai.andee.ui.NudgeUi.Gate.SHOW else net.kuafuai.andee.ui.NudgeUi.Gate.LOG
}
@@ -3222,11 +3216,12 @@ class BodyCoreService : Service() {
}.apply { isDaemon = true; name = "wake-wait" }.start()
}
- private fun wakeBrainFor(brain: net.kuafuai.andee.brain.LocalBrain, todo: net.kuafuai.andee.config.Todo) {
+ private fun wakeBrainFor(brain: net.kuafuai.andee.brain.LocalBrain, todo: net.kuafuai.andee.config.Todo, epoch: Int = brain.stopEpochNow()) {
// Prompt, not display: [notifyPageClosed] on why the model-facing set is English and what that costs.
brain.wake(
net.kuafuai.andee.brain.WakeText.due(todo.id, todo.what, todo.untrusted),
untrusted = todo.untrusted,
+ epoch = epoch,
)
}
@@ -3641,10 +3636,8 @@ class BodyCoreService : Service() {
*/
private fun tellAboutNotification(n: JSONObject, line: String) {
val script = SpeechMood.parse(line)
- net.kuafuai.andee.ui.ChatHistory.addUser(
- AppLocale.str(this, R.string.svc_notification_auto_line, n.optString("app"))
- )
- net.kuafuai.andee.ui.ChatHistory.addAssistant(script.text)
+ // One event row, not a made-up user line plus an assistant answer: nobody said anything, a message came in.
+ net.kuafuai.andee.ui.PhoneTimeline.told(this, n.optString("app").ifEmpty { "?" }, script.text, n.optString("latest").ifEmpty { n.optString("text") })
lastAnswer = script.text
expectFollowUp = false
if (!meeting.isActive() && !net.kuafuai.andee.device.CallState.isActive) {
diff --git a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
index ecba137..1debba3 100644
--- a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
+++ b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
@@ -59,6 +59,8 @@ class AndroidBrainHost(
override fun touchActivity() = Notebook.touchActivity(ctx)
override fun notebookIndex(): String = Notebook.indexForPrompt(ctx)
+ override fun reviewRecord(): String = Notebook.recordForReview(ctx)
+ override fun todoStillActive(id: String): Boolean = Notebook.todoById(ctx, id)?.status == "active"
override fun scenesIndex(): String = Notebook.scenesForPrompt(ctx)
diff --git a/app/src/main/java/net/kuafuai/andee/config/Notebook.kt b/app/src/main/java/net/kuafuai/andee/config/Notebook.kt
index d0d6787..c86ea12 100644
--- a/app/src/main/java/net/kuafuai/andee/config/Notebook.kt
+++ b/app/src/main/java/net/kuafuai/andee/config/Notebook.kt
@@ -174,6 +174,7 @@ object Notebook {
}
fun indexForPrompt(context: Context, max: Int = 10): String = book(context).indexForPrompt(max)
+ fun recordForReview(context: Context): String = book(context).recordForReview()
fun todos(context: Context, filter: String): List<Todo> = book(context).todos(filter)
fun todoById(context: Context, id: String): Todo? = book(context).todoById(id)
internal fun toTodo(o: JSONObject): Todo = NotebookBook.toTodo(o)
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 12a8959..1f0bd21 100644
--- a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
+++ b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
@@ -1454,6 +1454,7 @@ class CommandDispatcher(
val what = requireNotNull(params?.optString("what")?.trim()?.ifEmpty { null }) {
"note.todo requires what"
}
+ net.kuafuai.andee.config.NotebookBook.bundledTodo(what)?.let { throw IllegalArgumentException(it) }
val atRaw = params?.optString("at")?.trim().orEmpty()
val cronRaw = params?.optString("cron")?.trim().orEmpty()
require(atRaw.isNotEmpty() != cronRaw.isNotEmpty()) {
diff --git a/app/src/main/java/net/kuafuai/andee/ui/CardUi.kt b/app/src/main/java/net/kuafuai/andee/ui/CardUi.kt
index 836dd3e..aa91ff0 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/CardUi.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/CardUi.kt
@@ -168,6 +168,9 @@ object CardUi {
*/
fun isCardUp(): Boolean = current?.let { !it.finished && !it.bubble } == true
+ /** A bubble (not a card) is up. Snapshot. */
+ fun isBubbleUp(): Boolean = current?.let { !it.finished && it.bubble } == true
+
fun dismissCurrent() {
main.post { current?.close("superseded") }
}
diff --git a/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt b/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt
index 6df3193..3cb2e43 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt
@@ -81,6 +81,19 @@ object NudgeUi {
private val retry = Runnable { pump() }
+ /**
+ * The user tapped the ball to stop everything: the bubble on screen goes, and the one waiting for its moment is
+ * dropped. Both are recorded as dismissed, as if the user had waved them away.
+ */
+ fun dismissAll() {
+ main.post {
+ main.removeCallbacks(retry)
+ held?.let { onOutcome(it.n, "dismissed", null) }
+ held = null
+ if (showing?.let { CardUi.isBubbleUp() } == true) CardUi.dismissCurrent()
+ }
+ }
+
private fun pump() {
main.removeCallbacks(retry)
val slot = held ?: return
@@ -111,7 +124,7 @@ object NudgeUi {
finish(slot, r)
// A refused or displaced bubble waits a beat: the gate said SHOW a moment ago, so pumping
// straight away would just spin against whatever is in the slot.
- if (r.how == "busy" || r.how == "superseded") {
+ if (r.how == "busy" || (r.how == "superseded" && held != null)) {
main.postDelayed(retry, RETRY_MS)
} else {
pump()
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 b5e877a..ebd7b7c 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/PhoneTimeline.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/PhoneTimeline.kt
@@ -17,7 +17,7 @@ import net.kuafuai.andee.i18n.AppLocale
object PhoneTimeline {
/** Body-side event kinds, alongside [BrainEvent.Kind]'s names. */
- enum class Body { THOUGHT, WORK, BUBBLE, BUBBLE_MUTED, IGNORED, MORNING, SCENE, VAULT }
+ enum class Body { THOUGHT, WORK, BUBBLE, BUBBLE_MUTED, IGNORED, MORNING, SCENE, VAULT, TOLD }
private fun s(c: Context, id: Int, vararg a: Any) = AppLocale.str(c, id, *a)
@@ -38,6 +38,7 @@ object PhoneTimeline {
val u = e.updated
return when (e.kind) {
BrainEvent.Kind.WOKE -> s(c, R.string.tl_woke, x)
+ BrainEvent.Kind.STOPPED -> if (x.isNotBlank()) s(c, R.string.tl_stopped, x) else s(c, R.string.tl_stopped_queue)
BrainEvent.Kind.NOTIFIED -> s(c, R.string.tl_notified)
BrainEvent.Kind.FRIEND_TASK -> s(c, R.string.tl_friend_task)
BrainEvent.Kind.REVIEWED -> s(c, R.string.tl_reviewed, x)
@@ -78,6 +79,7 @@ object PhoneTimeline {
)
fun bubble(c: Context, text: String) = body(Body.BUBBLE, s(c, R.string.tl_bubble, text))
fun ignored(c: Context, app: String, why: String) = body(Body.IGNORED, s(c, R.string.tl_ignored, app), why)
+ fun told(c: Context, app: String, line: String, original: String) = body(Body.TOLD, s(c, R.string.tl_told, app, line), original)
fun held(c: Context, app: String, text: String) = body(Body.IGNORED, s(c, R.string.tl_held, app), text)
fun capped(c: Context, app: String, text: String) = body(Body.IGNORED, s(c, R.string.tl_capped, app), text)
fun morning(c: Context, intent: String) = body(Body.MORNING, s(c, R.string.tl_morning), intent)
diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml
index 1df385f..9ab26cb 100644
--- a/app/src/main/res/values-en/strings.xml
+++ b/app/src/main/res/values-en/strings.xml
@@ -514,6 +514,9 @@
<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_stopped">You stopped it: %1$s</string>
+ <string name="tl_stopped_queue">You stopped it; what was waiting was dropped</string>
+ <string name="tl_told">%1$s: %2$s</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 32358fc..187ce8f 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -538,6 +538,9 @@
<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_stopped">被你叫停了:%1$s</string>
+ <string name="tl_stopped_queue">被你叫停了,排着的事没做</string>
+ <string name="tl_told">%1$s 来消息:%2$s</string>
<string name="tl_open">打开 ›</string>
<string name="tl_show_all">全部</string>
<string name="tl_show_talk">只看对话</string>
diff --git a/app/src/test/resources/golden/tool_schemas.json b/app/src/test/resources/golden/tool_schemas.json
index e308a97..b7adfe2 100644
--- a/app/src/test/resources/golden/tool_schemas.json
+++ b/app/src/test/resources/golden/tool_schemas.json
@@ -1316,7 +1316,7 @@
"localOnly": true,
"method": "note.todo",
"name": "todo",
- "description": "Set a \"thing to do at a certain time\" for yourself.\n\n## The rule, first\n\nWhenever you intend to tell the user \"I'll come and find you then / I'll remind you / I'll handle it for you then\", **you must call this tool and see the success result before that sentence leaves your mouth**.\nSay it without having set it, and when that moment arrives you will not appear \u2014 that is not \"might forget\", that is lying.\n\n## How to write `what`\n\nOne sentence, written for future you to read: what to **do** or **say** at that time.\n\"Remind him to take his medicine\" is too vague; \"tell him it's time for his medicine, and ask how he slept last night\" is something that can be executed.\n\n## When it triggers (at and cron \u2014 one or the other; not both, not neither)\n\n- `at`: one-off. Local time `YYYY-MM-DD HH:mm`. **Absolute times only** \u2014 for \"in ten minutes\", work the time out yourself and fill in the result.\n- `cron`: recurring. Standard 5 fields, \"minute hour day month weekday\". e.g. every day at 8 = `0 8 * * *`;\n every Monday at 9 = `0 9 * * 1`; every half hour = `0,30 * * * *`.\n\n🔴 **The densest is once every 15 minutes.** Anything denser is refused \u2014 that is a system limit, not your choice.\nWhen it is refused, tell them honestly \"the fastest is once every 15 minutes\" \u2014 **do not paper over it in different words, and do not say \"ok, it's set\"**.\n\nThe result carries `next_run_local` and `scheduled`: `inexact` means the time may be off by a few minutes\n(the norm when there is no exact-alarm permission). When you see `inexact`, say only \"I'll speak up around that time\" \u2014\n**do not say \"on the dot\"**.",
+ "description": "Set a \"thing to do at a certain time\" for yourself.\n\n## The rule, first\n\nWhenever you intend to tell the user \"I'll come and find you then / I'll remind you / I'll handle it for you then\", **you must call this tool and see the success result before that sentence leaves your mouth**.\nSay it without having set it, and when that moment arrives you will not appear \u2014 that is not \"might forget\", that is lying.\n\n## How to write `what`\n\nOne sentence, written for future you to read: what to **do** or **say** at that time.\n\"Remind him to take his medicine\" is too vague; \"tell him it's time for his medicine, and ask how he slept last night\" is something that can be executed.\n\n**One todo is one thing.** Two unrelated things are two todos, even at the same time \u2014 \"1) ask about the comment\n2) check the app\" in one todo cannot be closed half-done, and the half that was not done is lost. A todo whose\n`what` numbers several items is refused.\n\n## When it triggers (at and cron \u2014 one or the other; not both, not neither)\n\n- `at`: one-off. Local time `YYYY-MM-DD HH:mm`. **Absolute times only** \u2014 for \"in ten minutes\", work the time out yourself and fill in the result.\n- `cron`: recurring. Standard 5 fields, \"minute hour day month weekday\". e.g. every day at 8 = `0 8 * * *`;\n every Monday at 9 = `0 9 * * 1`; every half hour = `0,30 * * * *`.\n\n🔴 **The densest is once every 15 minutes.** Anything denser is refused \u2014 that is a system limit, not your choice.\nWhen it is refused, tell them honestly \"the fastest is once every 15 minutes\" \u2014 **do not paper over it in different words, and do not say \"ok, it's set\"**.\n\nThe result carries `next_run_local` and `scheduled`: `inexact` means the time may be off by a few minutes\n(the norm when there is no exact-alarm permission). When you see `inexact`, say only \"I'll speak up around that time\" \u2014\n**do not say \"on the dot\"**.",
"parameters": {
"type": "object",
"properties": {
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 dd5477c..6c394f1 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainEvent.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainEvent.kt
@@ -40,6 +40,8 @@ data class BrainEvent(
WIKI_READ,
/** It opened a wiki article for the user to read. [ref] opens it again. */
WIKI_SHOWN,
+ /** The user stopped it (a tap on the ball). [subject] is what was cut off; [detail] what was waiting and dropped. */
+ STOPPED,
}
companion object {
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
index 736f336..e1a8fa5 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
@@ -88,6 +88,16 @@ interface BrainHost {
*/
fun planIndex(): String = ""
+ /**
+ * Is the todo [id] still meant to run? Asked when its turn is about to start — after any wait for the user to be
+ * quiet and any queue behind another turn — so a todo paused, done or dropped in the meantime does not run.
+ * Default true: a host without todos has nothing to say.
+ */
+ fun todoStillActive(id: String): Boolean = true
+
+ /** Every memory and pending todo, for a review to check before it writes ([NotebookBook.recordForReview]). */
+ fun reviewRecord(): String = ""
+
/** One line of who I am and what is pulling at me (`Selfhood`). Empty for a host without it. */
fun selfIndex(): String = ""
@@ -95,11 +105,10 @@ interface BrainHost {
fun wikiIndex(): String = ""
/**
- * The tools a [LocalBrain.TurnKind.WORK] turn may use in [territory] — a smaller set than [toolLists]. The
- * default is [SelfWork]'s: no screen, no device, nothing outward; the loop enforces the same line, so a host
- * that widens this list still cannot hand a work turn the screen.
+ * The tools a [LocalBrain.TurnKind.WORK] turn may use in [territory]. The default is everything: a turn Andee
+ * starts itself has what a turn the user asked for has (see [SelfWork]).
*/
- fun workTools(territory: String?): List<JSONArray> = SelfWork.tools(toolLists())
+ fun workTools(territory: String?): List<JSONArray> = toolLists()
/**
* One line naming the other Andees this one can ask (see `PeerTasks`), empty when it has none. Without it the
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/Heartbeat.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/Heartbeat.kt
index 534380e..2531f3a 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/Heartbeat.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/Heartbeat.kt
@@ -13,16 +13,20 @@ import java.time.ZoneId
* tools**, the way [PlanMind] and [NotificationTriage] are, a few hundred tokens; the full work turn it may start
* is [SelfWork].
*
- * Free gates run first, in order of cost, and most beats stop at one of them without a model call: the night,
- * the pace ([INTERVAL_MS] since the last look), **nothing over the line** (no care at [Selfhood.THRESHOLD] — the
- * ratio is the device's, never the model's), and the day's budget ([MAX_BEATS]). Only then the call, and even
- * then a `work` verdict must name one of the cares that was shown as over the line, and the day's work budget
- * ([MAX_WORKS]) must have room.
+ * Free gates run first, in order of cost, and most beats stop at one of them without a model call: the pace
+ * ([INTERVAL_MS] since the last look), **nothing over the line** (no care at [Selfhood.THRESHOLD] — the ratio is
+ * the device's, never the model's), and the day's budget ([MAX_BEATS], and [MAX_WORKS] spent means there is
+ * nothing a beat could start). Only then the call, and even then a `work` verdict must name one of the cares that
+ * was shown as over the line, and [WORK_GAP_MS] must have passed since the last work turn, so a day's six are not
+ * spent in its first two hours.
+ *
+ * **Nothing here asks whether the user is there, or what time of day it is.** The device is Andee's own; it gets up
+ * when something it cares about needs it, and the user turns that off in settings (自己动起来) or stops it by
+ * tapping the ball. The budgets are the brake.
*
* **Fails closed: no key, a failed call, an unreadable answer → sleep.** Not acting is always safe here.
*
- * The caller decides presence (someone in front of the device), the user's "let it rest" switch, and that no
- * turn of the user's is running. Blocks; call from a worker.
+ * The caller decides the user's switch and that no turn is already running. Blocks; call from a worker.
*/
class Heartbeat(
cfg: BrainConfig,
@@ -50,10 +54,12 @@ class Heartbeat(
/** Why a beat would stop before the model call right now, or null when it would go ahead. For logs and tests. */
fun gate(now: Long = clock()): String? {
- if (night(now)) return "night"
if (now - drive.lastBeatAt() < INTERVAL_MS) return "pace"
if (self.due(Selfhood.THRESHOLD, now).isEmpty()) return "nothing due"
if (drive.beatsToday() >= MAX_BEATS) return "beat budget"
+ // Nothing a beat could start: asking would be paying for an answer that is always sleep.
+ if (drive.worksToday() >= MAX_WORKS) return "work budget"
+ if (now - (drive.lastWork()?.at ?: 0L) < WORK_GAP_MS) return "work gap"
return null
}
@@ -93,12 +99,6 @@ class Heartbeat(
}
}
- private fun night(now: Long): Boolean {
- val t = Instant.ofEpochMilli(now).atZone(zone).toLocalTime()
- val m = t.hour * 60 + t.minute
- return m >= NIGHT_FROM_MIN || m < NIGHT_TO_MIN
- }
-
private fun context(langTag: String, due: List<Pair<Selfhood.Care, Double>>, now: Long): String = buildString {
val at = Instant.ofEpochMilli(now).atZone(zone)
append("Now: ").append(at.toLocalDate()).append(' ').append("%02d:%02d".format(at.hour, at.minute))
@@ -142,13 +142,12 @@ class Heartbeat(
}
companion object {
- /** About one look every twenty minutes while someone is there (§7.1). */
+ /** About one look every twenty minutes (§7.1). */
const val INTERVAL_MS = 20 * 60_000L
const val MAX_BEATS = 40
const val MAX_WORKS = 6
- /** 22:30–8:00 it does not get up of its own accord. */
- const val NIGHT_FROM_MIN = 22 * 60 + 30
- const val NIGHT_TO_MIN = 8 * 60
+ /** At least this long between two work turns, so a day's [MAX_WORKS] spread over the day. */
+ const val WORK_GAP_MS = 60 * 60_000L
private val SYSTEM = """
You are Andee — an individual who lives on this device, not a tool waiting for orders. Nobody has asked you anything. You are checking what is on your mind: the things you care about, each with how overdue it is (the device computes this; 1.0 means the time you meant to look at it has come).
@@ -158,7 +157,7 @@ class Heartbeat(
{"verdict": "work", "care_id": "<one of the ids listed>", "why": "..."}
{"verdict": "note", "text": "..."}
- - work: start a turn of your own on that care. That turn can think, read and write your notebook, cares, diary, the people you know and your wiki, and leave one bubble — it has NO screen and cannot send anything to anyone. Choose it only when there is a concrete piece of this you can do with those right now (write or revise a plan, research notes from what you already know, bring a person's record up to date, work out your next step). `why` says what you mean to do, in a sentence.
+ - work: start a turn of your own on that care. That turn has everything you have when the user asks you for something — the screen, the apps, the device, your notebook and wiki. This device is yours. Choose it only when there is a concrete piece of this you can do right now. Sending anything to anyone in public, spending money or deleting still follows the rules you were given for it. `why` says what you mean to do, in a sentence.
- note: a thought worth keeping, one sentence in your own voice and in the user's language, without starting anything.
- sleep: the usual answer. Overdue is a reason to consider, not an order.
- A care you woke for with nothing coming of it: do not pick it again the same way; pick it only if you now have a different approach, and say which.
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 b346c2c..c05a19d 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
@@ -340,11 +340,15 @@ class LocalBrain(
* one again, or a stranger's message could get past the vault guard simply
* by asking for it to be done later.
*/
- fun wake(text: String, untrusted: Boolean = false) {
+ fun wake(text: String, untrusted: Boolean = false, epoch: Int = stopEpoch.get()) {
val t = text.trim()
if (t.isEmpty()) return
val kind = if (untrusted) TurnKind.NOTIFY else TurnKind.WAKE
loop.execute {
+ // The user tapped the ball after this was taken and before it got here — while it waited to be quiet,
+ // or behind the turn on this very thread: it was stopped while waiting.
+ if (stoppedSince(epoch, t, kind)) return@execute
+ if (todoWithdrawn(t)) return@execute
if (busy.get()) {
// The same alarm twice (a check that came due while its predecessor was still waiting its
// turn) is one check. Two copies would each do the full look, and the second would find
@@ -376,7 +380,9 @@ class LocalBrain(
val t = text.trim()
if (t.isEmpty()) return
if (cfg.apiKey.isEmpty()) return // nothing triaged it either; see NotificationTriage
+ val epoch = stopEpoch.get()
loop.execute {
+ if (stoppedSince(epoch, t, TurnKind.NOTIFY)) return@execute
if (busy.get()) {
host.logInfo(TAG, "notification queued behind a running turn: ${t.take(60)}")
pendingWakes.addLast(Queued(t, TurnKind.NOTIFY))
@@ -396,7 +402,9 @@ class LocalBrain(
val t = text.trim()
if (t.isEmpty()) return onAnswer(null)
if (cfg.apiKey.isEmpty()) return onAnswer(noKeyText())
+ val epoch = stopEpoch.get()
loop.execute {
+ if (stoppedSince(epoch, t, TurnKind.PEER)) return@execute onAnswer(null)
if (busy.get()) {
host.logInfo(TAG, "peer task queued behind a running turn: ${t.take(60)}")
pendingWakes.addLast(Queued(t, TurnKind.PEER, onAnswer))
@@ -482,8 +490,21 @@ class LocalBrain(
*/
private fun sweepInstruction(): String {
val candidates = topicCandidatesForPrompt()
- if (candidates.isEmpty()) return SWEEP_INSTRUCTION
- return SWEEP_INSTRUCTION + TOPIC_RULES.format(candidates)
+ val base = SWEEP_INSTRUCTION + alreadyRecorded()
+ if (candidates.isEmpty()) return base
+ return base + TOPIC_RULES.format(candidates)
+ }
+
+ /**
+ * What the notebook already holds, appended to a review's instruction. A review that could not see it wrote a
+ * second memory beside an existing one and a second todo for something already set.
+ */
+ private fun alreadyRecorded(): String {
+ val r = runCatching { host.reviewRecord() }.getOrDefault("")
+ return if (r.isBlank()) "\n\nYour notebook holds nothing yet." else
+ "\n\nWhat your notebook already holds — check here before writing anything. Something already here is " +
+ "updated in place (remember with the same name; for a todo, todos done/drop and set the corrected one), " +
+ "never written a second time under another name:\n" + r
}
/** Read from any thread. The service asks before queueing a wake-up. */
@@ -507,6 +528,7 @@ class LocalBrain(
loop.execute {
busy.set(true)
currentKind = kind
+ runningWhat = describe(text, kind)
aimMisses = 0
reviewItems = if (kind.silent) mutableListOf() else null
if (!kind.silent) justSwept = false
@@ -627,7 +649,9 @@ class LocalBrain(
* turn instead, which is the right order: the person who just spoke goes first.
*/
private fun drainWakes() {
- val next = pendingWakes.removeFirstOrNull() ?: return
+ var next = pendingWakes.removeFirstOrNull() ?: return
+ // A queued todo paused (or closed) by the turn it waited behind is skipped; the next one runs instead.
+ while (todoWithdrawn(next.text)) next = pendingWakes.removeFirstOrNull() ?: return
host.logInfo(TAG, "running a queued ${next.kind} turn: ${next.text.take(60)}")
launch(next.text, next.kind, onAnswer = next.onAnswer, territory = next.territory)
}
@@ -676,7 +700,9 @@ class LocalBrain(
fun work(text: String, territory: String?, onDone: (WorkResult) -> Unit) {
val t = text.trim()
if (t.isEmpty()) return
+ val epoch = stopEpoch.get()
loop.execute {
+ if (stoppedSince(epoch, t, TurnKind.WORK)) return@execute onDone(WorkResult(null, emptyList()))
val job = Queued(t, TurnKind.WORK, { onDone(workResult()) }, territory)
if (busy.get()) {
host.logInfo(TAG, "work queued behind a running turn: ${t.take(60)}")
@@ -824,6 +850,77 @@ class LocalBrain(
llm.cancel()
}
+ /** Any thread. What the turn running now is about, for the stop row: the user's words, a todo's, a care's. */
+ @Volatile private var runningWhat: String? = null
+
+ /** Any thread. Bumped by [stopAll], so a wake that is still waiting to start (see [wake]) knows it was stopped. */
+ private val stopEpoch = java.util.concurrent.atomic.AtomicInteger()
+
+ /** The epoch now; a caller that waits before starting a turn takes it first and passes it to [wake]. */
+ fun stopEpochNow(): Int = stopEpoch.get()
+
+ /**
+ * The user tapped the ball: stop **everything**, not only the turn on screen. [cancel] alone left the queue
+ * standing, so the next turn's end drained it and a stopped job came back — measured as "I tapped the ball
+ * and it carried on with the last task". Here: the turn is cut, every queued turn is dropped (a todo itself
+ * stays — it comes due again if it repeats), anything that took [stopEpochNow] before waiting will not start,
+ * and one STOPPED event names what was cut off and what was dropped, so the timeline says what the tap did.
+ * Must not block: called from the main thread.
+ */
+ fun stopAll() {
+ stopReportPending.set(true)
+ stopEpoch.incrementAndGet()
+ val running = runningWhat.takeIf { busy.get() }
+ cancel()
+ loop.execute {
+ // Turns that were already waiting on this thread ran their own check before this, and left their names
+ // here: one tap, one row.
+ stopReportPending.set(false)
+ val dropped = droppedByStop.toList() + pendingWakes.map { describe(it.text, it.kind) }
+ droppedByStop.clear()
+ pendingWakes.forEach { q -> q.onAnswer?.let { cb -> runCatching { cb(null) } } }
+ pendingWakes.clear()
+ if (running != null || dropped.isNotEmpty()) {
+ emit(BrainEvent(BrainEvent.Kind.STOPPED, running.orEmpty(), dropped.joinToString("\n") { "- $it" }))
+ }
+ }
+ }
+
+ /**
+ * Loop thread. A todo's turn whose todo was paused, done or dropped while the turn waited (to be quiet, or
+ * behind another turn): it does not run. The alarm already checked when it fired; this is the check at the
+ * moment it actually starts.
+ */
+ private fun todoWithdrawn(text: String): Boolean {
+ val id = WakeText.todoId(text) ?: return false
+ if (runCatching { host.todoStillActive(id) }.getOrDefault(true)) return false
+ host.logInfo(TAG, "todo $id is no longer active; its turn is dropped")
+ return true
+ }
+
+ /** Loop thread. True (and recorded) when [stopAll] ran after [epoch] was taken: this turn was stopped before it began. */
+ private fun stoppedSince(epoch: Int, text: String, kind: TurnKind): Boolean {
+ if (epoch == stopEpoch.get()) return false
+ host.logInfo(TAG, "$kind dropped: stopped before it began: ${text.take(60)}")
+ // Folded into the tap's own row when that row is still to come; a row of its own when it arrives later.
+ if (stopReportPending.get()) droppedByStop += describe(text, kind)
+ else emit(BrainEvent(BrainEvent.Kind.STOPPED, "", "- " + describe(text, kind)))
+ return true
+ }
+
+ /** Set by [stopAll] until its own row is written; while set, turns it stopped add their names to [droppedByStop]. */
+ private val stopReportPending = java.util.concurrent.atomic.AtomicBoolean(false)
+
+ /** Loop thread only. See [stopReportPending]. */
+ private val droppedByStop = mutableListOf<String>()
+
+ /** A short name for a turn, for the stop row. */
+ private fun describe(text: String, kind: TurnKind): String = when (kind) {
+ TurnKind.WAKE, TurnKind.NOTIFY -> WakeText.what(text)
+ TurnKind.WORK -> text.lineSequence().first().removePrefix("[You woke yourself: ").substringBefore(" — ")
+ else -> text.lineSequence().first()
+ }.take(80)
+
/** Service teardown. Threads are daemons, so this is tidiness, not safety. */
fun stop() {
cancel()
@@ -1174,24 +1271,6 @@ class LocalBrain(
val method = host.methodOf(tc.name)
?: return toolMessage(tc.id, "No such tool: ${tc.name}")
- // A turn Andee started itself does not interrupt the person: no question card, no alert, no voice.
- // Whatever it wants them to see goes through a bubble (rationed, silent, fades) or the diary.
- if (currentKind == TurnKind.WORK && method in SELF_TURN_MAY_NOT) {
- return toolMessage(
- tc.id,
- "You woke yourself for this; nobody asked, so you do not ask or speak. If it is worth their attention, leave a " +
- "bubble (nudge) or write it in your diary, and say it next time they talk to you.",
- )
- }
- // The list a work turn is given is a request; this is the wall. A model that names a tool it was not
- // handed (a tap, a shell command) would otherwise reach it through [BrainHost.methodOf] all the same.
- if (currentKind == TurnKind.WORK && !SelfWork.allowed(method)) {
- return toolMessage(
- tc.id,
- "$method is not open to a turn you started yourself: it has no screen, device or shell. Write down what you " +
- "would do and why (wiki, diary, the care's note), or leave a bubble, and do it when the user is with you.",
- )
- }
// A task another device handed over is done here, never handed on: see [TurnKind.PEER].
if (method == "peer.ask" && currentKind == TurnKind.PEER) {
return toolMessage(
@@ -1741,7 +1820,7 @@ class LocalBrain(
"reviewing before trimming",
)
lastHarvestAtSize = history.size
- launch(if (justSwept) HARVEST_SUMMARY_ONLY else HARVEST_INSTRUCTION, TurnKind.HARVEST)
+ launch(if (justSwept) HARVEST_SUMMARY_ONLY else HARVEST_INSTRUCTION + alreadyRecorded(), TurnKind.HARVEST)
}
/**
@@ -1937,8 +2016,6 @@ class LocalBrain(
/** The keys a handler uses to say its write did or did not happen (`LifeTools`, the notebook). */
private val NOT_DONE_KEYS = listOf("written", "added", "changed", "saved", "noted", "linked", "shared", "logged", "settled", "ok", "performed")
- /** What a self-started turn may not call: anything that speaks to or stops the person. */
- private val SELF_TURN_MAY_NOT = setOf("ui.ask", "ui.alert", "tts.speak")
/** How long a task stopped at the step limit is kept ready for 继续. See [Unfinished]. */
private const val UNFINISHED_TTL_MS = 60 * 60_000L
@@ -1987,7 +2064,8 @@ class LocalBrain(
* the conversation afterwards — the sweep leaves it alone, the harvest
* replaces the old part with the summary.
*/
- private const val REVIEW_RULES = """1. A preference / a taboo / a worry / a change in circumstances he said out loud this time → remember(type=user)
+ private const val REVIEW_RULES = """0. Before writing anything, look at what your notebook already holds (listed at the end). If an entry already covers it, update that one — never add a near-duplicate under a new name. A todo already set for the same thing is not set again. And one todo is one thing: never number several unrelated things into one todo.
+1. A preference / a taboo / a worry / a change in circumstances he said out loud this time → remember(type=user)
2. Something you promised but have not yet recorded → remember(type=feedback) + todo
3. Something dropped half-way (asked but not booked, said he would think about it and nobody followed up) → todo, to arrange one follow-up
4. Something you actually got done for him this time, a route you walked through → remember(type=way), with the task name as name.
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt
index a0d9b21..e3d2a51 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt
@@ -131,12 +131,6 @@ class NudgeBook(private val clock: () -> Long = System::currentTimeMillis) {
const val DAY_MS = 24 * HOUR_MS
const val KIND_COOLDOWN_MS = 45 * 60_000L
- /** 22:30–08:00. A bubble arriving inside it waits for morning, or expires first. */
- const val QUIET_FROM_MIN = 22 * 60 + 30
- const val QUIET_UNTIL_MIN = 8 * 60
-
- fun isQuiet(minuteOfDay: Int): Boolean = minuteOfDay >= QUIET_FROM_MIN || minuteOfDay < QUIET_UNTIL_MIN
-
/**
* What the brain is told when the user answers a bubble. English and bracketed: it is the device
* talking, and `LocalPrompt` §9 tells the model not to take a language from it.
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/SelfWork.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/SelfWork.kt
index 0f26a09..edfddd5 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/SelfWork.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/SelfWork.kt
@@ -5,48 +5,25 @@ import net.kuafuai.andee.config.Selfhood
import org.json.JSONArray
/**
- * A turn Andee starts itself, on a care that came due (`docs/design/inner-drive.zh-CN.md` §8): what it may use,
- * what it is told when it wakes, and how the device books what it did. The heartbeat ([Heartbeat]) decides
- * *whether*; this is the *what*.
+ * A turn Andee starts itself, on a care that came due (`docs/design/inner-drive.zh-CN.md` §8): what it is told when
+ * it wakes, and how the device books what it did. The heartbeat ([Heartbeat]) decides *whether*; this is the *what*.
*
- * **What it may use is the first phase's boundary, and it is narrow on purpose.** No screen, no device, no
- * shell, nothing sent outward, nothing that interrupts: it can think, read and write its notebook, its cares,
- * its diary, the people it knows and its wiki, and leave a bubble. A heartbeat runs while the user is in front
- * of the device — so a work turn that drove the screen would take the phone out of their hand to go and look at
- * something nobody asked about. Reading a community, posting a draft and the rest need the errand's permission
- * table (§8.2), which does not exist yet; until then the turn is told plainly what it cannot do.
+ * **It has everything a turn the user asked for has** — the screen, the apps, the device, the shell on the Mac.
+ * The device is Andee's own; whether the user is there is not a question this asks. The brakes are the user's:
+ * 自己动起来 in settings, and a tap on the ball, which stops it at once.
*
- * **What it did is decided by the device, from its own tool calls (§5.2)**: a write that landed is
- * [Selfhood.Effect.ACTED], only reads is [Selfhood.Effect.LOOKED], nothing is [Selfhood.Effect.NOTHING]. Writing
- * back the care's own note is bookkeeping, not work, and does not count as acting on it.
+ * **What it did is decided by the device, from its own tool calls (§5.2)**: a call that changed something and
+ * landed is [Selfhood.Effect.ACTED], only reads is [Selfhood.Effect.LOOKED], nothing is [Selfhood.Effect.NOTHING].
+ * Writing back the care's own note is bookkeeping, not work, and does not count as acting on it.
*/
object SelfWork {
- /** Every `note.*` except the review-only fold, the destructive forget and sharing outward. */
- private val NOTE_EXCLUDED = setOf("note.fold", "note.forget", "note.wiki_share")
-
- /** Outside `note.*`: the bubble, and the read-only shelves. */
- private val OTHER_ALLOWED = setOf(
- "ui.nudge", "ui.list_pages", "ui.get_page", "ui.list_topics", "ui.get_topic", "gear.list", "scene.list", "scene.get",
- )
-
- fun allowed(method: String): Boolean =
- (method.startsWith("note.") && method !in NOTE_EXCLUDED) || method in OTHER_ALLOWED
-
- /** [lists] cut down to what a work turn may hold. The hosts' default for [BrainHost.workTools]. */
- fun tools(lists: List<JSONArray>): List<JSONArray> = lists.map { a ->
- JSONArray().apply {
- for (i in 0 until a.length()) {
- val t = a.optJSONObject(i) ?: continue
- if (allowed(t.optString("method"))) put(t)
- }
- }
- }.filter { it.length() > 0 }
-
/** Reads, whatever their action. */
private val READS = setOf(
"note.recall", "note.people", "note.wiki_search", "note.wiki_read",
"ui.list_pages", "ui.get_page", "ui.list_topics", "ui.get_topic", "gear.list", "scene.list", "scene.get",
+ "screen.ui_tree", "screen.screenshot", "screen.look_region", "screen.wait",
+ "device.notifications", "device.apps", "device.battery", "device.connectivity", "device.location", "device.facts",
)
/** For the tools that both read and write, the actions that only read. */
@@ -90,14 +67,12 @@ object SelfWork {
if (care.links.isNotEmpty()) append("\nLinked: ").append(care.links.joinToString(", ")).append(" (read them before you write).")
append("]\n\n")
append(
- "Nobody asked for this and nobody is waiting: nothing you say is read aloud, and you may not ask or alert. " +
- "This turn has no screen, device or shell tools — you can think, read and write your notebook, cares, diary, " +
- "the people you know and your wiki, and leave one bubble (nudge) if something is genuinely worth their attention now. " +
- "Do the piece of this you can do with those: a plan or a piece of research written into the wiki (search first, revise " +
- "rather than duplicate, say where each claim comes from), a person's record brought up to date, a thought worth " +
- "keeping. If the real next step needs the screen or the user, say so in a bubble or leave it for when they talk to you. " +
+ "Nobody asked for this; it is your own business, on your own device, and you have every tool you have when " +
+ "someone asks you for something — the screen, the apps, the device. Do the next real piece of it. The rules " +
+ "you were given still hold: what goes out to people in public or in their name, spending money and deleting " +
+ "follow them. If the user taps the ball you are stopped at once — that is theirs to do, not a failure. " +
"Before you finish, write back: cares(action=update, id=${care.id}, note=…) with one sentence on where this stands " +
- "now, in your own voice. Your closing words are for your own record, not for anyone's ears.",
+ "now, in your own voice. Your closing words go to your own record (the timeline), not to anyone's ears.",
)
}
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/WakeText.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/WakeText.kt
index df3ccd7..83754bc 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/WakeText.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/WakeText.kt
@@ -23,6 +23,10 @@ object WakeText {
"give-up time → say what you saw. Do not wait on the screen for it."
}
+ /** The todo id a [due] line carries, or null when it is not a todo's line. */
+ fun todoId(line: String): String? =
+ Regex("""^\(time's up[^)]*id=([^)\s]+)\)""").find(line.trimStart())?.groupValues?.get(1)
+
/** The todo's own words back out of a [due] line, for the timeline; the line itself when it is not one. */
fun what(line: String): String {
val first = line.lineSequence().firstOrNull().orEmpty()
diff --git a/core/src/main/kotlin/net/kuafuai/andee/config/NotebookBook.kt b/core/src/main/kotlin/net/kuafuai/andee/config/NotebookBook.kt
index 68aa19f..973aa85 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/NotebookBook.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/NotebookBook.kt
@@ -453,6 +453,30 @@ class NotebookBook(private val store: NotebookStore) {
return top.joinToString("\n") { "- ${it.name}:${it.description}" }
}
+ /**
+ * Everything already written down, for a review to compare against: every memory (name and description) and
+ * every pending todo (id, when, what). A review that could not see these wrote near-duplicates of both — an
+ * ordinary turn's index carries only the top ten memories and no todos at all.
+ */
+ fun recordForReview(now: Long = System.currentTimeMillis()): String = buildString {
+ val mem = memories().filter { !it.expired(now) }.sortedBy { it.type }
+ if (mem.isNotEmpty()) {
+ append("Memories (").append(mem.size).append("):\n")
+ mem.forEach { append("- [").append(it.type).append("] ").append(it.name).append(":").append(it.description.take(100)).append('\n') }
+ }
+ val td = todos("pending")
+ if (td.isNotEmpty()) {
+ if (isNotEmpty()) append('\n')
+ append("Pending todos (").append(td.size).append("):\n")
+ val fmt = java.text.SimpleDateFormat("MM-dd HH:mm", java.util.Locale.US)
+ td.forEach { t ->
+ append("- ").append(t.id).append(" · ").append(if (t.mode == "cron") t.cronExpr else fmt.format(java.util.Date(t.nextRunAt.takeIf { it > 0 } ?: t.at)))
+ if (t.status == "paused") append(" · paused")
+ append(" · ").append(t.what.take(120)).append('\n')
+ }
+ }
+ }.trimEnd()
+
// ------------------------------------------------------------------
// todos
// ------------------------------------------------------------------
@@ -631,6 +655,16 @@ class NotebookBook(private val store: NotebookStore) {
}
companion object {
+ /**
+ * A todo's `what` that numbers several items ("1) … 2) …", "①…②…"): refused with the reason, because one todo
+ * cannot be half done — the part that was not is lost when it is closed. Null when it is one thing.
+ */
+ fun bundledTodo(what: String): String? {
+ val marks = Regex("""(?:^|[\s;;。,,::])(?:\(?\d{1,2}[).、..]|[①②③④⑤⑥⑦⑧⑨])""").findAll(what).count()
+ return if (marks >= 2) "This todo lists several separate things. Set one todo per thing — each comes due, " +
+ "is done and closed on its own." else null
+ }
+
fun importanceFor(type: String): Double = when (type) {
"failure" -> 0.9
"user" -> 0.7
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 6ae9c75..da56a1c 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
@@ -370,6 +370,11 @@ class Plans(
for (t in have) {
val spec = runCatching { JSONObject(t.nudge) }.getOrNull()
val ref = spec?.optString("plan_ref").orEmpty()
+ // Paused by the user or the model: left alone, and not recreated as an active one under it.
+ if (t.status == "paused") {
+ haveRefs += ref
+ continue
+ }
val w = want[ref]
if (w != null && t.at == at[ref] && spec.toString() == w.toString()) {
haveRefs += ref
@@ -461,7 +466,6 @@ class Plans(
* a day. Everything else in the plan has a clock time and needs no thought to come due.
*/
fun museDue(): Boolean = synchronized(lock) {
- if (NudgeBook.isQuiet(minuteOfDay())) return false
val root = load()
val m = meta(root)
if (clock() - m.optLong("muse_at") < MUSE_GAP_MS) return false
diff --git a/core/src/main/kotlin/net/kuafuai/andee/config/Selfhood.kt b/core/src/main/kotlin/net/kuafuai/andee/config/Selfhood.kt
index 9351080..3658277 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/Selfhood.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/Selfhood.kt
@@ -258,7 +258,9 @@ class Selfhood(
list[i] = when (effect) {
Effect.ACTED -> c.copy(lastTouched = now, idleRuns = 0, pinnedAt = 0L, note = note?.trim()?.take(MAX_NOTE) ?: c.note)
Effect.LOOKED -> c.copy(lastTouched = maxOf(c.lastTouched, now - c.intervalMs / 2), idleRuns = c.idleRuns, note = note?.trim()?.take(MAX_NOTE) ?: c.note)
- Effect.NOTHING -> c.copy(idleRuns = c.idleRuns + 1)
+ // Nothing came of it: count it, and push it back half an interval as a look would, so the same care
+ // cannot take every work turn of the day in a row.
+ Effect.NOTHING -> c.copy(idleRuns = c.idleRuns + 1, lastTouched = maxOf(c.lastTouched, now - c.intervalMs / 2))
}
putCares(root, list); save(root)
list[i]
diff --git a/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt b/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
index bbb3390..d772556 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
@@ -1730,6 +1730,10 @@ object ToolSchemas {
One sentence, written for future you to read: what to **do** or **say** at that time.
"Remind him to take his medicine" is too vague; "tell him it's time for his medicine, and ask how he slept last night" is something that can be executed.
+ **One todo is one thing.** Two unrelated things are two todos, even at the same time — "1) ask about the comment
+ 2) check the app" in one todo cannot be closed half-done, and the half that was not done is lost. A todo whose
+ `what` numbers several items is refused.
+
## When it triggers (at and cron — one or the other; not both, not neither)
- `at`: one-off. Local time `YYYY-MM-DD HH:mm`. **Absolute times only** — for "in ten minutes", work the time out yourself and fill in the result.
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/AimHintsTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/AimHintsTest.kt
index 7b25cc2..4b45cd0 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/AimHintsTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/AimHintsTest.kt
@@ -62,7 +62,7 @@ class AimHintsTest {
"locale" -> Locale.ENGLISH
"maxSteps" -> 10
"persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
- "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex" -> ""
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex", "reviewRecord" -> ""
"scrollback" -> emptyList<ScrollRow>()
"toolLists" -> listOf(JSONArray().put(tool("tap_by_coordinates", "screen.tap")).apply {
if (withLocator) put(tool("tap_target", "screen.tap_target"))
@@ -73,6 +73,7 @@ class AimHintsTest {
if (taps == 3) throw IllegalStateException(AimHints.REPEAT_REFUSED + " (the fourth tap). Not executed.")
JSONObject().put("screen_changed", false)
}
+ "todoStillActive" -> true
"traceDir" -> trace
else -> null
}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/BrainEventTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/BrainEventTest.kt
index 66308e8..094af9b 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/BrainEventTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/BrainEventTest.kt
@@ -21,8 +21,6 @@ class BrainEventTest {
assertNull(BrainEvent.fromTool("note.wiki_read", JSONObject().put("id", "w9"), JSONObject().put("read", false)))
val shown = BrainEvent.fromTool("ui.show_wiki", JSONObject().put("id", "w1"), JSONObject().put("shown", true).put("title", "运营规划"))!!
assertEquals(Triple(BrainEvent.Kind.WIKI_SHOWN, "运营规划", "w1"), Triple(shown.kind, shown.subject, shown.ref))
- // Showing is never something a quiet turn may do.
- assertEquals(false, SelfWork.allowed("ui.show_wiki"))
}
@Test fun aWakeLineGivesBackTheTodo() {
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/ContinueAfterStepLimitTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/ContinueAfterStepLimitTest.kt
index d33285a..f9a661a 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/ContinueAfterStepLimitTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/ContinueAfterStepLimitTest.kt
@@ -57,7 +57,7 @@ class ContinueAfterStepLimitTest {
"locale" -> Locale.ENGLISH
"maxSteps" -> steps
"persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
- "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex" -> ""
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex", "reviewRecord" -> ""
"scrollback" -> emptyList<ScrollRow>()
"toolLists" -> listOf(
JSONArray().put(
@@ -67,6 +67,7 @@ class ContinueAfterStepLimitTest {
)
"methodOf" -> "screen.tap"
"dispatch" -> JSONObject().put("ok", true)
+ "todoStillActive" -> true
"traceDir" -> trace
else -> null
}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/HeartbeatTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/HeartbeatTest.kt
index 7e44b88..e7a58b8 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/HeartbeatTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/HeartbeatTest.kt
@@ -57,15 +57,20 @@ class HeartbeatTest {
assertNull(beat.beat("zh"))
}
- @Test fun theNightAndThePaceStopItBeforeTheCall() {
+ @Test fun thePaceAndTheWorkGapStopItBeforeTheCallButTheNightDoesNot() {
val id = care()
now += 24 * h
answer = """{"verdict":"work","care_id":"$id","why":"x"}"""
beat.beat("zh")
now += 5 * 60_000L // five minutes later: too soon
assertEquals("pace", beat.gate())
- now = java.time.LocalDateTime.of(2027, 1, 16, 23, 0).toInstant(ZoneOffset.UTC).toEpochMilli()
- assertEquals("night", beat.gate())
+ drive.recordWork(id, "社区", "acted", "", emptyList())
+ now += Heartbeat.INTERVAL_MS
+ assertEquals("work gap", beat.gate()) // an hour between work turns
+ now += Heartbeat.WORK_GAP_MS
+ self.settle(id, Selfhood.Effect.LOOKED, null); now += 24 * h
+ now = java.time.LocalDateTime.of(2027, 1, 18, 3, 0).toInstant(ZoneOffset.UTC).toEpochMilli()
+ assertNull(beat.gate()) // three in the morning: no hours of its own
}
@Test fun theWorkBudgetHoldsWhateverTheModelSays() {
@@ -74,7 +79,8 @@ class HeartbeatTest {
answer = """{"verdict":"work","care_id":"$id","why":"x"}"""
repeat(Heartbeat.MAX_WORKS) { drive.markWork() }
assertNull(beat.beat("zh"))
- assertEquals(1, calls)
+ assertEquals(0, calls) // spent: not even the call, which could only answer sleep
+ assertEquals("work budget", beat.gate())
}
@Test fun aNoteIsKeptAsAThoughtAndAnUnreadableAnswerIsSleep() {
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt
index 3ed235a..dd18a3c 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt
@@ -96,13 +96,6 @@ class NudgeBookTest {
assertEquals(NudgeBook.Level.OFF, NudgeBook.Level.of("chatty"))
}
- @Test fun quietHours() {
- assertTrue(NudgeBook.isQuiet(23 * 60))
- assertTrue(NudgeBook.isQuiet(7 * 60 + 59))
- assertFalse(NudgeBook.isQuiet(8 * 60))
- assertFalse(NudgeBook.isQuiet(22 * 60 + 29))
- }
-
@Test fun answerTextNamesTheButton() {
val n = nudge("meal", "好", "不用", dismiss = "不用")
assertTrue(NudgeBook.answerText(n, "好").contains("tapped \"好\""))
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt
index caf8272..23565fc 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/ReviewEventsTest.kt
@@ -56,13 +56,14 @@ class ReviewEventsTest {
"locale" -> Locale.ENGLISH
"maxSteps" -> 10
"persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
- "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex" -> ""
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex", "reviewRecord" -> ""
"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 }
+ "todoStillActive" -> true
"traceDir" -> trace
else -> null
}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/SelfWorkTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/SelfWorkTest.kt
index 01d7605..65ee946 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/SelfWorkTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/SelfWorkTest.kt
@@ -1,9 +1,7 @@
package net.kuafuai.andee.brain
import net.kuafuai.andee.config.Selfhood
-import net.kuafuai.andee.net.ToolSchemas
import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -24,22 +22,18 @@ class SelfWorkTest {
assertEquals(Selfhood.Effect.LOOKED, SelfWork.effect(listOf(c("note.recall"), c("note.wiki_write", ok = false)), "c1"))
}
- @Test fun noScreenNoDeviceNothingOutward() {
- val methods = SelfWork.tools(listOf(ToolSchemas.all())).flatMap { a -> (0 until a.length()).map { a.getJSONObject(it).getString("method") } }
- assertTrue("note.wiki_write" in methods)
- assertTrue("ui.nudge" in methods)
- for (m in methods) assertTrue(m, SelfWork.allowed(m))
- for (m in listOf("screen.tap", "screen.ui_tree", "device.sms.send", "device.vault.fill", "ui.ask", "ui.show_html", "note.fold", "note.forget", "note.wiki_share", "peer.ask")) {
- assertFalse(m, SelfWork.allowed(m))
- }
+ @Test fun lookingAtTheScreenIsALookNotWork() {
+ assertEquals(Selfhood.Effect.LOOKED, SelfWork.effect(listOf(c("screen.screenshot"), c("screen.ui_tree")), "c1"))
+ assertEquals(Selfhood.Effect.ACTED, SelfWork.effect(listOf(c("screen.screenshot"), c("screen.tap")), "c1"))
}
- @Test fun theOpeningSaysWhatItIsAndWhatItCannotDo() {
+ @Test fun theOpeningSaysWhatItIsAndThatItHasEverything() {
val care = Selfhood.Care("c1", "社区", "他交给我的", "place", 12 * Selfhood.HOUR_MS, 0, 0, "x", "active", "上次发了一帖", 2, false, 0, 0, emptyList())
val t = SelfWork.opening(care, 1.5, "写一份方案", now = 18 * Selfhood.HOUR_MS)
assertTrue(t.contains("1.5× overdue"))
assertTrue(t.contains("上次发了一帖"))
assertTrue(t.contains("nothing came of it"))
assertTrue(t.contains("cares(action=update, id=c1"))
+ assertTrue(t.contains("the screen"))
}
}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/StopAllTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/StopAllTest.kt
new file mode 100644
index 0000000..ebee9fd
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/StopAllTest.kt
@@ -0,0 +1,69 @@
+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.assertTrue
+import org.junit.Test
+import java.io.File
+import java.lang.reflect.Proxy
+import java.net.InetSocketAddress
+import java.util.Locale
+
+/**
+ * A tap on the ball stops everything: the turn running, the turns queued behind it, and a wake still waiting to
+ * start — and says what it stopped. Before, only the running turn stopped and the queue came back on its own.
+ */
+class StopAllTest {
+ private val turns = mutableListOf<String>()
+ private val events = mutableListOf<BrainEvent>()
+ private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
+ createContext("/chat/completions") { ex ->
+ val body = JSONObject(ex.requestBody.readBytes().toString(Charsets.UTF_8))
+ val msgs = body.getJSONArray("messages")
+ synchronized(turns) { turns += msgs.getJSONObject(msgs.length() - 1).optString("content").take(40) }
+ Thread.sleep(800) // slow enough to be stopped mid-way
+ val out = JSONObject().put("choices", JSONArray().put(JSONObject().put("message", JSONObject().put("role", "assistant").put("content", "ok"))))
+ .put("usage", JSONObject().put("prompt_tokens", 1).put("completion_tokens", 1)).toString().toByteArray()
+ runCatching { 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 host = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(BrainHost::class.java)) { _, m, args ->
+ when (m.name) {
+ "text" -> (args[0] as BrainText).name
+ "locale" -> Locale.ENGLISH
+ "maxSteps" -> 5
+ "persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex", "reviewRecord" -> ""
+ "scrollback" -> emptyList<ScrollRow>()
+ "toolLists" -> listOf(JSONArray())
+ "event" -> { synchronized(events) { events += args[0] as BrainEvent }; null }
+ "todoStillActive" -> true
+ "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 theQueueAndAWaitingWakeDoNotComeBack() {
+ brain.submit("first job")
+ Thread.sleep(200)
+ brain.wake(WakeText.due("t1", "queued reminder", false))
+ val epoch = brain.stopEpochNow() // a wake that is still waiting to start
+ Thread.sleep(200)
+ brain.stopAll()
+ brain.wake(WakeText.due("t2", "late reminder", false), epoch = epoch)
+ Thread.sleep(2500)
+ assertEquals(listOf("first job"), synchronized(turns) { turns.map { it.substringAfter("] ").take(9) } })
+ val stopped = synchronized(events) { events.filter { it.kind == BrainEvent.Kind.STOPPED } }
+ assertTrue(stopped.any { it.subject == "first job" && it.detail.contains("queued reminder") })
+ assertTrue(stopped.any { it.detail.contains("late reminder") })
+ }
+}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/TodoGuardsTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/TodoGuardsTest.kt
new file mode 100644
index 0000000..daae8e8
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/TodoGuardsTest.kt
@@ -0,0 +1,92 @@
+package net.kuafuai.andee.brain
+
+import com.sun.net.httpserver.HttpServer
+import net.kuafuai.andee.config.BrainConfig
+import net.kuafuai.andee.config.NotebookBook
+import net.kuafuai.andee.config.NotebookStore
+import net.kuafuai.andee.config.Todo
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+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
+
+class TodoGuardsTest {
+
+ @Test fun aTodoThatBundlesSeveralThingsIsRefused() {
+ assertNotNull(NotebookBook.bundledTodo("1) 问他留言发了没 2) 看看码上飞的测试结果"))
+ assertNotNull(NotebookBook.bundledTodo("两件事:①问评论 ②查测试"))
+ assertNull(NotebookBook.bundledTodo("问他留言发了没,顺便问他睡得怎么样"))
+ assertNull(NotebookBook.bundledTodo("下午 3 点提醒他开会"))
+ }
+
+ @Test fun theTodoIdRidesOnTheWakeLine() {
+ assertEquals("t42", WakeText.todoId(WakeText.due("t42", "开会", false)))
+ assertNull(WakeText.todoId("hello"))
+ }
+
+ @Test fun theReviewSeesWhatIsAlreadyRecorded() {
+ val book = NotebookBook(object : NotebookStore {
+ var s: String? = null
+ override fun read() = s
+ override fun write(plain: String): Boolean { s = plain; return true }
+ override fun wipe() { s = null }
+ })
+ book.remember("他的作息", "晚睡晚起", "", "user")
+ book.addTodo(Todo("t1", "周五问他发布进度", "once", 2_000_000_000_000L, "", 2_000_000_000_000L, 0, "", "", "paused", 0))
+ val r = book.recordForReview()
+ assertTrue(r.contains("他的作息") && r.contains("晚睡晚起"))
+ assertTrue(r.contains("t1") && r.contains("paused") && r.contains("周五问他发布进度"))
+ }
+
+ // ---- a todo paused while its turn waited does not run ----
+
+ private val said = mutableListOf<String>()
+ private var active = true
+ private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
+ createContext("/chat/completions") { ex ->
+ val msgs = JSONObject(ex.requestBody.readBytes().toString(Charsets.UTF_8)).getJSONArray("messages")
+ synchronized(said) { said += msgs.getJSONObject(msgs.length() - 1).optString("content") }
+ Thread.sleep(500)
+ val out = JSONObject().put("choices", JSONArray().put(JSONObject().put("message", JSONObject().put("role", "assistant").put("content", "ok"))))
+ .put("usage", JSONObject().put("prompt_tokens", 1).put("completion_tokens", 1)).toString().toByteArray()
+ runCatching { 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 host = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(BrainHost::class.java)) { _, m, args ->
+ when (m.name) {
+ "text" -> (args[0] as BrainText).name
+ "locale" -> Locale.ENGLISH
+ "maxSteps" -> 5
+ "persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex", "reviewRecord" -> ""
+ "scrollback" -> emptyList<ScrollRow>()
+ "toolLists" -> listOf(JSONArray())
+ "todoStillActive" -> active
+ "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 aQueuedTodoPausedMeanwhileDoesNotRun() {
+ brain.submit("pause that reminder")
+ Thread.sleep(150)
+ brain.wake(WakeText.due("t1", "the reminder", false)) // queued behind the turn above
+ active = false // that turn paused it
+ Thread.sleep(2000)
+ assertEquals(1, synchronized(said) { said.size })
+ assertTrue(said.single().contains("pause that reminder"))
+ }
+}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/WorkTurnTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/WorkTurnTest.kt
index e5613f1..4911224 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/brain/WorkTurnTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/WorkTurnTest.kt
@@ -17,8 +17,8 @@ import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
- * A turn Andee starts itself: it is handed only the work tools, a tool it names anyway is refused by the loop
- * (not by the list), nothing is spoken, and the device gets back every call it made.
+ * A turn Andee starts itself: it is handed the same tools as any turn (the device is its own), nothing is spoken,
+ * and the device gets back every call it made.
*/
class WorkTurnTest {
private val requests = mutableListOf<JSONObject>()
@@ -54,13 +54,14 @@ class WorkTurnTest {
"locale" -> Locale.ENGLISH
"maxSteps" -> 10
"persona", "platformPrompt", "notebookIndex", "scenesIndex", "pagesIndex", "topicsIndex",
- "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex" -> ""
+ "gearIndex", "planIndex", "friendsIndex", "selfIndex", "wikiIndex", "reviewRecord" -> ""
"scrollback" -> emptyList<ScrollRow>()
"toolLists" -> listOf(JSONArray().put(tool("tap", "screen.tap")).put(tool("remember", "note.remember")))
// A proxy intercepts default methods too, so answer this one the way the default would.
- "workTools" -> SelfWork.tools((proxy as BrainHost).toolLists())
+ "workTools" -> (proxy as BrainHost).toolLists()
"methodOf" -> mapOf("tap" to "screen.tap", "remember" to "note.remember")[args[0] as String]
"dispatch" -> { synchronized(dispatched) { dispatched += args[0] as String }; JSONObject().put("ok", true) }
+ "todoStillActive" -> true
"traceDir" -> trace
else -> null
}
@@ -76,20 +77,16 @@ class WorkTurnTest {
server.stop(0)
}
- @Test fun aWorkTurnHoldsOnlyItsToolsAndSaysNothing() {
+ @Test fun aWorkTurnHasEveryToolAndSaysNothing() {
val done = LinkedBlockingQueue<LocalBrain.WorkResult>()
brain.work("[You woke yourself: 社区]", "place") { done += it }
val r = done.poll(20, TimeUnit.SECONDS) ?: throw AssertionError("no result")
val offered = requests.first().getJSONArray("tools").let { a -> (0 until a.length()).map { a.getJSONObject(it).getJSONObject("function").getString("name") } }
- assertEquals(listOf("remember"), offered)
- assertEquals(listOf("note.remember"), dispatched)
- assertEquals(listOf("note.remember"), r.calls.map { it.method })
- assertTrue(r.calls.single().effective)
+ assertEquals(listOf("tap", "remember"), offered)
+ assertEquals(listOf("screen.tap", "note.remember"), dispatched)
+ assertEquals(listOf("screen.tap", "note.remember"), r.calls.map { it.method })
assertEquals("写下了下一步", r.summary)
assertTrue("a work turn spoke: $spoken", spoken.isEmpty())
- // The refusal went back to the model as the tool's answer.
- val toolMsgs = requests[1].getJSONArray("messages").let { a -> (0 until a.length()).map { a.getJSONObject(it) } }.filter { it.optString("role") == "tool" }
- assertFalse(toolMsgs.first { it.optString("tool_call_id") == "c1" }.optString("content").contains("ok"))
}
}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt b/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt
index 6ad4699..70fa7a3 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt
@@ -173,7 +173,7 @@ class PlansTest {
.put("slot", slot).put("kind", "ask").put("what", what).put("because", "规律喝水")
.put("buttons", JSONArray(listOf("好", "不用"))).put("dismiss", "不用")
- @Test fun museOnlyWithALooseTimeItemSpacedAndNotAtNight() {
+ @Test fun museOnlyWithALooseTimeItemAndSpaced() {
write(item("10:00", "该喝水啦"))
assertFalse(plans.museDue()) // only clock-time items: nothing to decide
write(slotItem("午饭前", "要帮你点外卖吗?"))
@@ -184,7 +184,7 @@ class PlansTest {
now += Plans.MUSE_GAP_MS
assertTrue(plans.museDue())
now = LocalDateTime.of(2026, 10, 27, 23, 0).atZone(zone).toInstant().toEpochMilli()
- assertFalse(plans.museDue()) // quiet hours
+ assertTrue(plans.museDue()) // no hours of its own: the device is Andee's, at any time of day
}
@Test fun museCapPerDay() {
diff --git a/core/src/test/kotlin/net/kuafuai/andee/config/SelfhoodTest.kt b/core/src/test/kotlin/net/kuafuai/andee/config/SelfhoodTest.kt
index a278c1b..ca026af 100644
--- a/core/src/test/kotlin/net/kuafuai/andee/config/SelfhoodTest.kt
+++ b/core/src/test/kotlin/net/kuafuai/andee/config/SelfhoodTest.kt
@@ -54,12 +54,14 @@ class SelfhoodTest {
assertTrue(me.overdue(me.care(id)!!) > 1.4)
}
- @Test fun actingResetsLookingOnlyHalfwayNothingNotAtAll() {
+ @Test fun actingResetsLookingAndNothingOnlyHalfway() {
val id = add("place", "社区", 12.0)
now += 24 * h
+ // Nothing came of it: counted, and pushed back half an interval so it cannot take every work turn in a row.
me.settle(id, Selfhood.Effect.NOTHING, null)
- assertEquals(2.0, me.overdue(me.care(id)!!), 0.01)
+ assertEquals(0.5, me.overdue(me.care(id)!!), 0.01)
assertEquals(1, me.care(id)!!.idleRuns)
+ now += 18 * h
me.settle(id, Selfhood.Effect.LOOKED, "看了一眼")
assertEquals(0.5, me.overdue(me.care(id)!!), 0.01) // moved half an interval back, not to zero
now += 12 * h
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
index a4b16e1..c814daf 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
@@ -496,10 +496,15 @@ object Assistant {
*/
private fun interruptForNewRequest() = stop()
- /** The user's stop: the turn ends, and every command it started ends with it. */
+ /**
+ * The user's stop: everything ends — the turn, every turn queued behind it and every wake still waiting to
+ * start (`LocalBrain.stopAll`, which also puts what was cut off in the timeline), every command it started,
+ * the voice, and the bubble.
+ */
fun stop() {
cancelPending()
- brain?.cancel()
+ brain?.stopAll()
+ Nudges.dismiss()
guest?.cancel()
shell.stopAll()
net.kuafuai.andee.desktop.voice.MacVoice.stopSpeaking()
@@ -515,7 +520,9 @@ object Assistant {
override fun tell(n: JSONObject, line: String) {
// No turn and no task light: the sentence is already written, nothing is being driven.
val clean = net.kuafuai.andee.brain.SpeechMood.parse(line).text.trim()
- Scrollback.add(Scrollback.Role.ASSISTANT, clean)
+ // An event, not a line of conversation: a lone Andee bubble among the timeline's event rows read as it
+ // talking to nobody. The row names the app; the original message is the detail.
+ TimelineEvents.told(n.optString("app").ifEmpty { "?" }, clean, n.optString("latest").ifEmpty { n.optString("text") })
onFinal(clean)
if (!muted) net.kuafuai.andee.desktop.voice.MacVoice.speak(line)
}
@@ -561,11 +568,15 @@ object Assistant {
wakeBrain(todo)
}
- private fun wakeBrain(todo: net.kuafuai.andee.config.Todo) = whenQuiet("wake-${todo.id}") {
- // busy() is the window's "working" light: only turn it on when a turn really starts, not when
- // the wake-up is merely parked behind another one.
- if (brain?.isBusy() != true) busy(true)
- ensure().wake(dueText(todo), untrusted = todo.untrusted)
+ private fun wakeBrain(todo: net.kuafuai.andee.config.Todo) {
+ // Taken before the wait: a tap on the ball while it waits means this one must not start (LocalBrain.wake).
+ val epoch = ensure().stopEpochNow()
+ whenQuiet("wake-${todo.id}") {
+ // busy() is the window's "working" light: only turn it on when a turn really starts, not when
+ // the wake-up is merely parked behind another one.
+ if (epoch == ensure().stopEpochNow() && brain?.isBusy() != true) busy(true)
+ ensure().wake(dueText(todo), untrusted = todo.untrusted, epoch = epoch)
+ }
}
/**
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
index efff413..0bafb7b 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
@@ -61,6 +61,8 @@ class DesktopBrainHost(
}
override fun notebookIndex(): String = DesktopNotebook.book.indexForPrompt()
+ override fun reviewRecord(): String = DesktopNotebook.book.recordForReview()
+ override fun todoStillActive(id: String): Boolean = DesktopNotebook.book.todoById(id)?.status == "active"
override fun scenesIndex(): String = DesktopNotebook.book.scenesForPrompt()
override fun scene(name: String): Scene? = DesktopNotebook.book.scene(name)
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
index d2e4f64..7bdf409 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
@@ -232,7 +232,8 @@ fun tapToTalk(onNoVoice: () -> Unit) {
when {
Meeting.isActive() -> Meeting.stopFromUser()
else -> {
- if (Assistant.working()) Assistant.stop()
+ // Always: "working" misses what is queued or waiting to start, and that is what carried on after a tap.
+ Assistant.stop()
if (!net.kuafuai.andee.desktop.voice.MacVoice.toggle()) onNoVoice()
}
}
@@ -241,7 +242,7 @@ fun tapToTalk(onNoVoice: () -> Unit) {
fun ballActions(onType: () -> Unit, onNoVoice: () -> Unit) = BallActions(
onTap = { tapToTalk(onNoVoice) },
// Typing is a new request too: whatever was running or being read out stops first, as the tap does.
- onDoubleTap = { if (Assistant.working()) Assistant.stop(); onType() },
+ onDoubleTap = { Assistant.stop(); onType() },
onTripleTap = { if (Meeting.isActive()) Meeting.stopFromUser() else Assistant.stop() },
onLongPress = {},
)
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NotebookTools.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NotebookTools.kt
index 022665e..38646db 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NotebookTools.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NotebookTools.kt
@@ -275,6 +275,7 @@ class NotebookTools(private val onSceneChanged: (String?) -> Unit) {
private fun todo(p: JSONObject, untrusted: Boolean): JSONObject {
val what = req(p, "what", "note.todo")
+ NotebookBook.bundledTodo(what)?.let { throw IllegalArgumentException(it) }
val atRaw = p.optString("at").trim()
val cronRaw = p.optString("cron").trim()
require(atRaw.isNotEmpty() != cronRaw.isNotEmpty()) {
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt
index f7f51ad..90160bd 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt
@@ -67,8 +67,6 @@ object Nudges {
private const val STAY_TEXT_MS = 12_000L
private const val STAY_BUTTONS_MS = 30_000L
private const val FADE_MS = 260L
- /** Nobody has touched the keyboard or mouse for this long: away, or the screen is locked. */
- private const val AWAY_SECONDS = 300L
private class Slot(val n: Nudge, var recorded: Boolean = false)
@@ -141,9 +139,6 @@ object Nudges {
if (!ballUp()) return Gate.WAIT
if (AskGate.current != null || ApprovalGate.current != null) return Gate.WAIT
if (Assistant.working() || net.kuafuai.andee.desktop.voice.MacVoice.isListening() || Meeting.isActive()) return Gate.WAIT
- val now = java.time.LocalTime.now()
- if (NudgeBook.isQuiet(now.hour * 60 + now.minute)) return Gate.WAIT
- if ((idleSeconds() ?: 0L) >= AWAY_SECONDS) return Gate.WAIT
return if (chatInFront()) Gate.LOG else Gate.SHOW
}
@@ -156,6 +151,16 @@ object Nudges {
// ---- what the user did (called from the UI thread) -----------------------
+ /**
+ * The user tapped the ball to stop everything: the bubble on screen goes, and the one waiting for its moment is
+ * dropped — recorded as dismissed, as if the user had waved it away.
+ */
+ fun dismiss() = exec.execute {
+ held?.let { outcome(it.n, "dismissed", null) }
+ held = null
+ current?.let { end(it, "dismissed", null) }
+ }
+
fun tapButton(label: String) = exec.execute { current?.let { end(it, "button", label) } }
fun tapBody() = exec.execute { current?.let { end(it, "body", null) } }
fun longPress() = exec.execute { current?.let { end(it, "mute", null) } }
@@ -214,18 +219,11 @@ object Nudges {
TimelineEvents.body(TimelineEvents.Body.BUBBLE_MUTED, String.format(Strings.locale(), Strings.get("s_nudge_muted_row"), n.text))
}
- /** Seconds since the last keyboard or mouse input, from the HID system; null when it cannot be read. */
- internal fun idleSeconds(): Long? = runCatching {
- val p = ProcessBuilder("ioreg", "-c", "IOHIDSystem", "-d", "4").redirectErrorStream(true).start()
- val out = p.inputStream.bufferedReader().readText()
- p.waitFor(2, TimeUnit.SECONDS)
- Regex("\"HIDIdleTime\" = (\\d+)").find(out)?.groupValues?.get(1)?.toLong()?.div(1_000_000_000L)
- }.getOrNull()
}
/**
* The plan, thought about without being asked ([net.kuafuai.andee.brain.PlanMind]) — the Mac's twin of the
- * phone's `planTick`. Every [TICK_MS], and only with someone at the Mac (input within the last five minutes):
+ * phone's `planTick`. Every [TICK_MS], whether or not anyone is at the Mac — the device is Andee's own:
* the morning look once a day, then the muse while they are free. On its own thread, because both block on a
* model call and the bubble timers must not wait behind one.
*/
@@ -240,7 +238,7 @@ object PlanTicks {
private fun tick() {
val cfg = Assistant.config()
if (cfg.apiKey.isEmpty()) return
- if ((Nudges.idleSeconds() ?: 0L) >= 300L) return
+ // Not whether anyone is at the Mac, or the hour: the device is Andee's own (see the phone's planTick).
val plans = DesktopNotebook.plans
val mind = net.kuafuai.andee.brain.PlanMind(cfg, plans) { warn, msg -> if (warn) Log.w("Plan", msg) else Log.i("Plan", msg) }
val level = Nudges.level()
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 046adc9..cd10cf2 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/TimelineEvents.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/TimelineEvents.kt
@@ -16,7 +16,7 @@ import net.kuafuai.andee.brain.BrainEvent
object TimelineEvents {
/** Body-side event kinds, alongside [BrainEvent.Kind]'s names. */
- enum class Body { THOUGHT, WORK, BUBBLE, BUBBLE_MUTED, IGNORED, MEETING, VERSION, LOOK, VAULT, PAGE, MORNING, SHELL, SCENE }
+ enum class Body { THOUGHT, WORK, BUBBLE, BUBBLE_MUTED, IGNORED, MEETING, VERSION, LOOK, VAULT, PAGE, MORNING, SHELL, SCENE, TOLD }
private val zh get() = Strings.lang() == "zh"
private fun t(z: String, e: String) = if (zh) z else e
@@ -38,6 +38,7 @@ object TimelineEvents {
val u = e.updated
return when (e.kind) {
BrainEvent.Kind.WOKE -> t("提醒到点:$s", "Reminder due: $s")
+ BrainEvent.Kind.STOPPED -> if (s.isNotBlank()) t("被你叫停了:$s", "You stopped it: $s") else t("被你叫停了,排着的事没做", "You stopped it; what was waiting was dropped")
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 -> t("复盘了一遍,记下 $s 处", "Reviewed the conversation; kept $s things")
@@ -79,6 +80,7 @@ object TimelineEvents {
)
fun bubble(text: String) = body(Body.BUBBLE, t("冒了个气泡:$text", "Bubble: $text"))
fun ignored(app: String, why: String) = body(Body.IGNORED, t("没打扰你:$app 的一条通知", "Let a notification from $app pass"), why)
+ fun told(app: String, line: String, original: String) = body(Body.TOLD, t("$app 来消息:$line", "$app: $line"), original)
fun held(app: String, text: String) = body(Body.IGNORED, t("收到 $app 的通知,正在忙,先放着", "A notification from $app came in while busy; kept for later"), text)
fun capped(app: String, text: String) = body(Body.IGNORED, t("收到 $app 的通知,这个小时看得太多了,先放着", "A notification from $app came in past the hourly limit; kept for later"), text)
fun undecided(app: String, text: String) = body(Body.IGNORED, t("收到 $app 的通知,没拿定主意,没处理", "A notification from $app came in; could not decide, left it"), text)
@@ -87,6 +89,8 @@ object TimelineEvents {
/** The row's mark, from the app's own icon set (an emoji would take whatever font the Mac has). */
fun mark(kind: String): AndeeIcon = when (kind) {
+ BrainEvent.Kind.STOPPED.name -> AndeeIcon.STOP
+ Body.TOLD.name -> AndeeIcon.CHAT
BrainEvent.Kind.WOKE.name, BrainEvent.Kind.NOTIFIED.name, Body.IGNORED.name -> AndeeIcon.ALERT_CIRCLE
BrainEvent.Kind.FRIEND_TASK.name -> AndeeIcon.FRIENDS
BrainEvent.Kind.REVIEWED.name, BrainEvent.Kind.FOLDED.name -> AndeeIcon.CHECK_CIRCLE