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: speaking first — bubbles, a plan, and the morning look

heychargingc2a918e86afe
diff --git a/CLAUDE.md b/CLAUDE.md
index 8b0bac2..becf281 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -588,6 +588,26 @@ The trap this introduced, caught before it compiled: `notified()` defers behind
`notified` is also not `submit`: it does not stamp `Notebook.touchActivity`, because the quiet-hour timer measures silence from the *user* and a chatty group would otherwise push the nightly review out all evening on their behalf.
+### Bubbles: the weakest way to speak first (`ui/NudgeUi.kt`, `brain/NudgeBook.kt`)
+
+`nudge` (local-only) holds a **silent** bubble over the folded ball — 「该喝水啦」, 「要帮你点外卖吗?」 [好][不用]. It is the opposite of a card on every axis: no TTS, no mic, no holding face, returns at once, never displaces a card, fades out if ignored. Design and what is still undone: `docs/design/proactive-nudge.zh-CN.md`. Four things are load-bearing:
+
+- **It shares the cards' one slot on the ball** (`CardUi.bubble` → `showSignboard(foldedWidth)`) and never gets a window of its own — one more overlay can push the combined opacity past the 0.80 that makes Android drop injected taps. A card arriving closes it as `superseded` and `NudgeUi` holds it again.
+- **A tap runs at the trust of the turn that wrote it** (`Nudge.untrusted` → `answerNudge` → `wake(untrusted = true)`). Same laundering `Todo.untrusted` closes: a stranger's notification must not get a trusted turn back for a 「好」.
+- **Budget, cooldown, quiet hours and mutes are device-side** (`NudgeBook.admit`), and a refusal is a normal result telling the model not to retry. `nudge` setting: unset = `few`, unrecognised = `off`, 关 leftmost.
+- **`nudgeGate` only ever holds, never drops** — the bubble's TTL decides when waiting stops being worth it. The `dismiss` button and a tap on a text-only bubble start no turn; voice never presses a bubble's button.
+- **The Mac has the same tool and the same `NudgeBook`** (`desktop/NudgeBubble.kt`: `Nudges` + `BubbleWindow`). There the bubble is its own non-focusable window beside the ball, like the prompt card and the caption — the Mac has no opacity ceiling and the ball's window is exactly the ball's size. "Unfolded card" becomes "chat window active" (→ a scrollback row), and "screen off" becomes five minutes with no keyboard or mouse input (`ioreg` `HIDIdleTime`). `uishot bubble` draws the card.
+
+### Plans: what it is trying to do, so speaking first has a reason (`config/Plans.kt`)
+
+Bubbles alone felt random — "no overall idea, no soul" was the user's verdict — so speaking first now hangs off a plan: **long-term directions** (what it is helping them get done; only from what they said, each with a `source`, ≤ 5 active) and a **day plan** (an intent in its own voice, items that each name a direction or todo in `because`, and a `quiet` list). Both live in the notebook's `plan` section, shared by both bodies like `Gear`. Design: `docs/design/proactive-nudge.zh-CN.md` §5–§6, §12.
+
+- **Timed `remind`/`ask` items become bubble todos** (`Plans.reconcile` → `Todo.nudge`): at their minute the device raises the bubble with **no model call**, and `recordOutcome` writes done / declined / ignored / skipped / missed back onto the item. Every plan write (tool or settings) and every start re-runs `reconcile` (`Scheduler.syncPlan` / `DesktopScheduler.syncPlan`). A bubble todo that comes due with nothing running is marked missed — never a notification, never a note to the brain.
+- **The review writes the plan** (`REVIEW_RULES` item 8), so a device nobody has talked to has none. After 20:00 it also drafts tomorrow's.
+- **The user sees and trims it in Settings → 它的打算.** Removing an item or pausing/removing a direction is done by the device at once and cannot be undone by the model (`userDropped`, `byUser`); anything else goes in through 告诉它一句 as an ordinary turn.
+- **`PlanMind` thinks about the plan without being asked, in two no-tool calls** (the triage pattern): `morning` once a day when the user first shows up (writes today's plan from directions, yesterday's outcomes, the draft, today's todos and the notebook — this is also what gives an unreviewed device a plan), and `muse` every ≥ 40 min while they are present, only for today's loose-time items, picking at most one. Timing state lives in the plan section's `meta`. Triggers: phone `USER_PRESENT` + a 10-min tick (`BodyCoreService.planTick`), Mac a 5-min tick with recent HID input (`PlanTicks`). Both fail closed — no key or a bad answer changes nothing. There is deliberately **no** "prepare while they are away" turn.
+- **`TurnGuards` refuses `note.directions` / `note.day_plan` on untrusted turns** — a planned bubble's tap is a trusted turn, so a stranger's words in the plan would be laundered.
+
### Scenes: ways of working it learned with this person (local brain only)
A scene (「陪我练英语」「帮我接管微信」「比价购物」) is a goal + voice + rules + routine that the model steps into for a while. It is **only a prompt** — no tool scoping, no scheduler of its own — and it is **learned, not shipped**: the model proposes one after the same kind of session has recurred, the user says yes, *then* `save_scene` writes it. `LocalPrompt` §11 is the whole teaching; the nightly review (`REVIEW_RULES` item 6) only leaves itself a `remember(type=feedback)` to propose one next time, because there is nobody to ask while it reviews.
diff --git a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
index 5ea11a1..c8cefd6 100644
--- a/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
+++ b/app/src/main/java/net/kuafuai/andee/BodyCoreService.kt
@@ -522,6 +522,19 @@ class BodyCoreService : Service() {
// windows — they need nothing but the WindowManager, but init them
// here where the service context is alive.
net.kuafuai.andee.ui.CardUi.init(this)
+ // Bubbles share the cards' slot on the ball; this decides when one may go up and what a tap on it
+ // starts. See [nudgeGate] and [answerNudge].
+ net.kuafuai.andee.ui.NudgeUi.init(
+ gate = ::nudgeGate,
+ onAnswer = ::answerNudge,
+ // A planned bubble's outcome goes back onto its plan item, so tonight's review can see it.
+ onOutcome = { n, how, button -> net.kuafuai.andee.config.Notebook.plans(this).recordOutcome(n, how, button) },
+ onMute = { n ->
+ net.kuafuai.andee.config.VoiceConfig.muteNudgeKind(this, n.kind)
+ // The user's setting just changed, by a gesture with no confirmation; they are owed the news.
+ net.kuafuai.andee.ui.ChatHistory.addAssistant(AppLocale.str(this, R.string.nudge_muted_row, n.text))
+ },
+ )
// The signboard's only source of work. Its listener is a separate
// service the system binds on its own schedule, and after an APK
// reinstall it routinely never rebinds — the permission still reads as
@@ -782,6 +795,7 @@ class BodyCoreService : Service() {
// and needs to be told the device is now mute.
startBrain(announce = false)
startWakeWord()
+ startPlanMind()
runStartupSelfCheck()
// Published last, deliberately: everything above builds the body, and
@@ -1650,6 +1664,8 @@ class BodyCoreService : Service() {
stopWsServer()
net.kuafuai.andee.wake.WakeWord.stop()
runCatching { unregisterReceiver(screenReceiver) }
+ runCatching { unregisterReceiver(presentReceiver) }
+ ui.removeCallbacks(planTickRunnable)
if (::asr.isInitialized) asr.shutdown()
if (::tts.isInitialized) tts.shutdown()
// Before audio.release(): it ends the recording, which needs the mic
@@ -2011,6 +2027,8 @@ class BodyCoreService : Service() {
// and the pinned tips live in this service and have to be told.
// See FloatingWindowUi.onLocaleChanged.
onLocaleChanged = { window.onLocaleChanged() },
+ // 它的打算 → 告诉它一句: an ordinary typed turn, so the model adjusts its own plan.
+ onTellBrain = { text -> ui.post { submitUserTurn(text, "typed") } },
)
settings = s
s.show()
@@ -2724,6 +2742,7 @@ class BodyCoreService : Service() {
// see [catchUpPromises] — but that is still better than an alarm
// that silently never comes back.
catchUpPromises()
+ net.kuafuai.andee.config.Scheduler.syncPlan(this)
return
}
android.util.Log.i(
@@ -2768,6 +2787,9 @@ class BodyCoreService : Service() {
// here, on the first start that can hear about it. This runs in hub
// mode too — see the early return above.
catchUpPromises()
+ // And the plan's bubbles: armed from the plan itself, so a reinstall or a lost alarm cannot leave a
+ // planned item silently unscheduled.
+ net.kuafuai.andee.config.Scheduler.syncPlan(this)
// The sweep is the other thing that only fires if the service is alive
// when its timer lands, so a process killed mid-quiet leaves a
// conversation that was never looked back at. Recover it here.
@@ -2878,6 +2900,11 @@ class BodyCoreService : Service() {
* defers itself if a turn is already running.
*/
fun wakeForTodo(todo: net.kuafuai.andee.config.Todo) {
+ // A planned bubble: shown by the device at its minute, no model involved. See [postPlanBubble].
+ if (todo.nudge.isNotEmpty()) {
+ postPlanBubble(todo)
+ return
+ }
val brain = localBrain
if (brain == null) {
// Nothing on this device can run a turn (no local brain — there is
@@ -3006,6 +3033,138 @@ class BodyCoreService : Service() {
}
/** Poll until nothing is speaking, asking or listening, or [WAKE_PATIENCE_MS] passes; then run [then]. */
+ // ---- the plan, thought about without being asked (PlanMind) ----------------------------
+
+ /** One worker: the morning look and the muse each block on a model call. */
+ private val planExec = java.util.concurrent.Executors.newSingleThreadExecutor { r ->
+ Thread(r, "plan-mind").apply { isDaemon = true }
+ }
+
+ private val planTickRunnable = object : Runnable {
+ override fun run() {
+ planTick()
+ ui.postDelayed(this, PLAN_TICK_MS)
+ }
+ }
+
+ /** Unlocking is the user arriving: the natural moment for the morning look. */
+ private val presentReceiver = object : android.content.BroadcastReceiver() {
+ override fun onReceive(c: android.content.Context, i: android.content.Intent) {
+ planTick()
+ }
+ }
+
+ private fun startPlanMind() {
+ androidx.core.content.ContextCompat.registerReceiver(
+ this,
+ presentReceiver,
+ android.content.IntentFilter(android.content.Intent.ACTION_USER_PRESENT),
+ androidx.core.content.ContextCompat.RECEIVER_NOT_EXPORTED,
+ )
+ ui.postDelayed(planTickRunnable, PLAN_FIRST_TICK_MS)
+ }
+
+ /**
+ * 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.
+ * 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()
+ planExec.execute {
+ val plans = net.kuafuai.andee.config.Notebook.plans(this)
+ val mind = net.kuafuai.andee.brain.PlanMind(cfg, plans) { warn, msg ->
+ if (warn) android.util.Log.w("Plan", msg) else android.util.Log.i("Plan", msg)
+ }
+ val lang = net.kuafuai.andee.config.VoiceConfig.uiLanguage(this)
+ val level = net.kuafuai.andee.brain.NudgeBook.Level.of(net.kuafuai.andee.config.VoiceConfig.nudgeLevel(this))
+ if (mind.morning(lang, level.perDay)) net.kuafuai.andee.config.Scheduler.syncPlan(this)
+ if (free && level != net.kuafuai.andee.brain.NudgeBook.Level.OFF) {
+ mind.muse(lang)?.let { id ->
+ plans.bubbleForItem(id, dispatcher.nudgeBook, level, net.kuafuai.andee.config.VoiceConfig.nudgeMuted(this))
+ ?.let(net.kuafuai.andee.ui.NudgeUi::post)
+ }
+ }
+ }
+ }
+
+ /**
+ * A planned bubble came due. The plan decides whether it is still worth showing and whether the user's
+ * limits allow it ([net.kuafuai.andee.config.Plans.bubbleFor]); the reason is written onto the item when
+ * not. Then it waits for its moment like any other bubble.
+ */
+ private fun postPlanBubble(todo: net.kuafuai.andee.config.Todo) {
+ val n = net.kuafuai.andee.config.Notebook.plans(this).bubbleFor(
+ todo,
+ dispatcher.nudgeBook,
+ net.kuafuai.andee.brain.NudgeBook.Level.of(net.kuafuai.andee.config.VoiceConfig.nudgeLevel(this)),
+ net.kuafuai.andee.config.VoiceConfig.nudgeMuted(this),
+ ) ?: return
+ net.kuafuai.andee.ui.NudgeUi.post(n)
+ }
+
+ /**
+ * Whether a bubble may go up right now. Main thread.
+ *
+ * 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.
+ */
+ 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
+ }
+
+ /**
+ * The user tapped a bubble's button (or the body of one with buttons): that is a turn.
+ *
+ * **It runs at the trust of the turn that wrote the bubble.** A bubble raised on a notification's turn
+ * carries a stranger's influence, and a 「好」 under it must not come back as the user's own request —
+ * so that one goes in as an untrusted wake, exactly like a todo set on such a turn ([wakeBrainFor]).
+ * Only the local brain raises bubbles (`nudge` is local-only), so there is no hub branch.
+ */
+ private fun answerNudge(n: net.kuafuai.andee.brain.Nudge, button: String?) {
+ if (exitRequested) return
+ val brain = localBrain ?: return
+ val text = net.kuafuai.andee.brain.NudgeBook.answerText(n, button)
+ // Task first, turn second. `submit` can answer synchronously (no key: it calls onFinal before it
+ // returns), and both begin and end are posts — begin queued after that end leaves the edge glow on
+ // until the 5-minute backstop. Measured on device.
+ acceptBrainOutput = true
+ dispatcher.beginTask()
+ window.setState(FloatingWindowUi.State.THINKING)
+ if (n.untrusted) {
+ brain.wake(text, untrusted = true)
+ } else {
+ // The same preparations [submitUserTurn] makes for any turn the user starts.
+ guestBrain?.cancel()
+ closeTyping()
+ dispatcher.beginTurn(null)
+ brain.submit(text)
+ }
+ }
+
private fun waitForQuiet(then: () -> Unit) {
Thread {
val until = android.os.SystemClock.uptimeMillis() + WAKE_PATIENCE_MS
@@ -3043,6 +3202,12 @@ class BodyCoreService : Service() {
val missed = net.kuafuai.andee.config.Scheduler.catchUp(this)
val brain = localBrain
for (todo in missed) {
+ // A planned bubble that came due while nothing ran: shown now if it is still worth it, else the
+ // plan item is marked missed. Never a note to the brain — nobody promised anything.
+ if (todo.nudge.isNotEmpty()) {
+ postPlanBubble(todo)
+ continue
+ }
if (brain != null) {
brain.note(
"(missed) you had promised: ${todo.what}" +
@@ -3239,6 +3404,10 @@ class BodyCoreService : Service() {
}
companion object {
+ /** How often to ask whether the plan wants thinking about; [PlanMind] decides whether it does. */
+ private const val PLAN_TICK_MS = 10 * 60_000L
+ private const val PLAN_FIRST_TICK_MS = 60_000L
+
private const val WS_PORT = 9008
/**
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 dc47ee2..121427f 100644
--- a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
+++ b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
@@ -79,6 +79,8 @@ class AndroidBrainHost(
override fun gearIndex(): String = dispatcher.gearShelf.indexForPrompt()
+ override fun planIndex(): String = net.kuafuai.andee.config.Notebook.plans(ctx).indexForPrompt()
+
override fun friendsIndex(): String = peers.tasks.indexForPrompt()
override fun topicsIndex(): String = ChatHistory.topicsForPrompt()
diff --git a/app/src/main/java/net/kuafuai/andee/config/AlarmReceiver.kt b/app/src/main/java/net/kuafuai/andee/config/AlarmReceiver.kt
index b030a3b..fbe52ca 100644
--- a/app/src/main/java/net/kuafuai/andee/config/AlarmReceiver.kt
+++ b/app/src/main/java/net/kuafuai/andee/config/AlarmReceiver.kt
@@ -92,6 +92,10 @@ class AlarmReceiver : BroadcastReceiver() {
if (service != null) {
Log.i(TAG, "todo due: ${todo.what.take(60)} — handing it to the service")
service.wakeForTodo(patched)
+ } else if (patched.nudge.isNotEmpty()) {
+ // A planned bubble is fine to miss, and a notification for one would be the loud version of the
+ // quiet thing it was. The plan item records it.
+ Notebook.plans(context).missed(patched)
} else {
// Nothing is running, so nothing can act on it. Say so — a silent
// drop here is the exact failure the whole feature exists to
@@ -116,7 +120,9 @@ class AlarmReceiver : BroadcastReceiver() {
Log.e(TAG, "catch-up after boot failed", it)
emptyList()
}
- for (todo in missed.take(3)) Scheduler.notifyMissed(context, todo)
+ val (bubbles, promises) = missed.partition { it.nudge.isNotEmpty() }
+ bubbles.forEach { Notebook.plans(context).missed(it) }
+ for (todo in promises.take(3)) Scheduler.notifyMissed(context, todo)
// The sweep timer is deliberately NOT armed here: it is armed at the
// end of a turn, and arming it at boot would sweep a conversation the
// user has not had yet.
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 0bda6ed..bd15092 100644
--- a/app/src/main/java/net/kuafuai/andee/config/Notebook.kt
+++ b/app/src/main/java/net/kuafuai/andee/config/Notebook.kt
@@ -100,6 +100,16 @@ object Notebook {
}
}
+ @Volatile
+ private var plans: net.kuafuai.andee.config.Plans? = null
+
+ /**
+ * Directions and day plans, kept inside the notebook's own file. One instance per process: its lock is
+ * what keeps a tool write and a settings tap from interleaving their read-modify-write of the section.
+ */
+ fun plans(context: Context): net.kuafuai.andee.config.Plans =
+ plans ?: synchronized(this) { plans ?: net.kuafuai.andee.config.Plans(book(context)).also { plans = it } }
+
/** The gear shelf (what is installed, what it is for), kept inside the notebook's own file. */
fun gear(context: Context): net.kuafuai.andee.config.Gear = net.kuafuai.andee.config.Gear(book(context))
diff --git a/app/src/main/java/net/kuafuai/andee/config/Scheduler.kt b/app/src/main/java/net/kuafuai/andee/config/Scheduler.kt
index ded67da..f35e6ba 100644
--- a/app/src/main/java/net/kuafuai/andee/config/Scheduler.kt
+++ b/app/src/main/java/net/kuafuai/andee/config/Scheduler.kt
@@ -121,6 +121,17 @@ object Scheduler {
}
}
+ /**
+ * Bring the plan's bubble alarms in line with the plan ([net.kuafuai.andee.config.Plans.reconcile]). After
+ * every plan write — by the model or by the user in settings — and once at start.
+ */
+ fun syncPlan(context: Context) {
+ val s = Notebook.plans(context).reconcile()
+ s.cancel.forEach { cancelTodo(context, it) }
+ s.arm.forEach { armTodo(context, it) }
+ if (s.arm.isNotEmpty() || s.cancel.isNotEmpty()) Log.i(TAG, "plan: armed ${s.arm.size}, cancelled ${s.cancel.size}")
+ }
+
fun cancelTodo(context: Context, id: String) {
runCatching {
am(context).cancel(todoIntent(context, id))
diff --git a/app/src/main/java/net/kuafuai/andee/config/VoiceConfig.kt b/app/src/main/java/net/kuafuai/andee/config/VoiceConfig.kt
index f06150d..3718539 100644
--- a/app/src/main/java/net/kuafuai/andee/config/VoiceConfig.kt
+++ b/app/src/main/java/net/kuafuai/andee/config/VoiceConfig.kt
@@ -687,6 +687,7 @@ object VoiceConfig {
"llm_reasoning_effort" to bc.reasoningEffort,
"grounding" to p.getString("grounding", "off")!!,
"notify" to notifyScope(context),
+ "nudge" to nudgeLevel(context),
"lang" to uiLanguage(context),
"sweep" to p.getString("sweep", "on")!!,
"sweep_quiet_minutes" to p.getString(
@@ -844,6 +845,30 @@ object VoiceConfig {
* reader: the scene-ended event, which must not tell the brain what the
* brain itself just did (a second turn to say "you left the scene").
*/
+ /**
+ * How many bubbles the device may raise by itself: `off` / `few` / `normal`, read through
+ * [net.kuafuai.andee.brain.NudgeBook.Level.of]. **Unset is `few` and unrecognised is `off`** — the
+ * split [notifyScope] draws, for its reasons, and the picker lists 关 leftmost to match.
+ */
+ fun nudgeLevel(context: Context): String =
+ net.kuafuai.andee.brain.NudgeBook.Level.of(
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("nudge", null),
+ ).key
+
+ /** Bubble kinds the user long-pressed away. Written directly, like `scene`: it is a set, not a field. */
+ fun nudgeMuted(context: Context): Set<String> =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ .getStringSet("nudge_muted", emptySet()).orEmpty().toSet()
+
+ fun muteNudgeKind(context: Context, kind: String) {
+ val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ p.edit().putStringSet("nudge_muted", nudgeMuted(context) + kind).apply()
+ }
+
+ fun clearNudgeMuted(context: Context) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove("nudge_muted").apply()
+ }
+
fun setActiveScene(context: Context, name: String?, byBrain: Boolean = false) {
val next = name?.trim().orEmpty()
val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
@@ -916,6 +941,7 @@ object VoiceConfig {
"llm_thinking", "llm_reasoning_effort",
"grounding",
"notify",
+ "nudge",
"lang",
"ball",
"sweep", "sweep_quiet_minutes", "sweep_daily_cap",
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 e601d7f..399f9e3 100644
--- a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
+++ b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
@@ -158,6 +158,9 @@ class CommandDispatcher(
) {
private val ui = Handler(Looper.getMainLooper())
+ /** The bubble budget. One per dispatcher, so a service restart starts the count again — see [NudgeBook]. */
+ val nudgeBook = net.kuafuai.andee.brain.NudgeBook()
+
/**
* Put the two guards on a freshly built screen controller.
*
@@ -836,6 +839,29 @@ class CommandDispatcher(
.put("how", r.how)
.put("read", true)
}
+ "ui.nudge" -> {
+ // Malformed → throws for the model to fix. Over budget → a normal result that says why: that
+ // is the user's limit, not a mistake, and "do not retry" has to reach the model as an answer.
+ val n = nudgeBook.parse(params, untrusted)
+ val refusal = nudgeBook.admit(
+ n,
+ net.kuafuai.andee.brain.NudgeBook.Level.of(VoiceConfig.nudgeLevel(appContext)),
+ VoiceConfig.nudgeMuted(appContext),
+ )
+ if (refusal != null) {
+ JSONObject().put("queued", false).put("reason", refusal)
+ } else {
+ net.kuafuai.andee.ui.NudgeUi.post(n)
+ JSONObject()
+ .put("queued", true)
+ .put(
+ "note",
+ "Queued. It goes up when the user is free and is dropped after its ttl. You will hear " +
+ "back only if they tap a button that is not `dismiss` — do not wait for it, and do " +
+ "not also say it out loud.",
+ )
+ }
+ }
"ui.show_html" -> {
val html = requireNotNull(params?.optString("html")?.ifEmpty { null }) { "ui.show_html requires html" }
// Reuses `html_default_title`, the same resource
@@ -1478,6 +1504,16 @@ class CommandDispatcher(
)
}
+ // The plan (`Plans`): shared logic in core; here only the alarms it asks for.
+ "note.directions", "note.day_plan" -> {
+ val r = Notebook.plans(appContext).handle(
+ method,
+ params,
+ net.kuafuai.andee.brain.NudgeBook.Level.of(VoiceConfig.nudgeLevel(appContext)).perDay,
+ )
+ if (method == "note.day_plan") Scheduler.syncPlan(appContext)
+ r
+ }
"note.todos" -> {
val action = params?.optString("action")?.trim()?.lowercase().orEmpty()
require(action in listOf("list", "done", "drop", "pause", "resume")) {
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 49dee56..836dd3e 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/CardUi.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/CardUi.kt
@@ -162,6 +162,12 @@ object CardUi {
*/
fun isAsking(): Boolean = current?.let { !it.finished && it.captureSpeech } == true
+ /**
+ * A real card (not a bubble) is up. A bubble yields to every card and never replaces one — see
+ * [bubble]. Snapshot, readable from any thread.
+ */
+ fun isCardUp(): Boolean = current?.let { !it.finished && !it.bubble } == true
+
fun dismissCurrent() {
main.post { current?.close("superseded") }
}
@@ -216,6 +222,9 @@ object CardUi {
private fun decideVoice(said: String): VoiceOutcome {
val handle = current ?: return VoiceOutcome.NOT_HANDLED
if (handle.finished) return VoiceOutcome.NOT_HANDLED
+ // A bubble was never spoken, so nothing the user says is an answer to it: a 「好」 meant for
+ // something else must not press a button they may not even have read.
+ if (handle.bubble) return VoiceOutcome.NOT_HANDLED
val spoken = normalizeForMatch(said)
val hit = handle.buttons.firstOrNull { label ->
val l = normalizeForMatch(label)
@@ -246,6 +255,8 @@ object CardUi {
val buttons: List<String>,
/** Whether speech that names no button should still answer this card. */
val captureSpeech: Boolean = false,
+ /** A silent [bubble], not a card: yields to cards and is never answered by voice. */
+ val bubble: Boolean = false,
@Volatile var finished: Boolean = false,
var onDone: ((Result) -> Unit)? = null,
var timeout: Runnable? = null,
@@ -515,6 +526,117 @@ object CardUi {
}
}
+ /**
+ * A silent bubble over the folded ball — the weakest way the device speaks first. See `NudgeUi`,
+ * which decides *when*; this only draws it.
+ *
+ * Everything a card does to get attention, this does not: no speech, no mic, no holding face, and it
+ * never displaces anything. It is shown only into an empty slot on a folded ball, and [onDone] fires
+ * with `busy` otherwise so the caller can hold it. A card arriving while it is up closes it with
+ * `superseded` (the ordinary one-signboard rule), which the caller also treats as "hold it again".
+ *
+ * Same window as the cards ([FloatingWindowUi.showSignboard]) and never a window of its own: one more
+ * overlay could push the combined opacity past the 0.80 at which Android silently drops the brain's
+ * injected taps.
+ *
+ * [onDone]'s `how`: `button` (with the label), `body` (the bubble itself), `mute` (long press),
+ * `timeout` (faded out unanswered), `superseded`, or `busy` (never shown). Main thread.
+ */
+ fun bubble(text: String, buttons: List<String>, stayMs: Long, onDone: (Result) -> Unit) {
+ main.post {
+ val context = appContext
+ val host = ballWindow()
+ if (current != null || context == null || host == null || !host.isShown() || !host.isFolded()) {
+ onDone(Result(null, "busy"))
+ return@post
+ }
+ val density = android.content.res.Resources.getSystem().displayMetrics.density
+ fun dp(v: Int) = (v * density).toInt()
+ val view = TailLinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ cornerRadius = dp(18)
+ setPadding(dp(16), dp(11), dp(16), dp(11))
+ }
+ val body = TextView(context).apply {
+ this.text = text
+ setTextColor(Color.parseColor(Glass.TITLE))
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, Glass.Type.BODY)
+ setLineSpacing(dp(2).toFloat(), 1f)
+ maxLines = 3
+ ellipsize = android.text.TextUtils.TruncateAt.END
+ gravity = Gravity.CENTER_HORIZONTAL
+ }
+ view.addView(body, LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,
+ ))
+ val btnViews = mutableListOf<TextView>()
+ if (buttons.isNotEmpty()) {
+ val row = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER
+ setPadding(0, dp(8), 0, 0)
+ }
+ buttons.forEachIndexed { i, label ->
+ val btn = TextView(context).apply {
+ this.text = label
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, Glass.Type.BODY)
+ setPadding(dp(14), dp(5), dp(14), dp(5))
+ gravity = Gravity.CENTER
+ isClickable = true
+ isFocusable = false
+ background = if (i == 0) Glass.tinted(context, dp(16)) else Glass.thumb(context, dp(16))
+ setTextColor(Color.parseColor(if (i == 0) Glass.ON_TINT else Glass.LABEL))
+ Glass.pressable(this)
+ }
+ row.addView(btn, LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,
+ ).apply { if (i > 0) marginStart = dp(8) })
+ btnViews.add(btn)
+ }
+ view.addView(row)
+ }
+ // As narrow as the words allow: a card-wide pane for 「该喝水啦」 is a card.
+ view.measure(
+ View.MeasureSpec.makeMeasureSpec(dp(BUBBLE_MAX_WIDTH_DP), View.MeasureSpec.AT_MOST),
+ View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
+ )
+ val width = maxOf(view.measuredWidth, dp(BUBBLE_MIN_WIDTH_DP))
+ view.tailX = width / 2
+
+ val handle = CardHandle(view, host, buttons, bubble = true)
+ handle.onDone = { r -> main.post { onDone(r) } }
+ buttons.forEachIndexed { i, label -> btnViews[i].setOnClickListener { handle.close("button", label) } }
+ view.setOnClickListener { handle.close("body") }
+ body.setOnClickListener { handle.close("body") }
+ val mute = View.OnLongClickListener { handle.close("mute"); true }
+ view.setOnLongClickListener(mute)
+ body.setOnLongClickListener(mute)
+ // Fades rather than blinks out: a bubble leaving on its own should not look like one that broke.
+ // The backstop is for a detached view, which never delivers its end action; close() runs once.
+ val timeoutRunnable = Runnable {
+ view.animate().alpha(0f).setDuration(BUBBLE_FADE_MS).withEndAction { handle.close("timeout") }.start()
+ main.postDelayed({ handle.close("timeout") }, BUBBLE_FADE_MS + 200)
+ }
+ handle.timeout = timeoutRunnable
+ if (host.showSignboard(view, foldedWidth = width)) {
+ current = handle
+ ensureEvictorWired(host)
+ view.pivotX = width / 2f
+ view.pivotY = view.measuredHeight.toFloat()
+ Glass.enter(view)
+ host.greet()
+ main.postDelayed(timeoutRunnable, stayMs)
+ } else {
+ handle.finished = true
+ onDone(Result(null, "busy"))
+ }
+ }
+ }
+
+ private const val BUBBLE_MAX_WIDTH_DP = 300
+ private const val BUBBLE_MIN_WIDTH_DP = 120
+ private const val BUBBLE_FADE_MS = 260L
+
/** Shared button wiring for both the hosted and the fallback card. */
private fun wireButtons(
handle: CardHandle,
diff --git a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt
index 22aabdb..4c9a5a4 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt
@@ -673,8 +673,12 @@ class FloatingWindowUi(
*
* Main thread only. One signboard at a time; false when there is no
* window to host it (caller falls back to its own overlay).
+ *
+ * [foldedWidth] narrows the window while folded, for a bubble that would
+ * look lost in a card-wide pane. Never narrower than the ball itself, or
+ * the ball area would be clipped by its own window.
*/
- fun showSignboard(content: View): Boolean {
+ fun showSignboard(content: View, foldedWidth: Int? = null): Boolean {
val v = root ?: return false
val p = params ?: return false
if (signboard != null) return false
@@ -691,7 +695,8 @@ class FloatingWindowUi(
val side = dp(COMPACT_DP)
// The width the card will get; measured here so the window can grow
// by exactly the card's height in the same updateViewLayout.
- val w = minOf(dm.widthPixels - dp(32), dp(560))
+ val w = foldedWidth?.coerceIn(side, dm.widthPixels - dp(32))
+ ?: minOf(dm.widthPixels - dp(32), dp(560))
content.measure(
View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
@@ -1029,6 +1034,11 @@ class FloatingWindowUi(
ui.post { ball?.signalOutcome(ok) }
}
+ /** A bubble went up that nobody asked for: wave once so the eye finds it. See `NudgeUi`. */
+ fun greet() {
+ ui.post { ball?.greet() }
+ }
+
/**
* The user changed the language in 设置. Re-read everything the window is
* showing right now.
diff --git a/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt b/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt
new file mode 100644
index 0000000..a064e06
--- /dev/null
+++ b/app/src/main/java/net/kuafuai/andee/ui/NudgeUi.kt
@@ -0,0 +1,153 @@
+package net.kuafuai.andee.ui
+
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import net.kuafuai.andee.brain.Nudge
+
+/**
+ * *When* a bubble goes up; [CardUi.bubble] is *how*. See `docs/design/proactive-nudge.zh-CN.md` §4.
+ *
+ * A bubble is something that is fine to miss, so this never makes the user's moment fit the bubble — the
+ * bubble waits for the moment. [gate] is asked before every attempt and answers [Gate.WAIT] whenever the
+ * user is busy with something else; a waiting bubble is retried every [RETRY_MS] until its TTL runs out,
+ * and is then dropped without a word, because 「该喝水啦」 three hours late is noise.
+ *
+ * **One held at a time, and the newest wins.** A queue of bubbles is push spam with extra steps — the same
+ * reason [CardUi] shows one card at a time.
+ *
+ * Main thread for everything; [post] may be called from anywhere.
+ */
+object NudgeUi {
+
+ enum class Gate {
+ /** Nothing in the way: try to show it. */
+ SHOW,
+
+ /** The user is busy (a card, speech, a task, a locked screen, quiet hours): hold it. */
+ WAIT,
+
+ /**
+ * The card is unfolded and the user is reading the scrollback: a bubble hanging off a full-screen
+ * card would be odd, so it is written there as a row instead and is done.
+ */
+ LOG,
+ }
+
+ private const val TAG = "Nudge"
+ private const val RETRY_MS = 5_000L
+ private const val STAY_TEXT_MS = 12_000L
+ private const val STAY_BUTTONS_MS = 30_000L
+
+ private val main = Handler(Looper.getMainLooper())
+
+ /** The bubble and whether its words are already in the scrollback — written once, however often it is re-held. */
+ private class Slot(val n: Nudge, var recorded: Boolean = false)
+
+ private var held: Slot? = null
+ private var showing: Slot? = null
+
+ private var gate: () -> Gate = { Gate.WAIT }
+ private var onAnswer: (Nudge, String?) -> Unit = { _, _ -> }
+ private var onMute: (Nudge) -> Unit = { }
+ private var onOutcome: (Nudge, String, String?) -> Unit = { _, _, _ -> }
+
+ /**
+ * @param onAnswer the user tapped a button that is not the `dismiss` one (label), or the body of a bubble
+ * that has buttons (null). Starts a turn.
+ * @param onMute the user long-pressed: never this kind again.
+ * @param onOutcome how every bubble ended (`button`, `body`, `mute`, `timeout`, `logged`, `expired`), for a
+ * planned one to be written back onto its plan item.
+ */
+ fun init(
+ gate: () -> Gate,
+ onAnswer: (Nudge, String?) -> Unit,
+ onMute: (Nudge) -> Unit,
+ onOutcome: (Nudge, String, String?) -> Unit = { _, _, _ -> },
+ ) {
+ this.gate = gate
+ this.onAnswer = onAnswer
+ this.onMute = onMute
+ this.onOutcome = onOutcome
+ }
+
+ fun post(n: Nudge) {
+ main.post {
+ held?.let { Log.i(TAG, "replaced a held bubble: ${it.n.text}") }
+ held = Slot(n)
+ pump()
+ }
+ }
+
+ private val retry = Runnable { pump() }
+
+ private fun pump() {
+ main.removeCallbacks(retry)
+ val slot = held ?: return
+ if (System.currentTimeMillis() >= slot.n.expiresAt) {
+ Log.i(TAG, "expired before it could be shown: ${slot.n.text}")
+ held = null
+ onOutcome(slot.n, "expired", null)
+ return
+ }
+ if (showing != null) {
+ // Its own end calls pump again.
+ return
+ }
+ when (gate()) {
+ Gate.WAIT -> main.postDelayed(retry, RETRY_MS)
+ Gate.LOG -> {
+ held = null
+ record(slot)
+ onOutcome(slot.n, "logged", null)
+ }
+ Gate.SHOW -> {
+ held = null
+ showing = slot
+ val stay = if (slot.n.buttons.isEmpty()) STAY_TEXT_MS else STAY_BUTTONS_MS
+ CardUi.bubble(slot.n.text, slot.n.buttons, stay) { r ->
+ showing = null
+ if (r.how != "busy") record(slot)
+ 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") {
+ main.postDelayed(retry, RETRY_MS)
+ } else {
+ pump()
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * The bubble's words go in the scrollback when they first reach the user: they were said, and a user
+ * who looks back for "what was it saying" should find it. Never twice for one bubble.
+ */
+ private fun record(slot: Slot) {
+ if (slot.recorded) return
+ slot.recorded = true
+ ChatHistory.addAssistant(slot.n.text)
+ }
+
+ private fun finish(slot: Slot, r: CardUi.Result) {
+ val n = slot.n
+ Log.i(TAG, "${r.how}${r.button?.let { " [$it]" } ?: ""}: ${n.text}")
+ onOutcome(n, r.how, r.button)
+ when (r.how) {
+ "button" -> {
+ val b = r.button ?: return
+ if (b == n.dismiss) return
+ ChatHistory.addUser(b)
+ onAnswer(n, b)
+ }
+ // Tapping a bubble that only says something is "seen", not "let's talk".
+ "body" -> if (n.buttons.isNotEmpty()) onAnswer(n, null)
+ "mute" -> onMute(n)
+ // Never reached the user, or a card took its place: hold it again unless something newer is held.
+ "busy", "superseded" -> if (held == null) held = slot
+ else -> Unit
+ }
+ }
+}
diff --git a/app/src/main/java/net/kuafuai/andee/ui/SettingsUi.kt b/app/src/main/java/net/kuafuai/andee/ui/SettingsUi.kt
index ce18099..ea32fda 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/SettingsUi.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/SettingsUi.kt
@@ -127,6 +127,11 @@ class SettingsUi(
* the page it just opened.
*/
private val onOpenLink: (String) -> Unit = {},
+ /**
+ * The user typed a line to it from 它的打算 («今天别提喝水了»). Wired to the service's own user-turn path;
+ * null hides the box, because a box that sends nowhere is worse than none.
+ */
+ private val onTellBrain: ((String) -> Unit)? = null,
) {
private val wm: WindowManager =
@@ -385,6 +390,8 @@ class SettingsUi(
notebookSection(form)
gearSection(form)
notifySection(form)
+ nudgeSection(form)
+ planSection(form)
vaultSection(form)
maxStepsSection(form)
@@ -1339,6 +1346,177 @@ class SettingsUi(
)
}
+ /**
+ * How often the ball may hold up a bubble nobody asked for. Beside the notification setting because it is
+ * the same decision — how much this thing may interrupt — and 关 is leftmost because it is the fallback
+ * for a value nobody recognises (see `VoiceConfig.nudgeLevel`; unset reads as 少).
+ */
+ private fun nudgeSection(form: LinearLayout) {
+ val panel = group(form, lctx.getString(R.string.settings_section_nudge))
+ segmented(
+ panel,
+ "nudge",
+ listOf(
+ "off" to lctx.getString(R.string.common_off),
+ "few" to lctx.getString(R.string.settings_nudge_few),
+ "normal" to lctx.getString(R.string.settings_nudge_normal),
+ ),
+ )
+ note(panel, lctx.getString(R.string.settings_nudge_note))
+ // The way back from a long-press, which mutes with no confirmation — without this the only undo was
+ // a factory reset. Written at once, like the language: there is nothing to cancel about un-muting.
+ val muted = VoiceConfig.nudgeMuted(context)
+ if (muted.isNotEmpty()) {
+ val line = noteView(lctx.getString(R.string.settings_nudge_muted, muted.sorted().joinToString("、")))
+ panel.addView(line, rowParams(dp(10)))
+ lateinit var unmute: TextView
+ unmute = button(lctx.getString(R.string.settings_nudge_unmute), filled = false) {
+ VoiceConfig.clearNudgeMuted(context)
+ line.visibility = View.GONE
+ unmute.visibility = View.GONE
+ }
+ panel.addView(unmute, rowParams(dp(10)))
+ }
+ }
+
+ /**
+ * 它的打算: the plan, readable and trimmable by the person it is about (`Plans`, design doc §5.5).
+ *
+ * Removing and pausing are done by the device at once, not asked of the model — the plan is theirs to
+ * cut — and the alarms follow in the same tap (`Scheduler.syncPlan`). Anything subtler goes through the
+ * box at the bottom as an ordinary message, and the model changes the plan itself.
+ */
+ private fun planSection(form: LinearLayout) {
+ val panel = group(form, lctx.getString(R.string.settings_section_plan))
+ val box = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
+ panel.addView(box, matchWrap())
+ fun fill() {
+ box.removeAllViews()
+ val plans = net.kuafuai.andee.config.Notebook.plans(context)
+ val day = plans.day(plans.today())
+ rowLabel(box, lctx.getString(R.string.settings_plan_today))
+ if (day == null) {
+ note(box, lctx.getString(R.string.settings_plan_none_today))
+ } else {
+ box.addView(noteView(day.intent).apply {
+ setTextColor(Color.parseColor(Glass.TITLE))
+ textSize = Glass.Type.BODY
+ }, rowParams(dp(8)))
+ for (it in day.items.sortedBy { i -> i.time.ifEmpty { "99" } }) {
+ val live = it.status == "planned"
+ val line = "${it.time.ifEmpty { it.slot }.ifEmpty { "·" }} ${kindLabel(it.kind)} ${it.what}"
+ planRow(box, line, statusLabel(it.status), live) {
+ if (live) {
+ plans.dropItemByUser(day.date, it.id)
+ net.kuafuai.andee.config.Scheduler.syncPlan(context)
+ fill()
+ }
+ }
+ }
+ if (day.quiet.isNotEmpty()) note(box, lctx.getString(R.string.settings_plan_quiet, day.quiet.joinToString(";")))
+ }
+ rowLabel(box, lctx.getString(R.string.settings_plan_directions))
+ val dirs = plans.directions().filter { d -> d.status != "dropped" && d.status != "done" }
+ if (dirs.isEmpty()) note(box, lctx.getString(R.string.settings_plan_none_directions))
+ for (d in dirs) {
+ val paused = d.status == "paused"
+ val row = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ row.addView(noteView(d.title + if (d.howIHelp.isNotEmpty()) " — ${d.howIHelp}" else "").apply {
+ alpha = if (paused) 0.5f else 1f
+ }, LinearLayout.LayoutParams(0, WRAP, 1f))
+ row.addView(smallLink(lctx.getString(if (paused) R.string.settings_plan_resume else R.string.settings_plan_pause)) {
+ plans.setDirectionByUser(d.id, if (paused) "active" else "paused")
+ fill()
+ })
+ row.addView(smallLink(lctx.getString(R.string.settings_plan_remove)) {
+ plans.setDirectionByUser(d.id, "dropped")
+ fill()
+ })
+ box.addView(row, rowParams(dp(8)))
+ }
+ }
+ fill()
+ val tell = onTellBrain ?: return
+ rowLabel(panel, lctx.getString(R.string.settings_plan_tell))
+ val row = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ val et = EditText(context).apply {
+ background = Glass.well(context, dp(13))
+ setPadding(dp(14), dp(13), dp(14), dp(13))
+ setTextColor(Color.parseColor(Glass.TITLE))
+ setHintTextColor(Color.parseColor(Glass.MUTED))
+ textSize = Glass.Type.BODY
+ isSingleLine = true
+ inputType = InputType.TYPE_CLASS_TEXT
+ hint = lctx.getString(R.string.settings_plan_tell_hint)
+ }
+ row.addView(et, LinearLayout.LayoutParams(0, WRAP, 1f))
+ val sent = noteView("")
+ row.addView(smallLink(lctx.getString(R.string.settings_plan_send)) {
+ val text = et.text?.toString().orEmpty().trim()
+ if (text.isEmpty()) return@smallLink
+ tell(text)
+ et.setText("")
+ sent.text = lctx.getString(R.string.settings_plan_sent)
+ })
+ panel.addView(row, rowParams(dp(5)))
+ panel.addView(sent, rowParams(dp(6)))
+ }
+
+ /** One plan item: what, its state, and ✕ while it is still to come. */
+ private fun planRow(parent: LinearLayout, text: String, status: String, removable: Boolean, onRemove: () -> Unit) {
+ val row = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ row.addView(noteView(text).apply { alpha = if (removable) 1f else 0.6f }, LinearLayout.LayoutParams(0, WRAP, 1f))
+ row.addView(TextView(context).apply {
+ this.text = status
+ textSize = Glass.Type.CAPTION
+ setTextColor(Color.parseColor(Glass.MUTED))
+ setPadding(dp(10), 0, dp(4), 0)
+ })
+ if (removable) row.addView(smallLink("✕", onRemove))
+ parent.addView(row, rowParams(dp(6)))
+ }
+
+ private fun smallLink(label: String, onClick: () -> Unit): TextView = TextView(context).apply {
+ text = label
+ textSize = Glass.Type.CAPTION
+ setTextColor(Color.parseColor(Glass.ACCENT))
+ setPadding(dp(10), dp(8), dp(4), dp(8))
+ isClickable = true
+ Glass.pressable(this)
+ setOnClickListener { onClick() }
+ }
+
+ private fun kindLabel(kind: String): String = lctx.getString(
+ when (kind) {
+ "ask" -> R.string.settings_plan_kind_ask
+ "prepare" -> R.string.settings_plan_kind_prepare
+ "follow_up" -> R.string.settings_plan_kind_follow_up
+ else -> R.string.settings_plan_kind_remind
+ },
+ )
+
+ private fun statusLabel(status: String): String = lctx.getString(
+ when (status) {
+ "done" -> R.string.settings_plan_st_done
+ "declined" -> R.string.settings_plan_st_declined
+ "ignored" -> R.string.settings_plan_st_ignored
+ "missed" -> R.string.settings_plan_st_missed
+ "skipped" -> R.string.settings_plan_st_skipped
+ "moved" -> R.string.settings_plan_st_moved
+ "dropped" -> R.string.settings_plan_st_dropped
+ else -> R.string.settings_plan_st_planned
+ },
+ )
+
// ---- Widgets ----
/** Section title + its panel. Returns the panel; rows go in there. */
diff --git a/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallTextureView.kt b/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallTextureView.kt
index 7e38339..2ac70d2 100644
--- a/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallTextureView.kt
+++ b/app/src/main/java/net/kuafuai/andee/ui/ball/EmotionBallTextureView.kt
@@ -100,6 +100,11 @@ class EmotionBallTextureView @JvmOverloads constructor(
renderer.signalOutcome(ok)
}
+ /** A bubble the ball raised by itself just went up. */
+ fun greet() {
+ renderer.greet()
+ }
+
/** One-shot body gesture, e.g. a nod when the mic opens. */
fun trigger(action: Action) {
renderer.request(action)
diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml
index f7ffc6f..348cce3 100644
--- a/app/src/main/res/values-en/strings.xml
+++ b/app/src/main/res/values-en/strings.xml
@@ -221,6 +221,38 @@
<string name="settings_notify_chat">Chat apps</string>
<string name="settings_notify_all">Everything</string>
<string name="settings_notify_note">When a message arrives it decides for itself whether it is worth your attention: lets the noise go, says the useful part out loud, handles what needs handling. \"Chat apps\" means the ones with a person on the other end — WeChat, QQ, DingTalk, Lark, SMS. \"Everything\" watches the rest too, minus progress bars and permanent notifications. It only puts a card up when it cannot decide. Off means nothing interrupts you — the messages are all still there, and you can ask about them whenever.</string>
+ <string name="nudge_muted_row">OK, nothing like \"%1$s\" again. To bring it back: Settings → Speaking first.</string>
+ <string name="settings_section_nudge">Speaking first</string>
+ <string name="settings_nudge_few">Rarely</string>
+ <string name="settings_nudge_normal">Normal</string>
+ <string name="settings_nudge_note">Now and then a small bubble appears over the ball — \"Time for some water\", \"Want me to order lunch?\". It makes no sound and fades by itself if you ignore it, and it never shows while you are busy, talking, locked or at night (22:30–8:00). \"Rarely\" is at most 1 an hour and 4 a day, \"Normal\" 2 an hour and 8 a day. Long-press a bubble and that kind never comes back.</string>
+ <string name="settings_nudge_muted">Turned off by long-press: %1$s</string>
+ <string name="settings_nudge_unmute">Bring them all back</string>
+ <string name="settings_section_plan">Its plans</string>
+ <string name="settings_plan_today">Today</string>
+ <string name="settings_plan_none_today">No plan for today yet. It writes one when it looks back over a quiet stretch.</string>
+ <string name="settings_plan_quiet">Not bothering you today about: %1$s</string>
+ <string name="settings_plan_directions">What it is helping you with</string>
+ <string name="settings_plan_none_directions">Nothing yet. It only writes these from things you have said.</string>
+ <string name="settings_plan_pause">Pause</string>
+ <string name="settings_plan_resume">Resume</string>
+ <string name="settings_plan_remove">Remove</string>
+ <string name="settings_plan_tell">Tell it something</string>
+ <string name="settings_plan_tell_hint">e.g. no water reminders today</string>
+ <string name="settings_plan_send">Send</string>
+ <string name="settings_plan_sent">Passed on — it will adjust its plan.</string>
+ <string name="settings_plan_kind_remind">remind</string>
+ <string name="settings_plan_kind_ask">ask</string>
+ <string name="settings_plan_kind_prepare">prepare</string>
+ <string name="settings_plan_kind_follow_up">follow up</string>
+ <string name="settings_plan_st_planned">to do</string>
+ <string name="settings_plan_st_done">done</string>
+ <string name="settings_plan_st_declined">declined</string>
+ <string name="settings_plan_st_ignored">ignored</string>
+ <string name="settings_plan_st_missed">missed</string>
+ <string name="settings_plan_st_skipped">skipped</string>
+ <string name="settings_plan_st_moved">moved</string>
+ <string name="settings_plan_st_dropped">removed</string>
<string name="settings_section_typing">Typing</string>
<string name="settings_typing_no_ime">ADBKeyboard is the only keyboard on this device and it has no keyboard UI, so nothing can be typed right now. Enable one in system settings and it will show up here.</string>
<string name="settings_typing_current">Your keyboard</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 2eaec73..9982b74 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -198,6 +198,38 @@
<string name="settings_notify_chat">聊天类</string>
<string name="settings_notify_all">全部</string>
<string name="settings_notify_note">来消息的时候,它先自己看一眼值不值当:没事的就放过,要紧的说一声,该办的直接去办。「聊天类」是微信、QQ、钉钉、飞书、短信这些有人在那头的;「全部」连其它 App 也一起看(进度条、常驻通知除外)。拿不准的才弹牌子问你。关掉就谁也不打扰你 —— 消息都还在,想知道的时候问它一声就行。</string>
+ <string name="nudge_muted_row">好,像「%1$s」这样的以后不提了。想恢复,到 设置 → 主动招呼。</string>
+ <string name="settings_section_nudge">主动招呼</string>
+ <string name="settings_nudge_few">少</string>
+ <string name="settings_nudge_normal">正常</string>
+ <string name="settings_nudge_note">它有时会在球的头上冒一个小气泡,比如「该喝水啦」「要帮你点外卖吗?」。不出声,不理它几秒后就自己消失;你在忙、在说话、锁屏或者夜里(22:30–8:00)都不会出。「少」是每小时最多 1 个、每天 4 个,「正常」是每小时 2 个、每天 8 个。长按某个气泡,这一类以后就不再提。</string>
+ <string name="settings_nudge_muted">长按关掉的:%1$s</string>
+ <string name="settings_nudge_unmute">全部恢复</string>
+ <string name="settings_section_plan">它的打算</string>
+ <string name="settings_plan_today">今天</string>
+ <string name="settings_plan_none_today">今天还没有计划。它会在你们安静一阵后的复盘里写出来。</string>
+ <string name="settings_plan_quiet">今天不打扰:%1$s</string>
+ <string name="settings_plan_directions">长期在帮你做的事</string>
+ <string name="settings_plan_none_directions">还没有。它只会根据你说过的话来写。</string>
+ <string name="settings_plan_pause">暂停</string>
+ <string name="settings_plan_resume">恢复</string>
+ <string name="settings_plan_remove">移除</string>
+ <string name="settings_plan_tell">告诉它一句</string>
+ <string name="settings_plan_tell_hint">比如:今天别提喝水了</string>
+ <string name="settings_plan_send">发送</string>
+ <string name="settings_plan_sent">已转告,它会自己调整计划。</string>
+ <string name="settings_plan_kind_remind">提醒</string>
+ <string name="settings_plan_kind_ask">问一句</string>
+ <string name="settings_plan_kind_prepare">准备</string>
+ <string name="settings_plan_kind_follow_up">跟进</string>
+ <string name="settings_plan_st_planned">待做</string>
+ <string name="settings_plan_st_done">已做</string>
+ <string name="settings_plan_st_declined">不用了</string>
+ <string name="settings_plan_st_ignored">没理</string>
+ <string name="settings_plan_st_missed">错过</string>
+ <string name="settings_plan_st_skipped">跳过</string>
+ <string name="settings_plan_st_moved">推迟</string>
+ <string name="settings_plan_st_dropped">已移除</string>
<string name="settings_section_typing">打字</string>
<string name="settings_typing_no_ime">这台设备上只有 ADBKeyboard(它没有键盘界面),所以现在打不了字。去系统设置里启用一个输入法,这里就会出现。</string>
<string name="settings_typing_current">你现在的输入法</string>
diff --git a/app/src/test/resources/golden/tool_schemas.json b/app/src/test/resources/golden/tool_schemas.json
index 9dd8061..47ab7ee 100644
--- a/app/src/test/resources/golden/tool_schemas.json
+++ b/app/src/test/resources/golden/tool_schemas.json
@@ -801,6 +801,39 @@
"required": ["text"]
}
},
+ {
+ "localOnly": true,
+ "method": "ui.nudge",
+ "name": "nudge",
+ "description": "Hold up a small SILENT bubble over your ball: the lightest way to speak\nfirst. Nothing is read aloud, the mic stays off, and you are not\nblocked \u2014 this returns at once. If the user is busy (a card is up,\nyou are talking, a task is running, the screen is off, quiet hours)\nthe device holds it until they are not, and drops it once `ttl_minutes`\nhas passed. Ignoring it is a perfectly good answer.\n\nUSE FOR things that are fine to miss: \"该喝水啦\", \"12点了,要帮你点外卖吗?\",\n\"你下午三点有个会\". NOT for anything that needs a decision now (that is\nask_user) and NOT as a second copy of something you are saying out\nloud in this turn \u2014 say it or bubble it, never both.\n\nWith buttons, a tap comes back to you later as its own turn\n(\"[You offered in a bubble: \u2026 \u2014 the user tapped \u2026]\"). Mark the \"no\nthanks\" button as `dismiss`: tapping it just closes the bubble and\nyou hear nothing. A button only means they want it \u2014 anything\nirreversible (paying, sending) still needs its own yes.\n\nThe device rations these (per hour, per day, and per `kind`) at a\nlevel the user chose, and the user can mute a kind. A refusal says\nwhy: do not retry it, and do not dress the same thing up as another\nkind.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "buttons": {
+ "description": "0\u20133 short labels, e.g. [\"好\",\"不用\"]. Omit for a bubble that only says something.",
+ "type": "array"
+ },
+ "ttl_minutes": {
+ "default": 30,
+ "description": "How long it stays worth saying, 1\u2013720. Default 30.",
+ "type": "integer"
+ },
+ "kind": {
+ "description": "A short stable tag for this sort of bubble, e.g. water, meal, meeting. Used for rationing and for the user muting it.",
+ "type": "string"
+ },
+ "dismiss": {
+ "description": "Which button means \"no thanks\" \u2014 exactly one of `buttons`. Tapping it ends the bubble with no turn.",
+ "type": "string"
+ },
+ "text": {
+ "description": "One short sentence (≤ 60 characters), in the language the user speaks. Plain text, no markdown.",
+ "type": "string"
+ }
+ },
+ "required": ["text"]
+ }
+ },
{
"method": "ui.show_html",
"name": "show_html",
@@ -1241,6 +1274,109 @@
"required": ["what"]
}
},
+ {
+ "localOnly": true,
+ "method": "note.directions",
+ "name": "plan_directions",
+ "description": "Your long-term directions with this person: what you are helping them get done these weeks, and how.\nThey are the reason behind every item of every day plan, and the user can see them \u2014 and pause or\nremove them \u2014 in Settings.\n\n- `list`: see them.\n- `add`: title, why, how_i_help, good_when, source. **Only from what the user said or did** \u2014 `source`\n says when and what (\"10-26: 「这周要把 0.6.2 发出去」\"). A goal you think would be good for them is\n not theirs; do not add it.\n- `update` / `pause` / `resume` / `done` / `drop`: by id.\n\nAt most 5 active; more than that is no focus at all. A direction the user paused or removed is theirs:\nyou cannot resume or re-add it unless they ask for it in so many words.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "how_i_help": {
+ "description": "What you will do about it, concretely",
+ "type": "string"
+ },
+ "action": {
+ "description": "What to do",
+ "type": "string",
+ "enum": [
+ "list",
+ "add",
+ "update",
+ "pause",
+ "resume",
+ "done",
+ "drop"
+ ]
+ },
+ "why": {
+ "description": "Why it matters to them, in their terms",
+ "type": "string"
+ },
+ "good_when": {
+ "description": "How you will know it is done",
+ "type": "string"
+ },
+ "id": {
+ "description": "For everything but list and add; take it from list",
+ "type": "string"
+ },
+ "source": {
+ "description": "When and what they said or did that makes this theirs. Required for add",
+ "type": "string"
+ },
+ "title": {
+ "description": "A few words, in the user's language",
+ "type": "string"
+ }
+ },
+ "required": ["action"]
+ }
+ },
+ {
+ "localOnly": true,
+ "method": "note.day_plan",
+ "name": "day_plan",
+ "description": "Your plan for a day: what you mean to do for this person, and when you will speak to them. The user sees\nit in Settings and can remove items; a line of it rides on every message.\n\n- `get`: the plan for `date` (today, tomorrow or YYYY-MM-DD).\n- `write`: replace the still-planned part of that day.\n - `intent`: one sentence in your own voice and the user's language \u2014 「今天我想帮他把发布收个尾,别的事少打扰。」\n - `items`: each `{time, slot, kind, what, because, buttons, dismiss, tag}`\n - `time` \"HH:mm\", or \"\" with a `slot` (a loose time: 午饭前, when they first talk to me).\n - `kind`: remind (a bubble telling them something), ask (a bubble with buttons), prepare (something\n you do quietly ahead of time), follow_up (pick up something left half-way).\n - `what`: for remind/ask, exactly the bubble's words (≤ 60 characters, their language); otherwise\n what you will do.\n - `because`: the direction or todo it serves. Required \u2014 an item that serves nothing is not part\n of the plan.\n - remind/ask with a `time` become bubbles at that minute with no further thought from you; what\n happened (done / declined / ignored / skipped) is written back onto the item.\n - `quiet`: what you will NOT bother them about today \u2014 as much a part of the plan as the items.\n At most 5 remind/ask a day. Items already done or ignored stay as the day's history; items the user\n removed cannot be put back.\n- `mark`: set an item done / dropped / moved by id, when it was handled some other way.\n\nA day with nothing to say is a good plan. Never plan anything irreversible (paying, sending, deleting):\nthose need the user, asked at the time.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "date": {
+ "description": "today (default), tomorrow, or YYYY-MM-DD",
+ "type": "string"
+ },
+ "note": {
+ "description": "For mark: a few words on why",
+ "type": "string"
+ },
+ "action": {
+ "description": "What to do",
+ "type": "string",
+ "enum": [
+ "get",
+ "write",
+ "mark"
+ ]
+ },
+ "quiet": {
+ "description": "For write: what you will leave alone today",
+ "type": "array"
+ },
+ "id": {
+ "description": "For mark: the item id from get",
+ "type": "string"
+ },
+ "intent": {
+ "description": "For write: one sentence, your own voice",
+ "type": "string"
+ },
+ "items": {
+ "description": "For write: the items, see the description",
+ "type": "array"
+ },
+ "status": {
+ "description": "For mark",
+ "type": "string",
+ "enum": [
+ "done",
+ "dropped",
+ "moved"
+ ]
+ }
+ },
+ "required": ["action"]
+ }
+ },
{
"localOnly": true,
"method": "note.todos",
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 05973c9..e0217b9 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
@@ -82,6 +82,12 @@ interface BrainHost {
*/
fun gearIndex(): String = ""
+ /**
+ * One line of the plan (see `Plans`): today's intent, the next items, the long-term directions. Empty
+ * for a host without plans, so it changes by not a byte.
+ */
+ fun planIndex(): String = ""
+
/**
* One line naming the other Andees this one can ask (see `PeerTasks`), empty when it has none. Without it the
* model answers "do you have friends" from nothing; a default, so a host without friends changes by not a byte.
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 6456d1a..c1afad7 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
@@ -688,6 +688,9 @@ class LocalBrain(
// Empty notebook, empty string, zero cost: the feature only starts
// paying for itself once there is something to remember.
val index = host.notebookIndex()
+ // The plan (`Plans`): what it is helping them with and what it meant to do today. Right after
+ // the notebook and for the same cache reason; it is the thread every turn should be able to see.
+ val plan = host.planIndex()
val scenes = host.scenesIndex()
// The pages it has made, the same way and for the same reason: a
// tool answers a question the brain thought to ask, and 「上次那个表格」
@@ -740,6 +743,12 @@ class LocalBrain(
} else {
"\n\n(what your notebook holds, for reference; use recall for detail)\n$index"
} +
+ if (plan.isEmpty()) {
+ ""
+ } else {
+ "\n\n(your plan — what you are helping them with and what you meant to do today; " +
+ "the user can see it in Settings; change it with day_plan / plan_directions)\n$plan"
+ } +
// Same position and same reason as the notebook index:
// a newly saved scene must not cost the prefix cache.
// Only the scene you are *in* sits in the system prompt.
@@ -1744,6 +1753,8 @@ class LocalBrain(
When it has, remember under the same name to overwrite that entry. This one is a judgement left for future you, not a log.
6. A kind of session that has now come up more than once and will come again (practising a language, minding his messages, comparing prices) and is not a scene yet → remember(type=feedback) "propose saving <kind> as a scene next time we do it". Do NOT call save_scene here: scenes are saved only after he says yes (§11), and he is not here.
7. You used an installed app this time and learned what it is for, what it can do on his behalf, or a limit you hit → note_gear (only what you actually saw; a login only if you saw it signed in). If a note on the shelf turned out wrong this time, correct it. Never touch gear_visibility here: what is kept out of view is his call, made when he is present.
+8. The plan (your plan line; day_plan get for detail). Keep today's plan true: if there is none, write one (day_plan write, date=today); if what happened in this conversation changed it, rewrite it; after 20:00, also draft tomorrow's — and before you do, read today's outcomes (day_plan get): keep what landed, do less of or move what he ignored or declined, carry over what was moved. If your plan line says the weekly look at the directions is due, do it now: plan_directions list, then mark done what is done, pause what has stalled, and add what he newly said he is working toward. Every item points at a long-term direction or a todo in `because`; at most 5 that interrupt (remind/ask), at the times you would really choose; a quiet day is a fine plan, and `quiet` says what you will leave alone today.
+ Long-term directions (plan_directions add) come only from what he said or did — quote it in `source`; a goal you think would be good for him is not his. With no directions yet, one `ask` item a day may be getting to know him (what he is busy with lately, what he would like you to keep an eye on — in his language), until he has answered or ignored it twice. Never put back what he removed.
If this conversation genuinely produced nothing new, record nothing — ending empty-handed is allowed. Forcing one in just dirties the notebook."""
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt
new file mode 100644
index 0000000..a0d9b21
--- /dev/null
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/NudgeBook.kt
@@ -0,0 +1,152 @@
+package net.kuafuai.andee.brain
+
+import org.json.JSONObject
+
+/**
+ * One bubble the model asked to hold up over the ball: the weakest way this device has of speaking first.
+ *
+ * Unlike a card it is silent, blocks nothing and is allowed to be ignored — not answering is an answer.
+ * See `docs/design/proactive-nudge.zh-CN.md` §4.
+ */
+data class Nudge(
+ val text: String,
+ /** 0–3 labels. Empty = a bubble that only says something. */
+ val buttons: List<String>,
+ /** The label that means "no thanks": tapping it ends the bubble without starting a turn. */
+ val dismiss: String?,
+ val kind: String,
+ /** Absolute millis after which the bubble is stale and must not be shown at all. */
+ val expiresAt: Long,
+ /**
+ * The turn that wrote it was [LocalBrain.TurnKind.NOTIFY]. The turn a tap on it starts runs as one too —
+ * otherwise a stranger's message could put a 「好」 button in front of the user and get a trusted turn back
+ * for it, the same laundering `Todo.untrusted` closes for the alarm clock.
+ */
+ val untrusted: Boolean,
+ /** `date#item` when this bubble is a planned item ([net.kuafuai.andee.config.Plans]); blank otherwise. */
+ val planRef: String = "",
+)
+
+/**
+ * The device's half of `nudge`: what a bubble may say, and how often the model may raise one.
+ *
+ * **The limits are here and not in the prompt**, for the reason every rule in [net.kuafuai.andee.net.TurnGuards]
+ * is: a prompt is a request. Being spoken to first is only welcome when it is rare, and a stream of small
+ * interruptions is how a user learns to mute the ball, after which even the right ones are lost. So the
+ * budget is mechanical and a refusal comes back to the model as a sentence saying why.
+ *
+ * Pure apart from the clock, so it can be tested. In memory only: a service restart resets the counts,
+ * which errs toward one extra bubble and is not worth a file.
+ */
+class NudgeBook(private val clock: () -> Long = System::currentTimeMillis) {
+
+ /** How chatty the user lets it be. [OFF] is also the fallback for a value nobody recognises. */
+ enum class Level(val key: String, val perHour: Int, val perDay: Int) {
+ OFF("off", 0, 0),
+ FEW("few", 1, 4),
+ NORMAL("normal", 2, 8),
+ ;
+
+ companion object {
+ /** Unset means [FEW], unrecognised means [OFF] — the same split `VoiceConfig.notifyScope` draws. */
+ fun of(saved: String?): Level = when (saved?.trim()?.lowercase()) {
+ null, "" -> FEW
+ FEW.key -> FEW
+ NORMAL.key -> NORMAL
+ else -> OFF
+ }
+ }
+ }
+
+ private val admitted = ArrayDeque<Pair<Long, String>>()
+
+ /**
+ * Read a `ui.nudge` call. Throws [IllegalArgumentException] with a sentence for the model on a malformed
+ * one — those are the model's to fix, unlike [admit]'s refusals, which are not.
+ */
+ fun parse(params: JSONObject?, untrusted: Boolean): Nudge {
+ val text = params?.optString("text")?.trim().orEmpty()
+ require(text.isNotEmpty()) { "nudge requires text" }
+ require(text.length <= MAX_TEXT) {
+ "A bubble holds one short sentence (≤ $MAX_TEXT characters); this was ${text.length}. " +
+ "If it needs more than that, it is a conversation, not a bubble — use ask_user, or say it next time they talk to you."
+ }
+ val arr = params?.optJSONArray("buttons")
+ val buttons = if (arr == null) emptyList() else List(arr.length()) { arr.optString(it).trim() }.filter { it.isNotEmpty() }
+ require(buttons.size <= MAX_BUTTONS) { "A bubble has at most $MAX_BUTTONS buttons; got ${buttons.size}." }
+ require(buttons.toSet().size == buttons.size) { "Two buttons have the same label." }
+ buttons.firstOrNull { it.length > MAX_LABEL }?.let {
+ throw IllegalArgumentException("Button labels are a word or two (≤ $MAX_LABEL characters): \"$it\"")
+ }
+ val dismiss = params?.optString("dismiss")?.trim()?.ifEmpty { null }
+ require(dismiss == null || dismiss in buttons) {
+ "dismiss must be one of the buttons, letter for letter: \"$dismiss\" is not in $buttons"
+ }
+ val ttlMin = params?.optLong("ttl_minutes", DEFAULT_TTL_MIN) ?: DEFAULT_TTL_MIN
+ require(ttlMin in 1..MAX_TTL_MIN) { "ttl_minutes must be 1–$MAX_TTL_MIN; got $ttlMin" }
+ val kind = params?.optString("kind")?.trim()?.lowercase()?.take(MAX_KIND)?.ifEmpty { null } ?: "other"
+ return Nudge(text, buttons, dismiss, kind, clock() + ttlMin * 60_000L, untrusted)
+ }
+
+ /**
+ * Admit [n] against the budget, or say why not. Null = admitted, and counted from now: a bubble that is
+ * held and then expires has still spent its slot, which errs toward fewer.
+ */
+ fun admit(n: Nudge, level: Level, muted: Set<String>): String? {
+ val now = clock()
+ if (level == Level.OFF) {
+ return "The user has turned bubbles off in settings. Do not raise one; if it matters, say it the next time they talk to you."
+ }
+ if (n.kind in muted) {
+ return "The user asked not to be reminded of \"${n.kind}\" any more. Respect that; do not raise it under another kind."
+ }
+ while (admitted.isNotEmpty() && now - admitted.first().first >= DAY_MS) admitted.removeFirst()
+ val lastHour = admitted.count { now - it.first < HOUR_MS }
+ if (lastHour >= level.perHour) {
+ return "Bubble budget used: at most ${level.perHour} per hour at the user's setting. Not raised. " +
+ "Do not retry; if it still matters later, it can wait."
+ }
+ if (admitted.size >= level.perDay) {
+ return "Bubble budget used: at most ${level.perDay} per day at the user's setting. Not raised. Do not retry today."
+ }
+ admitted.lastOrNull { it.second == n.kind }?.let { (at, _) ->
+ if (now - at < KIND_COOLDOWN_MS) {
+ val mins = (KIND_COOLDOWN_MS - (now - at) + 59_999) / 60_000
+ return "A \"${n.kind}\" bubble went up ${(now - at) / 60_000} min ago; the same kind waits " +
+ "${KIND_COOLDOWN_MS / 60_000} min between bubbles ($mins min to go). Not raised."
+ }
+ }
+ admitted.addLast(now to n.kind)
+ return null
+ }
+
+ companion object {
+ const val MAX_TEXT = 60
+ const val MAX_BUTTONS = 3
+ const val MAX_LABEL = 12
+ const val MAX_KIND = 24
+ const val DEFAULT_TTL_MIN = 30L
+ const val MAX_TTL_MIN = 720L
+ const val HOUR_MS = 60 * 60_000L
+ 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.
+ */
+ fun answerText(n: Nudge, button: String?): String =
+ if (button != null) {
+ "[You offered in a bubble: \"${n.text}\" — the user tapped \"$button\"]"
+ } else {
+ "[You offered in a bubble: \"${n.text}\" — the user tapped the bubble itself rather than a " +
+ "button: they want to talk about it]"
+ }
+ }
+}
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/PlanMind.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/PlanMind.kt
new file mode 100644
index 0000000..908f3cd
--- /dev/null
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/PlanMind.kt
@@ -0,0 +1,124 @@
+package net.kuafuai.andee.brain
+
+import net.kuafuai.andee.config.BrainConfig
+import net.kuafuai.andee.config.Plans
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * The two moments it thinks about its plan without being asked — `docs/design/proactive-nudge.zh-CN.md` §5.4
+ * and §6.2. Both are **one call with no tools**, the way [NotificationTriage] is: the system prompt plus ~55
+ * tool descriptions of a full turn would cost forty times as much for a question this small.
+ *
+ * * [morning] — the first time the user shows up each day: look at yesterday's outcomes, the directions,
+ * today's draft and today's todos, and write today's plan (or keep the draft). This is also what gives a
+ * device a plan before any review has run.
+ * * [muse] — while they are around: of today's items that have only a loose time ("before lunch"), is now
+ * the moment for one? At most one, usually none.
+ *
+ * Both fail closed: no key, a failed call, an unreadable answer → nothing changes. The old behaviour of not
+ * thinking is always a safe one here, unlike triage, where it meant raising the signboard.
+ *
+ * Blocks; call from a worker.
+ */
+class PlanMind(
+ cfg: BrainConfig,
+ private val plans: Plans,
+ private val log: (warn: Boolean, msg: String) -> Unit = { _, _ -> },
+) {
+
+ private val ready = cfg.apiKey.isNotEmpty()
+
+ private val llm = LlmClient(
+ baseUrl = cfg.baseUrl,
+ apiKey = cfg.apiKey,
+ model = cfg.model,
+ thinking = false,
+ reasoningEffort = cfg.reasoningEffort,
+ )
+
+ /**
+ * Write today's plan in the light of the morning. Marks the morning done whether or not the call worked —
+ * a second attempt every few minutes would be the expensive way to fail.
+ *
+ * @return true when the plan was rewritten (the caller then re-syncs the alarms).
+ */
+ fun morning(langTag: String, bubblesPerDay: Int): Boolean {
+ if (!plans.morningDue()) return false
+ plans.markMorning()
+ if (!ready) return false
+ val obj = ask(MORNING, "Interface language: $langTag\n\n" + plans.morningContext(), "morning") ?: return false
+ if (obj.optBoolean("keep")) {
+ log(false, "morning: kept the draft")
+ return false
+ }
+ return runCatching {
+ plans.handle("note.day_plan", obj.put("action", "write").put("date", "today"), bubblesPerDay)
+ log(false, "morning: wrote today's plan — ${obj.optString("intent").take(80)}")
+ true
+ }.getOrElse {
+ log(true, "morning: plan refused: ${it.message}")
+ false
+ }
+ }
+
+ /**
+ * @return the id of the loose-time item whose moment is now, or null (the usual answer). The caller turns
+ * it into a bubble through [Plans.bubbleForItem], so the user's limits still apply.
+ */
+ fun muse(langTag: String): String? {
+ if (!plans.museDue()) return null
+ val context = plans.museContext() ?: return null
+ plans.markMuse()
+ if (!ready) return null
+ val obj = ask(MUSE, "Interface language: $langTag\n\n$context", "muse") ?: return null
+ return if (obj.optString("verdict") == "nudge") obj.optString("id").trim().ifEmpty { null } else null
+ }
+
+ private fun ask(system: String, user: String, what: String): JSONObject? {
+ val reply = try {
+ llm.complete(
+ listOf(
+ JSONObject().put("role", "system").put("content", system),
+ JSONObject().put("role", "user").put("content", user),
+ ),
+ JSONArray(),
+ )
+ } catch (t: Throwable) {
+ log(true, "$what call failed: ${t.message}")
+ return null
+ }
+ val raw = reply.content.trim()
+ log(false, "$what: ${raw.take(200)} (tokens ${reply.promptTokens}/${reply.completionTokens})")
+ val start = raw.indexOf('{')
+ val end = raw.lastIndexOf('}')
+ if (start < 0 || end <= start) return null
+ return runCatching { JSONObject(raw.substring(start, end + 1)) }.getOrNull()
+ }
+
+ companion object {
+ private val MORNING = """
+ You are Andee — an individual who lives on this person's device, not a tool. It is the start of their day, and you are deciding what you mean to do for them today. You will be given the time, your long-term directions with them, yesterday's plan with what happened to each item, today's draft (if your review wrote one), the todos due today, and your notebook about them.
+
+ Reply with ONLY a JSON object — no prose, no code fence. Either {"keep": true} when the draft is still right, or today's plan:
+ {"intent": "...", "items": [{"time": "HH:mm" or "", "slot": "...", "kind": "remind|ask|prepare|follow_up", "what": "...", "because": "...", "buttons": [...], "dismiss": "...", "tag": "..."}], "quiet": ["..."]}
+
+ Rules:
+ - intent: one sentence in your own voice, first person, in the user's language (the interface language unless your notebook says otherwise).
+ - Every item's `because` names a long-term direction or a todo. An item that serves nothing is not part of the plan.
+ - remind/ask are bubbles: `what` is exactly the bubble's words, ≤ 60 characters, in their language. ask has 2–3 short buttons and `dismiss` is the "no thanks" one. Give a `time` later than now when you know the moment, otherwise a `slot` ("before lunch", "when they come back to the computer").
+ - At most 5 remind/ask. Fewer is better. A quiet day is a good plan; say in `quiet` what you will leave alone today.
+ - Learn from yesterday: what they ignored or declined, do less of or at another time; what landed, keep; what was moved, carry over.
+ - Never invent a goal they did not state. With no directions yet, at most one ask today, to get to know them (what they are busy with, what they would like you to keep an eye on).
+ - Never put back anything listed as removed by the user. Never plan anything irreversible (paying, sending, deleting).
+ """.trimIndent()
+
+ private val MUSE = """
+ You are Andee, deciding whether now is the moment to speak to the person you look after. You will be given the time, today's intent, what already happened today, and the plan items that have only a loose time ("before lunch", "in the afternoon").
+
+ Reply with ONLY a JSON object — no prose, no code fence: {"verdict": "hold"} or {"verdict": "nudge", "id": "<item id>"}.
+
+ Choose "nudge" only when the item's loose time clearly fits now and nothing that already happened today makes it wrong (they just declined something similar, it is past its moment, or today's "not today" covers it). Otherwise "hold" — holding is the usual answer, and a missed moment costs less than an interruption at the wrong one.
+ """.trimIndent()
+ }
+}
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 c0aaa90..083b056 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/NotebookBook.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/NotebookBook.kt
@@ -648,6 +648,7 @@ class NotebookBook(private val store: NotebookStore) {
status = o.optString("status", "active"),
createdAt = o.optLong("created_at"),
untrusted = o.optBoolean("untrusted", false),
+ nudge = o.optString("nudge"),
)
fun toJson(t: Todo): JSONObject = JSONObject()
@@ -663,5 +664,6 @@ class NotebookBook(private val store: NotebookStore) {
.put("status", t.status)
.put("created_at", t.createdAt)
.put("untrusted", t.untrusted)
+ .apply { if (t.nudge.isNotEmpty()) put("nudge", t.nudge) }
}
}
diff --git a/core/src/main/kotlin/net/kuafuai/andee/config/NotebookTypes.kt b/core/src/main/kotlin/net/kuafuai/andee/config/NotebookTypes.kt
index a63e098..dc33072 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/config/NotebookTypes.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/NotebookTypes.kt
@@ -42,4 +42,9 @@ data class Todo(
* Rows written before this field existed read as false.
*/
val untrusted: Boolean = false,
+ /**
+ * A bubble spec (JSON) when this todo raises a bubble at its time instead of waking the model — the
+ * plan's timed items ([Plans.reconcile]). Blank for an ordinary todo.
+ */
+ val nudge: String = "",
)
diff --git a/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt b/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
new file mode 100644
index 0000000..79e88ec
--- /dev/null
+++ b/core/src/main/kotlin/net/kuafuai/andee/config/Plans.kt
@@ -0,0 +1,649 @@
+package net.kuafuai.andee.config
+
+import net.kuafuai.andee.brain.Nudge
+import net.kuafuai.andee.brain.NudgeBook
+import org.json.JSONArray
+import org.json.JSONObject
+import java.time.Instant
+import java.time.LocalDate
+import java.time.LocalTime
+import java.time.ZoneId
+
+/**
+ * What it is trying to do with this person, and what it means to do today — so that speaking first is
+ * the next step of a plan rather than a guess. See `docs/design/proactive-nudge.zh-CN.md` §5–§6.
+ *
+ * Two layers, the upper one guiding the lower:
+ *
+ * * **Directions** — what it is helping them get done these weeks. Only from what they said or did, each
+ * with its `source`; at most [MAX_DIRECTIONS] active. A direction the user removed is kept as a tombstone
+ * so the model cannot quietly write it back.
+ * * **Day plans** — one per date: an intent in its own voice, items that each point back at a direction
+ * or a todo (`because`), and the things it will *not* bother them about today.
+ *
+ * Items with a clock time that interrupt (`remind` / `ask`) become **bubble todos** ([reconcile]): the
+ * scheduler raises the bubble at that minute with no model call, and the outcome is written back onto the
+ * item ([recordOutcome]). That is what makes most of the speaking-first predictable and cheap.
+ *
+ * Stored in the notebook under `plan`, through the book itself (like [Gear]), so wipe, factory reset and
+ * export cover it. Shared by both bodies; each one only arms and cancels the alarms [reconcile] returns.
+ */
+class Plans(
+ private val book: NotebookBook,
+ private val clock: () -> Long = System::currentTimeMillis,
+ private val zone: ZoneId = ZoneId.systemDefault(),
+) {
+
+ data class Direction(
+ val id: String,
+ val title: String,
+ val why: String,
+ val howIHelp: String,
+ val goodWhen: String,
+ val source: String,
+ /** `active` / `paused` / `done` / `dropped`. */
+ val status: String,
+ /** The user paused or removed it themselves; the model may not undo that. */
+ val byUser: Boolean,
+ val updatedAt: Long,
+ )
+
+ data class Item(
+ val id: String,
+ /** `HH:mm`, or blank when the item has only a [slot]. */
+ val time: String,
+ /** A loose time ("午饭前", "when they first talk to me"), for items without a clock time. */
+ val slot: String,
+ /** `remind` / `ask` / `prepare` / `follow_up`. */
+ val kind: String,
+ /** What to do — for `remind` / `ask`, exactly the words of the bubble. */
+ val what: String,
+ /** Which direction or todo this serves. Never blank. */
+ val because: String,
+ val buttons: List<String>,
+ val dismiss: String,
+ /** A stable short tag for the bubble (water, meal…); blank = one of a kind. */
+ val tag: String,
+ /** `planned` / `done` / `declined` / `ignored` / `missed` / `skipped` / `moved` / `dropped`. */
+ val status: String,
+ /** Why it ended up in [status], when the device knows. */
+ val note: String,
+ )
+
+ data class Day(
+ val date: String,
+ val intent: String,
+ val items: List<Item>,
+ val quiet: List<String>,
+ val updatedAt: Long,
+ /** `what` of items the user removed today; the model may not put them back. */
+ val userDropped: List<String>,
+ )
+
+ /** What the body has to do to its alarms after a plan changed. */
+ data class Sync(val arm: List<Todo>, val cancel: List<String>)
+
+ private val lock = Any()
+
+ // ---- storage -------------------------------------------------------------
+
+ private fun load(): JSONObject = book.section(SECTION)
+ private fun save(o: JSONObject) = book.putSection(SECTION, o)
+
+ fun today(): String = Instant.ofEpochMilli(clock()).atZone(zone).toLocalDate().toString()
+ private fun tomorrow(): String = LocalDate.parse(today()).plusDays(1).toString()
+
+ fun directions(): List<Direction> = synchronized(lock) { dirs(load()) }
+
+ fun day(date: String): Day? = synchronized(lock) { load().optJSONObject("days")?.optJSONObject(date)?.let(::toDay) }
+
+ private fun dirs(root: JSONObject): List<Direction> {
+ val a = root.optJSONArray("directions") ?: return emptyList()
+ return (0 until a.length()).mapNotNull { a.optJSONObject(it)?.let(::toDirection) }
+ }
+
+ private fun putDirs(root: JSONObject, list: List<Direction>) {
+ root.put("directions", JSONArray().apply { list.forEach { put(toJson(it)) } })
+ }
+
+ private fun putDay(root: JSONObject, d: Day) {
+ val days = root.optJSONObject("days") ?: JSONObject()
+ days.put(d.date, toJson(d))
+ // Keep a week behind today and anything ahead; older days are only history nobody reads.
+ val cutoff = LocalDate.parse(today()).minusDays(KEEP_DAYS).toString()
+ days.keys().asSequence().toList().filter { it < cutoff }.forEach { days.remove(it) }
+ root.put("days", days)
+ }
+
+ // ---- the two tools ---------------------------------------------------------
+
+ /**
+ * `note.directions` and `note.day_plan`. Throws [IllegalArgumentException] with a sentence for the model
+ * on a malformed call; refusals that are the user's limits come back as results that say why.
+ *
+ * @param bubblesPerDay how many bubbles the user's 主动招呼 level allows a day, so a plan can be told it
+ * asked for more than will ever be shown.
+ */
+ fun handle(method: String, p: JSONObject?, bubblesPerDay: Int): JSONObject = when (method) {
+ "note.directions" -> directionsTool(p ?: JSONObject())
+ "note.day_plan" -> dayPlanTool(p ?: JSONObject(), bubblesPerDay)
+ else -> throw IllegalArgumentException("unknown method $method")
+ }
+
+ private fun directionsTool(p: JSONObject): JSONObject = synchronized(lock) {
+ val root = load()
+ val list = dirs(root).toMutableList()
+ val now = clock()
+ when (val action = p.optString("action", "list")) {
+ "list" -> {
+ // Looking at them is the weekly review the plan line asks for; stamp it so the ask goes away.
+ root.put("meta", meta(root).put("directions_reviewed_at", now)); save(root)
+ return listDirections(list)
+ }
+ "add" -> {
+ val title = req(p, "title")
+ val source = req(p, "source")
+ if (list.any { it.title == title && it.byUser && it.status == "dropped" }) {
+ return JSONObject().put("added", false).put(
+ "reason", "The user removed \"$title\" themselves. Do not put it back unless they ask for it again in so many words.",
+ )
+ }
+ if (list.any { it.title == title && it.status == "active" }) {
+ return JSONObject().put("added", false).put("reason", "\"$title\" is already a direction; use update.")
+ }
+ if (list.count { it.status == "active" } >= MAX_DIRECTIONS) {
+ return JSONObject().put("added", false).put(
+ "reason", "Already $MAX_DIRECTIONS active directions. More than that is no focus at all: finish, pause or drop one first.",
+ )
+ }
+ val d = Direction(
+ "d" + now.toString(36), title, p.optString("why"), p.optString("how_i_help"),
+ p.optString("good_when"), source, "active", false, now,
+ )
+ list += d
+ putDirs(root, list); save(root)
+ return JSONObject().put("added", true).put("id", d.id)
+ }
+ "update", "pause", "resume", "done", "drop" -> {
+ val id = req(p, "id")
+ val i = list.indexOfFirst { it.id == id }
+ require(i >= 0) { "No direction with id $id; list first." }
+ val old = list[i]
+ if (old.byUser && action != "update") {
+ return JSONObject().put("changed", false).put(
+ "reason", "The user set this one to ${old.status} themselves. Leave it; ask them if you think it should change.",
+ )
+ }
+ list[i] = when (action) {
+ "update" -> old.copy(
+ title = p.optString("title").ifEmpty { old.title },
+ why = p.optString("why").ifEmpty { old.why },
+ howIHelp = p.optString("how_i_help").ifEmpty { old.howIHelp },
+ goodWhen = p.optString("good_when").ifEmpty { old.goodWhen },
+ source = p.optString("source").ifEmpty { old.source },
+ updatedAt = now,
+ )
+ "pause" -> old.copy(status = "paused", updatedAt = now)
+ "resume" -> old.copy(status = "active", updatedAt = now)
+ "done" -> old.copy(status = "done", updatedAt = now)
+ else -> old.copy(status = "dropped", updatedAt = now)
+ }
+ putDirs(root, list); save(root)
+ return JSONObject().put("changed", true).put("id", id).put("status", list[i].status)
+ }
+ else -> throw IllegalArgumentException("action must be list, add, update, pause, resume, done or drop; got $action")
+ }
+ }
+
+ private fun listDirections(list: List<Direction>): JSONObject = JSONObject().put(
+ "directions",
+ JSONArray().apply {
+ list.filter { it.status != "dropped" || it.byUser }.forEach {
+ put(
+ JSONObject().put("id", it.id).put("title", it.title).put("why", it.why).put("how_i_help", it.howIHelp)
+ .put("good_when", it.goodWhen).put("source", it.source).put("status", it.status)
+ .put("set_by_user", it.byUser),
+ )
+ }
+ },
+ )
+
+ private fun dayPlanTool(p: JSONObject, bubblesPerDay: Int): JSONObject {
+ val action = p.optString("action", "get")
+ val date = when (val d = p.optString("date", "today").trim()) {
+ "", "today" -> today()
+ "tomorrow" -> tomorrow()
+ else -> runCatching { LocalDate.parse(d).toString() }.getOrNull()
+ ?: throw IllegalArgumentException("date is today, tomorrow or YYYY-MM-DD; got $d")
+ }
+ return when (action) {
+ "get" -> day(date)?.let { dayJson(it) } ?: JSONObject().put("date", date).put("exists", false)
+ "write" -> write(date, p, bubblesPerDay)
+ "mark" -> synchronized(lock) {
+ val id = req(p, "id")
+ val status = req(p, "status")
+ require(status in setOf("done", "dropped", "moved")) { "status for mark is done, dropped or moved" }
+ val root = load()
+ val d = root.optJSONObject("days")?.optJSONObject(date)?.let(::toDay)
+ ?: throw IllegalArgumentException("No plan for $date")
+ require(d.items.any { it.id == id }) { "No item $id in the plan for $date" }
+ putDay(root, d.copy(items = d.items.map { if (it.id == id) it.copy(status = status, note = p.optString("note")) else it }, updatedAt = clock()))
+ save(root)
+ JSONObject().put("marked", true).put("id", id).put("status", status)
+ }
+ else -> throw IllegalArgumentException("action must be get, write or mark; got $action")
+ }
+ }
+
+ /**
+ * Replace the still-planned part of [date]'s plan. Items that already happened (done, ignored, …) stay as
+ * the day's history; what the user removed today cannot come back.
+ */
+ private fun write(date: String, p: JSONObject, bubblesPerDay: Int): JSONObject = synchronized(lock) {
+ val intent = req(p, "intent")
+ val arr = p.optJSONArray("items") ?: JSONArray()
+ require(arr.length() <= MAX_ITEMS) { "At most $MAX_ITEMS items in a day." }
+ val root = load()
+ val old = root.optJSONObject("days")?.optJSONObject(date)?.let(::toDay)
+ val kept = old?.items?.filter { it.status != "planned" }.orEmpty()
+ val dropped = old?.userDropped.orEmpty()
+ var n = (kept.mapNotNull { it.id.removePrefix("p").toIntOrNull() }.maxOrNull() ?: 0)
+ val refused = JSONArray()
+ val fresh = mutableListOf<Item>()
+ for (i in 0 until arr.length()) {
+ val o = arr.optJSONObject(i) ?: continue
+ val what = o.optString("what").trim()
+ require(what.isNotEmpty()) { "Every item needs `what`." }
+ val kind = o.optString("kind", "remind").trim()
+ require(kind in KINDS) { "kind is one of $KINDS; got $kind" }
+ val because = o.optString("because").trim()
+ require(because.isNotEmpty()) {
+ "Item \"$what\" has no `because`. Every item points at a direction or a todo; one that cannot is not part of the plan."
+ }
+ val time = o.optString("time").trim()
+ require(time.isEmpty() || runCatching { LocalTime.parse(time) }.isSuccess) { "time is HH:mm or empty; got $time" }
+ if (what in dropped) {
+ refused.put(JSONObject().put("what", what).put("reason", "The user removed this today."))
+ continue
+ }
+ val buttons = o.optJSONArray("buttons")?.let { a -> (0 until a.length()).map { a.optString(it).trim() }.filter { it.isNotEmpty() } }.orEmpty()
+ require(buttons.size <= NudgeBook.MAX_BUTTONS) { "At most ${NudgeBook.MAX_BUTTONS} buttons." }
+ if (kind in INTERRUPTING) require(what.length <= NudgeBook.MAX_TEXT) {
+ "\"$what\" is the bubble's words and a bubble holds ≤ ${NudgeBook.MAX_TEXT} characters."
+ }
+ val dismiss = o.optString("dismiss").trim()
+ require(dismiss.isEmpty() || dismiss in buttons) { "dismiss must be one of the buttons." }
+ fresh += Item(
+ "p${++n}", time, o.optString("slot").trim(), kind, what, because, buttons, dismiss,
+ o.optString("tag").trim().lowercase().take(NudgeBook.MAX_KIND), "planned", "",
+ )
+ }
+ val interrupting = fresh.count { it.kind in INTERRUPTING }
+ require(interrupting <= MAX_INTERRUPTIONS) {
+ "$interrupting items would interrupt them (remind/ask); a day has at most $MAX_INTERRUPTIONS. Keep the ones that matter."
+ }
+ val quietArr = p.optJSONArray("quiet")
+ val quiet = if (quietArr == null) old?.quiet.orEmpty() else (0 until quietArr.length()).map { quietArr.optString(it).trim() }.filter { it.isNotEmpty() }
+ val d = Day(date, intent, kept + fresh, quiet, clock(), dropped)
+ putDay(root, d)
+ save(root)
+ JSONObject().put("written", true).put("date", date).put("items", fresh.size).put("refused", refused)
+ .put(
+ "note",
+ (if (interrupting > bubblesPerDay) "The user's setting allows $bubblesPerDay bubbles a day; the rest will be skipped. " else "") +
+ "Items with a clock time that remind/ask are now scheduled as bubbles; the outcome is written back onto each item.",
+ )
+ }
+
+ private fun dayJson(d: Day): JSONObject = JSONObject().put("date", d.date).put("exists", true).put("intent", d.intent)
+ .put("quiet", JSONArray(d.quiet))
+ .put(
+ "items",
+ JSONArray().apply {
+ d.items.forEach {
+ put(
+ JSONObject().put("id", it.id).put("time", it.time).put("slot", it.slot).put("kind", it.kind)
+ .put("what", it.what).put("because", it.because).put("status", it.status).put("note", it.note),
+ )
+ }
+ },
+ )
+ .put("removed_by_user", JSONArray(d.userDropped))
+
+ // ---- what the user does in settings ---------------------------------------------
+
+ /** The user removed an item. Done by the device, not asked of the model. */
+ fun dropItemByUser(date: String, id: String) = synchronized(lock) {
+ val root = load()
+ val d = root.optJSONObject("days")?.optJSONObject(date)?.let(::toDay) ?: return@synchronized
+ val it = d.items.firstOrNull { it.id == id } ?: return@synchronized
+ putDay(
+ root,
+ d.copy(
+ items = d.items.map { x -> if (x.id == id) x.copy(status = "dropped", note = "removed by the user") else x },
+ userDropped = (d.userDropped + it.what).distinct(), updatedAt = clock(),
+ ),
+ )
+ save(root)
+ }
+
+ /** The user paused, resumed or removed a direction. Only they can undo it. */
+ fun setDirectionByUser(id: String, status: String) = synchronized(lock) {
+ val root = load()
+ val list = dirs(root).map { if (it.id == id) it.copy(status = status, byUser = status != "active", updatedAt = clock()) else it }
+ putDirs(root, list)
+ save(root)
+ }
+
+ // ---- bubbles ----------------------------------------------------------------
+
+ /**
+ * Bring the bubble todos in line with today's and tomorrow's plans: a todo for every planned remind/ask
+ * item with a clock time still ahead, none for anything else. Writes the todos into the book and returns
+ * what the body has to arm and cancel.
+ */
+ fun reconcile(): Sync = synchronized(lock) {
+ val now = clock()
+ val want = HashMap<String, JSONObject>()
+ val at = HashMap<String, Long>()
+ for (date in listOf(today(), tomorrow())) {
+ val d = day(date) ?: continue
+ for (it in d.items) {
+ if (it.status != "planned" || it.kind !in INTERRUPTING || it.time.isEmpty()) continue
+ val t = LocalDate.parse(date).atTime(LocalTime.parse(it.time)).atZone(zone).toInstant().toEpochMilli()
+ if (t <= now) continue
+ val ref = "$date#${it.id}"
+ want[ref] = JSONObject().put("text", it.what).put("buttons", JSONArray(it.buttons))
+ .put("dismiss", it.dismiss).put("kind", it.tag.ifEmpty { "plan-${it.id}" })
+ .put("ttl_minutes", ITEM_TTL_MIN).put("plan_ref", ref)
+ at[ref] = t
+ }
+ }
+ val arm = mutableListOf<Todo>()
+ val cancel = mutableListOf<String>()
+ val have = book.todos("pending").filter { it.nudge.isNotEmpty() }
+ val haveRefs = HashSet<String>()
+ for (t in have) {
+ val spec = runCatching { JSONObject(t.nudge) }.getOrNull()
+ val ref = spec?.optString("plan_ref").orEmpty()
+ val w = want[ref]
+ if (w != null && t.at == at[ref] && spec.toString() == w.toString()) {
+ haveRefs += ref
+ continue
+ }
+ book.patchTodo(t.id, status = "dropped", nextRunAt = 0L)
+ cancel += t.id
+ }
+ for ((ref, spec) in want) {
+ if (ref in haveRefs) continue
+ val t = Todo(
+ id = NotebookBook.newTodoId() + ref.filter { it.isLetterOrDigit() },
+ what = "Plan bubble: ${spec.optString("text")}",
+ mode = "once", at = at[ref]!!, cronExpr = "", nextRunAt = at[ref]!!,
+ lastRunAt = 0L, lastStatus = "", lastError = "", status = "active", createdAt = now,
+ nudge = spec.toString(),
+ )
+ book.addTodo(t)
+ arm += t
+ }
+ Sync(arm, cancel)
+ }
+
+ /**
+ * A bubble todo came due: turn it into a bubble, or say why not. Never wakes the model.
+ *
+ * @return the bubble to post, or null when it is stale or over the user's limits — in which case the
+ * plan item already carries the reason.
+ */
+ fun bubbleFor(todo: Todo, nudges: NudgeBook, level: NudgeBook.Level, muted: Set<String>): Nudge? {
+ book.patchTodo(todo.id, status = "done")
+ val spec = runCatching { JSONObject(todo.nudge) }.getOrNull() ?: return null
+ val ref = spec.optString("plan_ref")
+ val n = nudges.parse(spec, untrusted = todo.untrusted)
+ val base = if (todo.at > 0) todo.at else clock()
+ val bubble = n.copy(expiresAt = base + spec.optLong("ttl_minutes", ITEM_TTL_MIN) * 60_000L, planRef = ref)
+ if (clock() >= bubble.expiresAt) {
+ mark(ref, "missed", "the device was not running when it was due")
+ return null
+ }
+ nudges.admit(bubble, level, muted)?.let { why ->
+ mark(ref, "skipped", why)
+ return null
+ }
+ return bubble
+ }
+
+ /** A bubble todo came due with nothing running to show it. Closed, and the item says so — no model, no notification. */
+ fun missed(todo: Todo) {
+ book.patchTodo(todo.id, status = "done")
+ runCatching { JSONObject(todo.nudge).optString("plan_ref") }.getOrNull()
+ ?.takeIf { it.isNotEmpty() }?.let { mark(it, "missed", "nothing was running when it was due") }
+ }
+
+ /** Write what happened to a bubble back onto its plan item. See [statusFor]. */
+ fun recordOutcome(n: Nudge, how: String, button: String?) {
+ if (n.planRef.isEmpty()) return
+ statusFor(n, how, button)?.let { mark(n.planRef, it, "") }
+ }
+
+ private fun mark(ref: String, status: String, note: String) = synchronized(lock) {
+ val date = ref.substringBefore('#')
+ val id = ref.substringAfter('#')
+ val root = load()
+ val d = root.optJSONObject("days")?.optJSONObject(date)?.let(::toDay) ?: return@synchronized
+ putDay(root, d.copy(items = d.items.map { if (it.id == id) it.copy(status = status, note = note) else it }))
+ save(root)
+ }
+
+ // ---- when to think (PlanMind) ---------------------------------------------------------
+
+ private fun meta(root: JSONObject): JSONObject = root.optJSONObject("meta") ?: JSONObject()
+
+ private fun minuteOfDay(): Int = Instant.ofEpochMilli(clock()).atZone(zone).toLocalTime().let { it.hour * 60 + it.minute }
+
+ /** Today's plan has not been looked at in the light of the morning yet, and it is morning or later. */
+ fun morningDue(): Boolean = synchronized(lock) {
+ meta(load()).optString("morning_date") != today() && minuteOfDay() >= MORNING_FROM_MIN
+ }
+
+ fun markMorning() = synchronized(lock) {
+ val root = load()
+ root.put("meta", meta(root).put("morning_date", today())); save(root)
+ }
+
+ /**
+ * Whether to ask "is it the moment for one of today's loose-time items?" — only when there is such an item
+ * to decide about, outside the night, not more often than [MUSE_GAP_MS] and not more than [MUSE_PER_DAY]
+ * 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
+ if (m.optString("muse_date") == today() && m.optInt("muse_count") >= MUSE_PER_DAY) return false
+ val d = root.optJSONObject("days")?.optJSONObject(today())?.let(::toDay) ?: return false
+ d.items.any { it.status == "planned" && it.kind in INTERRUPTING && it.time.isEmpty() }
+ }
+
+ fun markMuse() = synchronized(lock) {
+ val root = load()
+ val m = meta(root)
+ val count = if (m.optString("muse_date") == today()) m.optInt("muse_count") + 1 else 1
+ root.put("meta", m.put("muse_at", clock()).put("muse_date", today()).put("muse_count", count)); save(root)
+ }
+
+ /** Everything the morning look needs, as text: who, what for, what happened yesterday, what is on today. */
+ fun morningContext(): String = synchronized(lock) {
+ val root = load()
+ buildString {
+ append("Now: ").append(Instant.ofEpochMilli(clock()).atZone(zone).toLocalDateTime().toString().take(16).replace('T', ' '))
+ append(" (").append(LocalDate.parse(today()).dayOfWeek).append(")\n\n")
+ val dirs = dirs(root).filter { it.status == "active" }
+ append("Long-term directions:\n")
+ if (dirs.isEmpty()) append("(none yet)\n")
+ dirs.forEach { append("- ${it.title}: ${it.howIHelp} (because: ${it.why}; from: ${it.source})\n") }
+ val y = root.optJSONObject("days")?.optJSONObject(LocalDate.parse(today()).minusDays(1).toString())?.let(::toDay)
+ append("\nYesterday's plan and what happened:\n")
+ if (y == null) append("(none)\n") else y.items.forEach { append("- ${it.time.ifEmpty { it.slot }} ${it.kind} \"${it.what}\" → ${it.status}${if (it.note.isNotEmpty()) " (${it.note})" else ""}\n") }
+ val t = root.optJSONObject("days")?.optJSONObject(today())?.let(::toDay)
+ append("\nToday's draft:\n")
+ if (t == null) {
+ append("(none)\n")
+ } else {
+ append("intent: ${t.intent}\n")
+ t.items.forEach { append("- ${it.time.ifEmpty { it.slot }} ${it.kind} \"${it.what}\" because ${it.because} → ${it.status}\n") }
+ if (t.quiet.isNotEmpty()) append("quiet: ${t.quiet.joinToString("; ")}\n")
+ if (t.userDropped.isNotEmpty()) append("removed by the user today (never put back): ${t.userDropped.joinToString("; ")}\n")
+ }
+ val end = LocalDate.parse(today()).plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
+ val due = book.todos("pending").filter { it.nudge.isEmpty() && it.status == "active" && it.nextRunAt in 1 until end }
+ append("\nTodos due today:\n")
+ if (due.isEmpty()) append("(none)\n")
+ due.forEach { append("- ${Instant.ofEpochMilli(it.nextRunAt).atZone(zone).toLocalTime().toString().take(5)} ${it.what}\n") }
+ val notes = book.indexForPrompt()
+ if (notes.isNotEmpty()) append("\nWhat your notebook holds about them:\n").append(notes).append('\n')
+ }
+ }
+
+ /** Today's loose-time interrupting items, for the muse to choose from (or not). Null when there are none. */
+ fun museContext(): String? = synchronized(lock) {
+ val d = day(today()) ?: return null
+ val open = d.items.filter { it.status == "planned" && it.kind in INTERRUPTING && it.time.isEmpty() }
+ if (open.isEmpty()) return null
+ buildString {
+ append("Now: ").append(Instant.ofEpochMilli(clock()).atZone(zone).toLocalTime().toString().take(5)).append('\n')
+ append("Today's intent: ${d.intent}\n")
+ if (d.quiet.isNotEmpty()) append("Not today: ${d.quiet.joinToString("; ")}\n")
+ append("\nWhat already happened today:\n")
+ d.items.filter { it.status != "planned" }.forEach { append("- ${it.time.ifEmpty { it.slot }} \"${it.what}\" → ${it.status}\n") }
+ append("\nWaiting for the right moment (choose at most one, by id):\n")
+ open.forEach { append("- ${it.id}: when \"${it.slot}\", ${it.kind} \"${it.what}\"\n") }
+ }
+ }
+
+ /** The muse chose an item: its bubble, admitted against the user's limits, or null with the reason recorded. */
+ fun bubbleForItem(id: String, nudges: NudgeBook, level: NudgeBook.Level, muted: Set<String>): Nudge? {
+ val date = today()
+ val it = day(date)?.items?.firstOrNull { x -> x.id == id && x.status == "planned" && x.kind in INTERRUPTING } ?: return null
+ val spec = JSONObject().put("text", it.what).put("buttons", JSONArray(it.buttons)).put("dismiss", it.dismiss)
+ .put("kind", it.tag.ifEmpty { "plan-${it.id}" }).put("ttl_minutes", MUSE_TTL_MIN)
+ val n = nudges.parse(spec, untrusted = false).copy(planRef = "$date#$id")
+ nudges.admit(n, level, muted)?.let { why ->
+ mark(n.planRef, "skipped", why)
+ return null
+ }
+ return n
+ }
+
+ /** A week since the directions were last looked at, and there are some to look at. */
+ private fun directionsReviewDue(root: JSONObject): Boolean =
+ dirs(root).any { it.status == "active" } && clock() - meta(root).optLong("directions_reviewed_at") >= WEEK_MS
+
+ // ---- what rides on every user message ---------------------------------------------
+
+ fun indexForPrompt(): String = synchronized(lock) {
+ val root = load()
+ val active = dirs(root).filter { it.status == "active" }
+ val d = root.optJSONObject("days")?.optJSONObject(today())?.let(::toDay)
+ if (d == null && active.isEmpty()) {
+ return "No plan yet: no long-term directions, nothing planned today (plan_directions / day_plan)."
+ }
+ buildString {
+ if (d == null) {
+ append("No plan for today yet.")
+ } else {
+ append("Today's plan: \"${d.intent}\"")
+ val next = d.items.filter { it.status == "planned" }.sortedBy { it.time.ifEmpty { "99" } }.take(2)
+ if (next.isNotEmpty()) append(" — next: ").append(next.joinToString("; ") { "${it.time.ifEmpty { it.slot }} ${it.kind} \"${it.what}\"" })
+ val counts = d.items.groupingBy { it.status }.eachCount().entries.joinToString(", ") { "${it.key} ${it.value}" }
+ if (counts.isNotEmpty()) append(" ($counts)")
+ if (d.quiet.isNotEmpty()) append(". Not today: ").append(d.quiet.joinToString("; "))
+ append('.')
+ }
+ if (active.isNotEmpty()) append(" Long-term: ").append(active.joinToString("; ") { it.title }).append('.')
+ if (directionsReviewDue(root)) {
+ append(" A week since you last looked over the directions: in your next quiet review, plan_directions list — done, stalled, or something new they said?")
+ }
+ }
+ }
+
+ // ---- json ----------------------------------------------------------------------
+
+ private fun toDirection(o: JSONObject) = Direction(
+ o.optString("id"), o.optString("title"), o.optString("why"), o.optString("how_i_help"),
+ o.optString("good_when"), o.optString("source"), o.optString("status", "active"),
+ o.optBoolean("by_user"), o.optLong("updated_at"),
+ )
+
+ private fun toJson(d: Direction) = JSONObject().put("id", d.id).put("title", d.title).put("why", d.why)
+ .put("how_i_help", d.howIHelp).put("good_when", d.goodWhen).put("source", d.source)
+ .put("status", d.status).put("by_user", d.byUser).put("updated_at", d.updatedAt)
+
+ private fun toDay(o: JSONObject): Day {
+ val items = o.optJSONArray("items") ?: JSONArray()
+ return Day(
+ o.optString("date"), o.optString("intent"),
+ (0 until items.length()).mapNotNull { items.optJSONObject(it) }.map { i ->
+ Item(
+ i.optString("id"), i.optString("time"), i.optString("slot"), i.optString("kind"), i.optString("what"),
+ i.optString("because"),
+ i.optJSONArray("buttons")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty(),
+ i.optString("dismiss"), i.optString("tag"), i.optString("status", "planned"), i.optString("note"),
+ )
+ },
+ strings(o.optJSONArray("quiet")), o.optLong("updated_at"), strings(o.optJSONArray("user_dropped")),
+ )
+ }
+
+ private fun toJson(d: Day) = JSONObject().put("date", d.date).put("intent", d.intent)
+ .put(
+ "items",
+ JSONArray().apply {
+ d.items.forEach {
+ put(
+ JSONObject().put("id", it.id).put("time", it.time).put("slot", it.slot).put("kind", it.kind)
+ .put("what", it.what).put("because", it.because).put("buttons", JSONArray(it.buttons))
+ .put("dismiss", it.dismiss).put("tag", it.tag).put("status", it.status).put("note", it.note),
+ )
+ }
+ },
+ )
+ .put("quiet", JSONArray(d.quiet)).put("updated_at", d.updatedAt).put("user_dropped", JSONArray(d.userDropped))
+
+ private fun strings(a: JSONArray?): List<String> = if (a == null) emptyList() else (0 until a.length()).map { a.optString(it) }
+
+ private fun req(p: JSONObject, key: String): String =
+ p.optString(key).trim().ifEmpty { throw IllegalArgumentException("$key is required") }
+
+ companion object {
+ const val SECTION = "plan"
+ const val MAX_DIRECTIONS = 5
+ const val MAX_ITEMS = 12
+ const val MAX_INTERRUPTIONS = 5
+ const val KEEP_DAYS = 7L
+ /** A planned bubble is worth showing for an hour after its time, not longer. */
+ const val ITEM_TTL_MIN = 60L
+ const val MORNING_FROM_MIN = 5 * 60
+ const val MUSE_GAP_MS = 40 * 60_000L
+ const val MUSE_PER_DAY = 12
+ const val MUSE_TTL_MIN = 30L
+ const val WEEK_MS = 7 * 24 * 60 * 60_000L
+ val KINDS = setOf("remind", "ask", "prepare", "follow_up")
+ val INTERRUPTING = setOf("remind", "ask")
+
+ /**
+ * What a bubble's end means for its plan item. A bubble with only words that faded on screen was
+ * delivered — there was nothing to answer; one with buttons that faded was ignored. Null = no change
+ * (it was displaced and will come back).
+ */
+ fun statusFor(n: Nudge, how: String, button: String?): String? = when (how) {
+ "button" -> if (button != null && button == n.dismiss) "declined" else "done"
+ "body", "logged" -> "done"
+ "timeout" -> if (n.buttons.isEmpty()) "done" else "ignored"
+ "mute" -> "declined"
+ "expired" -> "missed"
+ else -> null
+ }
+ }
+}
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 c41543e..796754b 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
@@ -893,6 +893,43 @@ object ToolSchemas {
"timeout_ms" to prop("integer", "Auto-dismiss. Default 30000.", default = 30000),
),
),
+ tool(
+ localOnly = true,
+ name = "nudge",
+ method = "ui.nudge",
+ description = """
+ Hold up a small SILENT bubble over your ball: the lightest way to speak
+ first. Nothing is read aloud, the mic stays off, and you are not
+ blocked — this returns at once. If the user is busy (a card is up,
+ you are talking, a task is running, the screen is off, quiet hours)
+ the device holds it until they are not, and drops it once `ttl_minutes`
+ has passed. Ignoring it is a perfectly good answer.
+
+ USE FOR things that are fine to miss: "该喝水啦", "12点了,要帮你点外卖吗?",
+ "你下午三点有个会". NOT for anything that needs a decision now (that is
+ ask_user) and NOT as a second copy of something you are saying out
+ loud in this turn — say it or bubble it, never both.
+
+ With buttons, a tap comes back to you later as its own turn
+ ("[You offered in a bubble: … — the user tapped …]"). Mark the "no
+ thanks" button as `dismiss`: tapping it just closes the bubble and
+ you hear nothing. A button only means they want it — anything
+ irreversible (paying, sending) still needs its own yes.
+
+ The device rations these (per hour, per day, and per `kind`) at a
+ level the user chose, and the user can mute a kind. A refusal says
+ why: do not retry it, and do not dress the same thing up as another
+ kind.
+ """.trimIndent(),
+ required = listOf("text"),
+ props = mapOf(
+ "text" to prop("string", "One short sentence (≤ 60 characters), in the language the user speaks. Plain text, no markdown."),
+ "buttons" to prop("array", "0–3 short labels, e.g. [\"好\",\"不用\"]. Omit for a bubble that only says something."),
+ "dismiss" to prop("string", "Which button means \"no thanks\" — exactly one of `buttons`. Tapping it ends the bubble with no turn."),
+ "ttl_minutes" to prop("integer", "How long it stays worth saying, 1–720. Default 30.", default = 30),
+ "kind" to prop("string", "A short stable tag for this sort of bubble, e.g. water, meal, meeting. Used for rationing and for the user muting it."),
+ ),
+ ),
tool(
name = "show_html",
method = "ui.show_html",
@@ -1657,6 +1694,76 @@ object ToolSchemas {
"cron" to prop("string", "Recurring, 5 fields \"minute hour day month weekday\". Densest is once every 15 minutes"),
),
),
+ tool(
+ localOnly = true,
+ name = "plan_directions",
+ method = "note.directions",
+ description = """
+ Your long-term directions with this person: what you are helping them get done these weeks, and how.
+ They are the reason behind every item of every day plan, and the user can see them — and pause or
+ remove them — in Settings.
+
+ - `list`: see them.
+ - `add`: title, why, how_i_help, good_when, source. **Only from what the user said or did** — `source`
+ says when and what ("10-26: 「这周要把 0.6.2 发出去」"). A goal you think would be good for them is
+ not theirs; do not add it.
+ - `update` / `pause` / `resume` / `done` / `drop`: by id.
+
+ At most 5 active; more than that is no focus at all. A direction the user paused or removed is theirs:
+ you cannot resume or re-add it unless they ask for it in so many words.
+ """.trimIndent(),
+ required = listOf("action"),
+ props = mapOf(
+ "action" to propEnum("What to do", listOf("list", "add", "update", "pause", "resume", "done", "drop")),
+ "id" to prop("string", "For everything but list and add; take it from list"),
+ "title" to prop("string", "A few words, in the user's language"),
+ "why" to prop("string", "Why it matters to them, in their terms"),
+ "how_i_help" to prop("string", "What you will do about it, concretely"),
+ "good_when" to prop("string", "How you will know it is done"),
+ "source" to prop("string", "When and what they said or did that makes this theirs. Required for add"),
+ ),
+ ),
+ tool(
+ localOnly = true,
+ name = "day_plan",
+ method = "note.day_plan",
+ description = """
+ Your plan for a day: what you mean to do for this person, and when you will speak to them. The user sees
+ it in Settings and can remove items; a line of it rides on every message.
+
+ - `get`: the plan for `date` (today, tomorrow or YYYY-MM-DD).
+ - `write`: replace the still-planned part of that day.
+ - `intent`: one sentence in your own voice and the user's language — 「今天我想帮他把发布收个尾,别的事少打扰。」
+ - `items`: each `{time, slot, kind, what, because, buttons, dismiss, tag}`
+ - `time` "HH:mm", or "" with a `slot` (a loose time: 午饭前, when they first talk to me).
+ - `kind`: remind (a bubble telling them something), ask (a bubble with buttons), prepare (something
+ you do quietly ahead of time), follow_up (pick up something left half-way).
+ - `what`: for remind/ask, exactly the bubble's words (≤ 60 characters, their language); otherwise
+ what you will do.
+ - `because`: the direction or todo it serves. Required — an item that serves nothing is not part
+ of the plan.
+ - remind/ask with a `time` become bubbles at that minute with no further thought from you; what
+ happened (done / declined / ignored / skipped) is written back onto the item.
+ - `quiet`: what you will NOT bother them about today — as much a part of the plan as the items.
+ At most 5 remind/ask a day. Items already done or ignored stay as the day's history; items the user
+ removed cannot be put back.
+ - `mark`: set an item done / dropped / moved by id, when it was handled some other way.
+
+ A day with nothing to say is a good plan. Never plan anything irreversible (paying, sending, deleting):
+ those need the user, asked at the time.
+ """.trimIndent(),
+ required = listOf("action"),
+ props = mapOf(
+ "action" to propEnum("What to do", listOf("get", "write", "mark")),
+ "date" to prop("string", "today (default), tomorrow, or YYYY-MM-DD"),
+ "intent" to prop("string", "For write: one sentence, your own voice"),
+ "items" to prop("array", "For write: the items, see the description"),
+ "quiet" to prop("array", "For write: what you will leave alone today"),
+ "id" to prop("string", "For mark: the item id from get"),
+ "status" to propEnum("For mark", listOf("done", "dropped", "moved")),
+ "note" to prop("string", "For mark: a few words on why"),
+ ),
+ ),
tool(
localOnly = true,
name = "todos",
diff --git a/core/src/main/kotlin/net/kuafuai/andee/net/TurnGuards.kt b/core/src/main/kotlin/net/kuafuai/andee/net/TurnGuards.kt
index 70f5bf2..03fde4b 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/net/TurnGuards.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/net/TurnGuards.kt
@@ -17,6 +17,8 @@ object TurnGuards {
private val SCENE_WRITES = setOf("scene.save", "scene.enter", "scene.delete")
+ private val PLAN_WRITES = setOf("note.directions", "note.day_plan")
+
/**
* What the quiet-hour review may do to the gear shelf besides reading the notebook: write down what an
* app is *for*. It must not change what the user keeps out of view ([GEAR_VISIBILITY]) — that is theirs.
@@ -69,6 +71,14 @@ object TurnGuards {
"user's other devices: $method. Tell the user what you would have handed over and let them ask.",
)
}
+ // Same stranger, a quieter prize: the plan. Its timed items become bubbles that a tap turns into a
+ // turn of the user's own, so a stranger's words written into it would come back trusted.
+ if (untrusted && method in PLAN_WRITES) {
+ throw IllegalStateException(
+ "This turn started from somebody else's words (a notification, or a friend's Andee), so the plan cannot be " +
+ "changed from it: $method. If something here belongs in the plan, add it the next time the user talks to you.",
+ )
+ }
// Same stranger, a different prize: a scene is standing instructions the
// model works by afterwards, and one whose rules say "reply to my
// messages for me" is a capability. Reading and leaving stay open.
diff --git a/core/src/main/kotlin/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt b/core/src/main/kotlin/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt
index b8eef63..8a83be9 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/ui/ball/EmotionBallRenderer.kt
@@ -149,7 +149,7 @@ class EmotionBallRenderer {
/** A `screen.*` command just ran — see [pulseTool]. */
private var toolLeft = 0f
- /** Transient SUCCESS / FAILED face, outranking everything while it lasts. */
+ /** Transient SUCCESS / FAILED / WAVE face, outranking everything while it lasts. */
private var overlayMood: Mood? = null
private var overlayLeft = 0f
@@ -197,6 +197,15 @@ class EmotionBallRenderer {
outcomeRequest = if (ok) Mood.SUCCESS else Mood.FAILED
}
+ /**
+ * The ball is holding up a bubble it raised by itself: a wave and a hop, then back to whatever it was.
+ * Rides the outcome flash because it is the same kind of thing — a moment of face that outranks the
+ * rest and lets go on its own. A look without gestures shows WAVE as its plain face row.
+ */
+ fun greet() {
+ outcomeRequest = Mood.WAVE
+ }
+
/** Play a one-shot gesture on the next frame. Safe from any thread. */
fun request(action: Action) {
actionRequest = action
@@ -603,7 +612,13 @@ class EmotionBallRenderer {
overlayMood = it
overlayLeft = OVERLAY_SECONDS
toolLeft = 0f
- state.trigger(if (it == Mood.SUCCESS) Action.POP else Action.RECOIL)
+ state.trigger(
+ when (it) {
+ Mood.SUCCESS -> Action.POP
+ Mood.FAILED -> Action.RECOIL
+ else -> Action.HOP
+ },
+ )
}
if (overlayLeft > 0f) {
overlayLeft -= dt
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt
new file mode 100644
index 0000000..3ed235a
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/NudgeBookTest.kt
@@ -0,0 +1,111 @@
+package net.kuafuai.andee.brain
+
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class NudgeBookTest {
+
+ private var now = 1_000_000_000L
+ private val book = NudgeBook { now }
+
+ private fun nudge(kind: String = "water", vararg buttons: String, dismiss: String? = null): Nudge =
+ book.parse(
+ JSONObject().put("text", "该喝水啦").put("kind", kind)
+ .apply { if (buttons.isNotEmpty()) put("buttons", JSONArray(buttons.toList())) }
+ .apply { if (dismiss != null) put("dismiss", dismiss) },
+ untrusted = false,
+ )
+
+ @Test fun parsesDefaults() {
+ val n = book.parse(JSONObject().put("text", " 该喝水啦 "), untrusted = true)
+ assertEquals("该喝水啦", n.text)
+ assertEquals(emptyList<String>(), n.buttons)
+ assertEquals("other", n.kind)
+ assertEquals(now + 30 * 60_000L, n.expiresAt)
+ assertTrue(n.untrusted)
+ }
+
+ @Test(expected = IllegalArgumentException::class) fun rejectsDismissNotAmongButtons() {
+ nudge("meal", "好", "不用", dismiss = "算了")
+ }
+
+ @Test(expected = IllegalArgumentException::class) fun rejectsFourButtons() {
+ nudge("meal", "a", "b", "c", "d")
+ }
+
+ @Test(expected = IllegalArgumentException::class) fun rejectsLongText() {
+ book.parse(JSONObject().put("text", "字".repeat(NudgeBook.MAX_TEXT + 1)), false)
+ }
+
+ @Test(expected = IllegalArgumentException::class) fun rejectsTtlOutOfRange() {
+ book.parse(JSONObject().put("text", "x").put("ttl_minutes", 721), false)
+ }
+
+ @Test fun offRefusesEverything() {
+ assertNotNull(book.admit(nudge(), NudgeBook.Level.OFF, emptySet()))
+ }
+
+ @Test fun mutedKindRefused() {
+ assertNotNull(book.admit(nudge("water"), NudgeBook.Level.NORMAL, setOf("water")))
+ assertNull(book.admit(nudge("meal"), NudgeBook.Level.NORMAL, setOf("water")))
+ }
+
+ @Test fun hourlyBudgetAtFew() {
+ assertNull(book.admit(nudge("a"), NudgeBook.Level.FEW, emptySet()))
+ assertNotNull(book.admit(nudge("b"), NudgeBook.Level.FEW, emptySet()))
+ now += NudgeBook.HOUR_MS
+ assertNull(book.admit(nudge("b"), NudgeBook.Level.FEW, emptySet()))
+ }
+
+ @Test fun dailyBudgetAtFew() {
+ repeat(4) {
+ assertNull(book.admit(nudge("k$it"), NudgeBook.Level.FEW, emptySet()))
+ now += NudgeBook.HOUR_MS
+ }
+ assertNotNull(book.admit(nudge("k9"), NudgeBook.Level.FEW, emptySet()))
+ now += NudgeBook.DAY_MS
+ assertNull(book.admit(nudge("k9"), NudgeBook.Level.FEW, emptySet()))
+ }
+
+ @Test fun sameKindCoolsDown() {
+ assertNull(book.admit(nudge("water"), NudgeBook.Level.NORMAL, emptySet()))
+ now += 40 * 60_000L
+ assertNotNull(book.admit(nudge("water"), NudgeBook.Level.NORMAL, emptySet()))
+ assertNull(book.admit(nudge("meal"), NudgeBook.Level.NORMAL, emptySet()))
+ now += 10 * 60_000L
+ // Two in the last hour at NORMAL (water at -50, meal at -10) — the hourly cap, not the cooldown.
+ assertNotNull(book.admit(nudge("water"), NudgeBook.Level.NORMAL, emptySet()))
+ }
+
+ @Test fun refusalDoesNotSpendBudget() {
+ assertNotNull(book.admit(nudge("water"), NudgeBook.Level.NORMAL, setOf("water")))
+ assertNull(book.admit(nudge("a"), NudgeBook.Level.NORMAL, emptySet()))
+ assertNull(book.admit(nudge("b"), NudgeBook.Level.NORMAL, emptySet()))
+ }
+
+ @Test fun levelFallbacks() {
+ assertEquals(NudgeBook.Level.FEW, NudgeBook.Level.of(null))
+ assertEquals(NudgeBook.Level.FEW, NudgeBook.Level.of(""))
+ assertEquals(NudgeBook.Level.NORMAL, NudgeBook.Level.of("normal"))
+ 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 \"好\""))
+ assertTrue(NudgeBook.answerText(n, null).contains("bubble itself"))
+ }
+}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt b/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt
new file mode 100644
index 0000000..6ad4699
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/config/PlansTest.kt
@@ -0,0 +1,226 @@
+package net.kuafuai.andee.config
+
+import net.kuafuai.andee.brain.NudgeBook
+import net.kuafuai.andee.net.TurnGuards
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.time.LocalDateTime
+import java.time.ZoneId
+
+class PlansTest {
+
+ private val zone = ZoneId.of("Asia/Shanghai")
+ /** 2026-10-27 09:00 local. */
+ private var now = LocalDateTime.of(2026, 10, 27, 9, 0).atZone(zone).toInstant().toEpochMilli()
+ private 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 }
+ })
+ private val plans = Plans(book, { now }, zone)
+ private val nudges = NudgeBook { now }
+
+ private fun item(time: String, what: String, kind: String = "remind", vararg buttons: String) = JSONObject()
+ .put("time", time).put("kind", kind).put("what", what).put("because", "规律喝水")
+ .apply { if (buttons.isNotEmpty()) put("buttons", JSONArray(buttons.toList())).put("dismiss", buttons.last()) }
+
+ private fun write(vararg items: JSONObject, date: String = "today") = plans.handle(
+ "note.day_plan",
+ JSONObject().put("action", "write").put("date", date).put("intent", "今天少打扰").put("items", JSONArray(items.toList())),
+ 8,
+ )
+
+ @Test fun timedRemindersBecomeBubbleTodos() {
+ write(item("10:00", "该喝水啦"), item("08:00", "早上好"), item("", "看看发布进度", "prepare"))
+ val sync = plans.reconcile()
+ // 08:00 is already past and the prepare item has no bubble: one todo.
+ assertEquals(1, sync.arm.size)
+ val spec = JSONObject(sync.arm[0].nudge)
+ assertEquals("该喝水啦", spec.getString("text"))
+ assertEquals("2026-10-27#p1", spec.getString("plan_ref"))
+ // Reconciling again changes nothing.
+ val again = plans.reconcile()
+ assertTrue(again.arm.isEmpty() && again.cancel.isEmpty())
+ }
+
+ @Test fun rewritingCancelsTheOldBubble() {
+ write(item("10:00", "该喝水啦"))
+ val first = plans.reconcile().arm.single()
+ write(item("11:00", "该喝水啦"))
+ val sync = plans.reconcile()
+ assertEquals(listOf(first.id), sync.cancel)
+ assertEquals(1, sync.arm.size)
+ }
+
+ @Test fun whatTheUserRemovedCannotComeBack() {
+ write(item("10:00", "该喝水啦"))
+ plans.reconcile()
+ plans.dropItemByUser("2026-10-27", "p1")
+ assertEquals(1, plans.reconcile().cancel.size)
+ val r = write(item("10:30", "该喝水啦"))
+ assertEquals(1, r.getJSONArray("refused").length())
+ assertTrue(plans.reconcile().arm.isEmpty())
+ }
+
+ @Test(expected = IllegalArgumentException::class) fun everyItemNeedsABecause() {
+ write(JSONObject().put("time", "10:00").put("kind", "remind").put("what", "该喝水啦"))
+ }
+
+ @Test(expected = IllegalArgumentException::class) fun atMostFiveInterruptions() {
+ write(*(10..15).map { item("$it:00", "第 $it 点") }.toTypedArray())
+ }
+
+ @Test fun dueBubbleCarriesItsPlanRefAndOutcomeIsWrittenBack() {
+ write(item("10:00", "要帮你点外卖吗?", "ask", "好", "不用"))
+ val todo = plans.reconcile().arm.single()
+ now = todo.at
+ val n = plans.bubbleFor(todo, nudges, NudgeBook.Level.NORMAL, emptySet())
+ assertNotNull(n)
+ assertEquals("2026-10-27#p1", n!!.planRef)
+ assertEquals(todo.at + 60 * 60_000L, n.expiresAt)
+ plans.recordOutcome(n, "button", "不用")
+ assertEquals("declined", plans.day("2026-10-27")!!.items.single().status)
+ assertEquals("done", book.todoById(todo.id)!!.status)
+ }
+
+ @Test fun aBubbleLongPastItsTimeIsMissed() {
+ write(item("10:00", "该喝水啦"))
+ val todo = plans.reconcile().arm.single()
+ now = todo.at + 2 * 60 * 60_000L
+ assertNull(plans.bubbleFor(todo, nudges, NudgeBook.Level.NORMAL, emptySet()))
+ assertEquals("missed", plans.day("2026-10-27")!!.items.single().status)
+ }
+
+ @Test fun overTheUsersLimitIsSkippedWithTheReason() {
+ write(item("10:00", "该喝水啦"))
+ val todo = plans.reconcile().arm.single()
+ now = todo.at
+ assertNull(plans.bubbleFor(todo, nudges, NudgeBook.Level.OFF, emptySet()))
+ val it = plans.day("2026-10-27")!!.items.single()
+ assertEquals("skipped", it.status)
+ assertTrue(it.note.contains("turned bubbles off"))
+ }
+
+ @Test fun keptHistorySurvivesARewrite() {
+ write(item("10:00", "该喝水啦"))
+ val todo = plans.reconcile().arm.single()
+ now = todo.at
+ plans.recordOutcome(plans.bubbleFor(todo, nudges, NudgeBook.Level.NORMAL, emptySet())!!, "timeout", null)
+ write(item("15:00", "起来活动一下"))
+ val items = plans.day("2026-10-27")!!.items
+ assertEquals(listOf("done", "planned"), items.map { it.status })
+ assertEquals(listOf("p1", "p2"), items.map { it.id })
+ }
+
+ @Test fun directionsComeFromTheUserAndStayRemovedWhenTheyRemoveThem() {
+ val add = plans.handle(
+ "note.directions",
+ JSONObject().put("action", "add").put("title", "Andee 发布").put("source", "10-26: 这周要发 0.6.2"),
+ 8,
+ )
+ assertTrue(add.getBoolean("added"))
+ plans.setDirectionByUser(add.getString("id"), "dropped")
+ val again = plans.handle(
+ "note.directions",
+ JSONObject().put("action", "add").put("title", "Andee 发布").put("source", "x"),
+ 8,
+ )
+ assertFalse(again.getBoolean("added"))
+ }
+
+ @Test fun indexNamesTodayAndTheDirections() {
+ assertTrue(plans.indexForPrompt().startsWith("No plan yet"))
+ plans.handle("note.directions", JSONObject().put("action", "add").put("title", "规律喝水").put("source", "他说的"), 8)
+ write(item("10:00", "该喝水啦"))
+ val line = plans.indexForPrompt()
+ assertTrue(line.contains("\"今天少打扰\""))
+ assertTrue(line.contains("10:00 remind \"该喝水啦\""))
+ assertTrue(line.contains("Long-term: 规律喝水"))
+ }
+
+ @Test fun tomorrowsPlanIsScheduledToo() {
+ write(item("09:30", "早"), date = "tomorrow")
+ val t = plans.reconcile().arm.single()
+ assertTrue(JSONObject(t.nudge).getString("plan_ref").startsWith("2026-10-28#"))
+ }
+
+ @Test fun aStrangersTurnCannotWriteThePlan() {
+ for (m in listOf("note.day_plan", "note.directions")) {
+ val thrown = runCatching { TurnGuards.check(m, silent = false, untrusted = true) }.exceptionOrNull()
+ assertTrue(thrown is IllegalStateException)
+ }
+ TurnGuards.check("note.day_plan", silent = true, untrusted = false)
+ }
+
+ @Test fun morningOncePerDayAndNotBeforeFive() {
+ assertTrue(plans.morningDue())
+ plans.markMorning()
+ assertFalse(plans.morningDue())
+ now = LocalDateTime.of(2026, 10, 28, 4, 30).atZone(zone).toInstant().toEpochMilli()
+ assertFalse(plans.morningDue())
+ now = LocalDateTime.of(2026, 10, 28, 7, 0).atZone(zone).toInstant().toEpochMilli()
+ assertTrue(plans.morningDue())
+ }
+
+ private fun slotItem(slot: String, what: String) = JSONObject()
+ .put("slot", slot).put("kind", "ask").put("what", what).put("because", "规律喝水")
+ .put("buttons", JSONArray(listOf("好", "不用"))).put("dismiss", "不用")
+
+ @Test fun museOnlyWithALooseTimeItemSpacedAndNotAtNight() {
+ write(item("10:00", "该喝水啦"))
+ assertFalse(plans.museDue()) // only clock-time items: nothing to decide
+ write(slotItem("午饭前", "要帮你点外卖吗?"))
+ assertTrue(plans.museDue())
+ assertTrue(plans.museContext()!!.contains("午饭前"))
+ plans.markMuse()
+ assertFalse(plans.museDue()) // within the gap
+ 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
+ }
+
+ @Test fun museCapPerDay() {
+ write(slotItem("下午", "起来活动一下?"))
+ repeat(Plans.MUSE_PER_DAY) { plans.markMuse(); now += Plans.MUSE_GAP_MS }
+ assertFalse(plans.museDue())
+ }
+
+ @Test fun theMusesChoiceBecomesABubbleOrIsSkippedWithTheReason() {
+ write(slotItem("午饭前", "要帮你点外卖吗?"))
+ val n = plans.bubbleForItem("p1", nudges, NudgeBook.Level.NORMAL, emptySet())!!
+ assertEquals("2026-10-27#p1", n.planRef)
+ assertEquals("不用", n.dismiss)
+ assertNull(plans.bubbleForItem("p1", nudges, NudgeBook.Level.OFF, emptySet()))
+ assertEquals("skipped", plans.day("2026-10-27")!!.items.single().status)
+ assertNull(plans.bubbleForItem("nope", nudges, NudgeBook.Level.NORMAL, emptySet()))
+ }
+
+ @Test fun weeklyLookAtDirectionsIsAskedForThenGoesAway() {
+ plans.handle("note.directions", JSONObject().put("action", "add").put("title", "规律喝水").put("source", "他说的"), 8)
+ assertTrue(plans.indexForPrompt().contains("A week since"))
+ plans.handle("note.directions", JSONObject().put("action", "list"), 8)
+ assertFalse(plans.indexForPrompt().contains("A week since"))
+ now += Plans.WEEK_MS
+ assertTrue(plans.indexForPrompt().contains("A week since"))
+ }
+
+ @Test fun morningContextCarriesYesterdaysOutcomes() {
+ write(item("10:00", "该喝水啦"))
+ val todo = plans.reconcile().arm.single()
+ now = todo.at
+ plans.recordOutcome(plans.bubbleFor(todo, nudges, NudgeBook.Level.NORMAL, emptySet())!!, "button", null)
+ now = LocalDateTime.of(2026, 10, 28, 8, 0).atZone(zone).toInstant().toEpochMilli()
+ val c = plans.morningContext()
+ assertTrue(c.contains("Yesterday's plan"))
+ assertTrue(c.contains("\"该喝水啦\" → done"))
+ assertTrue(c.contains("Today's draft:\n(none)"))
+ }
+}
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 fe94e36..7a9ce13 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
@@ -437,6 +437,25 @@ object Assistant {
}
/** A turn is running, or its answer is being read out: what a tap on the ball should cut short. */
+ /**
+ * The user tapped a bubble's button (or the body of one with buttons): that is a turn, at the trust of
+ * the turn that wrote the bubble — a 「好」 under a bubble a notification's turn raised must not come
+ * back as the user's own request (the phone's `answerNudge`, and `Todo.untrusted` for the alarm clock).
+ */
+ fun answerNudge(n: net.kuafuai.andee.brain.Nudge, button: String?) {
+ val text = net.kuafuai.andee.brain.NudgeBook.answerText(n, button)
+ if (n.untrusted) {
+ if (brain?.isBusy() != true) busy(true)
+ ensure().wake(text, untrusted = true)
+ } else {
+ // A tap is the user asking, like [say]: it replaces whatever is running.
+ guest?.cancel()
+ if (brain?.isBusy() == true || net.kuafuai.andee.desktop.voice.MacVoice.isSpeaking()) interruptForNewRequest()
+ busy(true)
+ ensure().submit(text)
+ }
+ }
+
fun working(): Boolean = brain?.isBusy() == true || net.kuafuai.andee.desktop.voice.MacVoice.isSpeaking()
/**
@@ -488,6 +507,8 @@ object Assistant {
DesktopScheduler.onDue = { todo -> wakeFor(todo) }
Peers.tasks.brain = peerBrain
DesktopScheduler.catchUp()
+ DesktopScheduler.syncPlan()
+ PlanTicks.start()
}
/**
@@ -502,7 +523,13 @@ object Assistant {
* The wait is bounded, so a card nobody answers cannot hold an alarm back forever — it fires anyway
* after [WAKE_PATIENCE_MS], when the card has timed out on its own.
*/
- private fun wakeFor(todo: net.kuafuai.andee.config.Todo) = whenQuiet("wake-${todo.id}") {
+ private fun wakeFor(todo: net.kuafuai.andee.config.Todo) {
+ // A planned bubble: shown by the device, no model involved, nothing to wait for.
+ if (todo.nudge.isNotEmpty()) return Nudges.postPlanned(todo)
+ 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)
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
index 1e141d7..7ccfb0a 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
@@ -171,6 +171,7 @@ class BallRenderer(val width: Int, val height: Int) {
fun setWorking(w: Boolean) = post { renderer.working = w }
fun pulseTool() = post { renderer.pulseTool() }
fun signalOutcome(ok: Boolean) = post { renderer.signalOutcome(ok) }
+ fun greet() = post { renderer.greet() }
fun trigger(action: Action) = post { renderer.request(action) }
private fun post(f: () -> Unit) { commands.offer(f); java.util.concurrent.locks.LockSupport.unpark(thread) }
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 2e0fe61..00a065d 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
@@ -80,6 +80,8 @@ class DesktopBrainHost(
override fun gearIndex(): String = providers.filterIsInstance<net.kuafuai.andee.desktop.mac.MacGear>().firstOrNull()?.indexForPrompt().orEmpty()
override fun topicsIndex(): String = Scrollback.topicsIndex()
+ override fun planIndex(): String = DesktopNotebook.plans.indexForPrompt()
+
override fun friendsIndex(): String = Peers.tasks.indexForPrompt()
override fun foldTopic(title: String, summary: String, rows: List<ScrollRow>, text: String): FoldedTopic? {
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
index fb7f5ee..15ea05b 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
@@ -93,6 +93,9 @@ object MacBall {
/** A tool ran: a nod, then back to the working face on its own. */
fun onTool() { renderers.forEach { it.pulseTool() } }
+ /** A bubble it raised by itself just went up: wave once so the eye finds it. */
+ fun greet() { renderers.forEach { it.greet() } }
+
/**
* An answer came back. The opening face it was written with is held for
* when (if) it is spoken — the phone's fallback when the cue clock is
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 17404a1..c4d1124 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
@@ -93,6 +93,10 @@ fun main() {
)
BallCaptionWindow(ballWindow, suppressed = pending != null || ask != null)
PromptWindow(ballWindow, pending, ask)
+ // Bubbles stand beside the ball; with the chat window in front they are a scrollback row instead.
+ Nudges.ballUp = { ballWindow != null }
+ Nudges.chatInFront = { chat && chatWindow?.isActive == true }
+ BubbleWindow(ballWindow)
Window(
onCloseRequest = { chat = false },
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 099d23a..cb6fb4c 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NotebookTools.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NotebookTools.kt
@@ -21,6 +21,9 @@ object DesktopNotebook {
val book: NotebookBook by lazy {
NotebookBook(storeOverride ?: EncryptedFileStore(AppDirs.file("notebook.enc"), "notebook-key"))
}
+
+ /** Directions and day plans, in the same book. One instance: its lock serialises the tool and the settings page. */
+ val plans: net.kuafuai.andee.config.Plans by lazy { net.kuafuai.andee.config.Plans(book) }
}
/** Local-time formats the model writes todos in — the same list the phone accepts. */
@@ -74,6 +77,17 @@ object DesktopScheduler {
synchronized(armed) { armed.remove(id)?.cancel(false) }
}
+ /**
+ * Bring the plan's bubble timers in line with the plan ([net.kuafuai.andee.config.Plans.reconcile]). After
+ * every plan write — the model's or the user's in settings — and at launch.
+ */
+ fun syncPlan() {
+ val s = DesktopNotebook.plans.reconcile()
+ s.cancel.forEach(::cancel)
+ s.arm.forEach(::arm)
+ if (s.arm.isNotEmpty() || s.cancel.isNotEmpty()) Log.i(TAG, "plan: armed ${s.arm.size}, cancelled ${s.cancel.size}")
+ }
+
/** At launch: re-arm the future, fire what was missed while the app was closed. */
fun catchUp() {
val now = System.currentTimeMillis()
@@ -107,6 +121,12 @@ class NotebookTools(private val onSceneChanged: (String?) -> Unit) {
fun handles(method: String) = method.startsWith("note.") || method.startsWith("scene.")
fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any = when (method) {
+ // The plan (`Plans`): shared logic in core; here only the timers it asks for.
+ "note.directions", "note.day_plan" -> {
+ val r = DesktopNotebook.plans.handle(method, p, Nudges.level().perDay)
+ if (method == "note.day_plan") DesktopScheduler.syncPlan()
+ r
+ }
"note.remember" -> {
val (saved, overwrote) = book.remember(
name = req(p, "name", method),
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt
new file mode 100644
index 0000000..0e12ffc
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/NudgeBubble.kt
@@ -0,0 +1,333 @@
+package net.kuafuai.andee.desktop
+
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.layout.wrapContentSize
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.DpSize
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.window.ApplicationScope
+import androidx.compose.ui.window.Window
+import androidx.compose.ui.window.WindowPosition
+import androidx.compose.ui.window.rememberWindowState
+import kotlinx.coroutines.delay
+import net.kuafuai.andee.brain.Nudge
+import net.kuafuai.andee.brain.NudgeBook
+import net.kuafuai.andee.util.Log
+import java.util.concurrent.Executors
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+
+/** The bubble window's title; the native side finds the window by it. */
+const val BUBBLE_TITLE = "Andee Bubble"
+
+/**
+ * *When* a bubble goes up beside the ball, and what a tap on it does — the Mac's twin of the phone's
+ * `NudgeUi`. See `docs/design/proactive-nudge.zh-CN.md` §4; the budget is the shared [NudgeBook].
+ *
+ * A bubble is something that is fine to miss, so it waits for the user rather than the other way round:
+ * [gate] holds it while a card is up, a turn is running or being read out, a meeting is recording, it is
+ * the night, or nobody has touched the Mac for a while (away, or locked — this is the Mac's stand-in for
+ * the phone's screen-off check). A held bubble is retried every [RETRY_MS] and dropped silently once its
+ * TTL passes. One held at a time, newest wins.
+ *
+ * Everything here runs on one scheduler thread; the composable only reads [showing].
+ */
+object Nudges {
+
+ enum class Gate { SHOW, WAIT, LOG }
+
+ private const val RETRY_MS = 5_000L
+ 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)
+
+ /**
+ * The bubble budget, one per run (a restart starts the count again — see [NudgeBook]). Shared by the
+ * `nudge` tool and the plan's timed bubbles, so both draw on the user's one allowance.
+ */
+ val book = NudgeBook()
+
+ /** What is on screen. Read by [BubbleWindow]. */
+ var showing by mutableStateOf<Nudge?>(null)
+ private set
+ /** True for the fade before [showing] is cleared. */
+ var fading by mutableStateOf(false)
+ private set
+
+ private val exec = Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "nudges").apply { isDaemon = true } }
+ private var held: Slot? = null
+ private var current: Slot? = null
+ private var retry: ScheduledFuture<*>? = null
+ private var stay: ScheduledFuture<*>? = null
+ private var watch: ScheduledFuture<*>? = null
+
+ /** Set by Main: whether the chat window is in front of the user (then the bubble is a scrollback row). */
+ @Volatile var chatInFront: () -> Boolean = { false }
+ /** Set by Main: whether the ball's window exists to stand a bubble beside. */
+ @Volatile var ballUp: () -> Boolean = { false }
+
+ fun post(n: Nudge) = exec.execute {
+ held?.let { Log.i("Nudge", "replaced a held bubble: ${it.n.text}") }
+ held = Slot(n)
+ pump()
+ }
+
+ private fun pump() {
+ retry?.cancel(false)
+ val slot = held ?: return
+ if (System.currentTimeMillis() >= slot.n.expiresAt) {
+ Log.i("Nudge", "expired before it could be shown: ${slot.n.text}")
+ held = null
+ outcome(slot.n, "expired", null)
+ return
+ }
+ if (current != null) return
+ when (gate()) {
+ Gate.WAIT -> retry = exec.schedule(::pump, RETRY_MS, TimeUnit.MILLISECONDS)
+ Gate.LOG -> { held = null; record(slot); outcome(slot.n, "logged", null) }
+ Gate.SHOW -> {
+ held = null
+ current = slot
+ record(slot)
+ fading = false
+ showing = slot.n
+ MacBall.greet()
+ val ms = if (slot.n.buttons.isEmpty()) STAY_TEXT_MS else STAY_BUTTONS_MS
+ stay = exec.schedule({ fadeThenEnd("timeout") }, ms, TimeUnit.MILLISECONDS)
+ // A card arriving takes the spot beside the ball; the bubble steps back and is held again.
+ watch = exec.scheduleWithFixedDelay({
+ if (current === slot && (AskGate.current != null || ApprovalGate.current != null)) end(slot, "superseded", null)
+ }, 300, 300, TimeUnit.MILLISECONDS)
+ }
+ }
+ }
+
+ /**
+ * Whether a bubble may go up right now. Every answer but SHOW is a reason to hold it, never to drop it.
+ * Full-screen video and games are not detected yet, as on the phone.
+ */
+ private fun gate(): Gate {
+ 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
+ }
+
+ /** The bubble's words, once, when they first reach the user — on screen or as a row. */
+ private fun record(slot: Slot) {
+ if (slot.recorded) return
+ slot.recorded = true
+ Scrollback.add(Scrollback.Role.ASSISTANT, slot.n.text)
+ }
+
+ // ---- what the user did (called from the UI thread) -----------------------
+
+ 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) } }
+
+ private fun fadeThenEnd(how: String) {
+ val slot = current ?: return
+ fading = true
+ exec.schedule({ if (current === slot) end(slot, how, null) }, FADE_MS, TimeUnit.MILLISECONDS)
+ }
+
+ private fun end(slot: Slot, how: String, button: String?) {
+ if (current !== slot) return
+ current = null
+ stay?.cancel(false)
+ watch?.cancel(false)
+ showing = null
+ fading = false
+ val n = slot.n
+ Log.i("Nudge", "$how${button?.let { " [$it]" } ?: ""}: ${n.text}")
+ outcome(n, how, button)
+ when (how) {
+ "button" -> if (button != null && button != n.dismiss) {
+ Scrollback.add(Scrollback.Role.USER, button)
+ Assistant.answerNudge(n, button)
+ }
+ // A bubble that only says something: a tap is "seen", not "let's talk".
+ "body" -> if (n.buttons.isNotEmpty()) Assistant.answerNudge(n, null)
+ "mute" -> mute(n)
+ "superseded" -> if (held == null) held = slot
+ }
+ // Displaced: wait a beat rather than spin against the card that took the spot.
+ retry = exec.schedule(::pump, if (how == "superseded") RETRY_MS else 0L, TimeUnit.MILLISECONDS)
+ }
+
+ /** A planned bubble's ending goes back onto its plan item, for tonight's review and the settings page. */
+ private fun outcome(n: Nudge, how: String, button: String?) =
+ runCatching { DesktopNotebook.plans.recordOutcome(n, how, button) }
+ .onFailure { Log.w("Nudge", "could not record the outcome: ${it.message}") }
+
+ /** A planned bubble came due: the plan decides whether it is still worth showing and allowed. */
+ fun postPlanned(todo: net.kuafuai.andee.config.Todo) {
+ DesktopNotebook.plans.bubbleFor(todo, book, level(), muted())?.let(::post)
+ }
+
+ // ---- the user's settings -------------------------------------------------
+
+ fun level(): NudgeBook.Level = NudgeBook.Level.of(Settings.get("nudge").ifEmpty { null })
+
+ fun muted(): Set<String> = Settings.get("nudge_muted").split(',').map { it.trim() }.filter { it.isNotEmpty() }.toSet()
+
+ fun unmuteAll() = Settings.save(mapOf("nudge_muted" to ""))
+
+ private fun mute(n: Nudge) {
+ Settings.save(mapOf("nudge_muted" to (muted() + n.kind).joinToString(",")))
+ // A setting changed by a gesture with no confirmation; the user is owed the news and the way back.
+ Scrollback.add(Scrollback.Role.ASSISTANT, 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):
+ * 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.
+ */
+object PlanTicks {
+ private const val TICK_MS = 5 * 60_000L
+ private val exec = Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "plan-mind").apply { isDaemon = true } }
+
+ fun start() {
+ exec.scheduleWithFixedDelay({ runCatching(::tick).onFailure { Log.w("Plan", "tick failed: ${it.message}") } }, 60_000L, TICK_MS, TimeUnit.MILLISECONDS)
+ }
+
+ private fun tick() {
+ val cfg = Assistant.config()
+ if (cfg.apiKey.isEmpty()) return
+ if ((Nudges.idleSeconds() ?: 0L) >= 300L) return
+ 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()
+ if (mind.morning(Strings.lang(), level.perDay)) DesktopScheduler.syncPlan()
+ val free = !Assistant.working() && !Meeting.isActive() && AskGate.current == null && ApprovalGate.current == null
+ if (free && level != NudgeBook.Level.OFF) {
+ mind.muse(Strings.lang())?.let { id -> plans.bubbleForItem(id, Nudges.book, level, Nudges.muted())?.let(Nudges::post) }
+ }
+ }
+}
+
+/**
+ * The bubble beside the ball: a small card, its own window like the prompt card and the caption (the
+ * ball's window is exactly the ball's size). Never takes focus — a bubble that pulled the keyboard away
+ * from whatever the user was typing in would be the opposite of quiet. Sized to its content, because a
+ * transparent window larger than the card would swallow clicks around it.
+ */
+@Composable
+fun ApplicationScope.BubbleWindow(ball: java.awt.Window?) {
+ val n = Nudges.showing
+ val up = ball != null && n != null
+ // Keep the last words while it fades.
+ var shown by remember { mutableStateOf<Nudge?>(null) }
+ if (n != null) shown = n
+ val alpha by animateFloatAsState(if (n != null && !Nudges.fading) 1f else 0f, tween(if (Nudges.fading) 260 else 220))
+ val density = LocalDensity.current
+ var size by remember { mutableStateOf(DpSize(240.dp, 80.dp)) }
+ val state = rememberWindowState(size = size, position = WindowPosition(0.dp, 0.dp))
+ state.size = size
+ Window(
+ onCloseRequest = {},
+ state = state,
+ title = BUBBLE_TITLE,
+ visible = up,
+ undecorated = true,
+ transparent = true,
+ resizable = false,
+ alwaysOnTop = true,
+ focusable = false,
+ ) {
+ val w = window
+ LaunchedEffect(up) {
+ if (!up) return@LaunchedEffect
+ var floated = false
+ while (true) {
+ ball?.let { place(w, it, gap = 6) }
+ if (!floated && w.isShowing) floated = net.kuafuai.andee.desktop.mac.Bridge.floatWindow(BUBBLE_TITLE)
+ delay(80)
+ }
+ }
+ val b = shown ?: return@Window
+ Box(
+ Modifier.wrapContentSize(align = Alignment.TopStart, unbounded = true)
+ .onSizeChanged { with(density) { size = DpSize(it.width.toDp(), it.height.toDp()) } },
+ ) {
+ BubbleCard(b, Modifier.padding(4.dp).alpha(alpha))
+ }
+ }
+}
+
+/** The card itself, apart from its window so `uishot bubble` can draw it. */
+@Composable
+fun BubbleCard(b: Nudge, modifier: Modifier = Modifier) {
+ Column(
+ modifier.widthIn(min = 120.dp, max = 300.dp)
+ .background(Palette.cardSolid, RoundedCornerShape(16.dp))
+ .border(1.dp, Palette.hairline, RoundedCornerShape(16.dp))
+ .pointerInput(b) { detectTapGestures(onTap = { Nudges.tapBody() }, onLongPress = { Nudges.longPress() }) }
+ .padding(horizontal = 14.dp, vertical = 10.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ Text(b.text, color = Palette.text, fontSize = 14.sp, textAlign = TextAlign.Center, maxLines = 3)
+ if (b.buttons.isNotEmpty()) {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ b.buttons.forEachIndexed { i, label ->
+ val primary = i == 0
+ Text(
+ label, color = if (primary) Color.White else Palette.label, fontSize = 13.sp,
+ modifier = Modifier
+ .background(if (primary) Palette.tint else Palette.panel, RoundedCornerShape(12.dp))
+ .border(1.dp, if (primary) Color.Transparent else Palette.hairline, RoundedCornerShape(12.dp))
+ .clickable { Nudges.tapButton(label) }
+ .padding(horizontal = 14.dp, vertical = 5.dp),
+ )
+ }
+ }
+ }
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
index a3ea8fc..751a834 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
@@ -37,6 +37,7 @@ object Settings {
"shell_mode", "shell_workdirs", "shell_critical_confirm", "mute",
"google_api_key", "google_project", "google_location", "google_asr_model", "google_tts_model", "google_base_url",
"google_language", "tts_sample_rate", "grounding", "show_hub", "hub_url", "device_name", "theme", "peers",
+ "nudge", "nudge_muted",
)
/**
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
index 3a6538a..2d7c056 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
@@ -208,6 +208,25 @@ fun SettingsScreen(
}
}
+ // ---- 主动招呼: how often a bubble may go up beside the ball. 关 leftmost, as everywhere ----
+ Section(st("settings_section_nudge")) {
+ SegmentedPicker(
+ listOf("off" to st("common_off"), "few" to st("settings_nudge_few"), "normal" to st("settings_nudge_normal")),
+ Nudges.level().key.let { saved -> v["nudge"].orEmpty().ifEmpty { saved } },
+ ) { v["nudge"] = it }
+ Note(st("settings_nudge_note"))
+ // The way back from a long-press, which mutes with no confirmation. Written at once.
+ var muted by remember { mutableStateOf(Nudges.muted()) }
+ if (muted.isNotEmpty()) {
+ Note(st("settings_nudge_muted", muted.sorted().joinToString(if (zh) "、" else ", ")))
+ Row(Modifier.padding(top = 8.dp)) { Pill(st("settings_nudge_unmute")) {
+ // `v` holds the list as it was when the card opened, and Save writes all of `v` back.
+ Nudges.unmuteAll(); v["nudge_muted"] = ""; muted = emptySet()
+ } }
+ }
+ }
+ // ---- 它的打算: the plan, readable and trimmable by the person it is about ----
+ Section(st("settings_section_plan")) { PlanSection(zh) }
// ---- 保险箱: a summary here, and the door to the card ----
Section(st("settings_section_vault")) {
val vaultN = remember { runCatching { net.kuafuai.andee.desktop.mac.MacVault.entries().size }.getOrDefault(0) }
@@ -303,6 +322,72 @@ fun SettingsScreen(
}
}
+/**
+ * 它的打算 (`Plans`, design doc §5.5). Removing and pausing are done by the device at once, not asked of the
+ * model, and the timers follow in the same click. Anything subtler goes through the box at the bottom as an
+ * ordinary message, and the model changes the plan itself.
+ */
+@Composable
+private fun PlanSection(zh: Boolean) {
+ var rev by remember { mutableStateOf(0) }
+ val plans = DesktopNotebook.plans
+ val day = remember(rev) { plans.day(plans.today()) }
+ val dirs = remember(rev) { plans.directions().filter { it.status != "dropped" && it.status != "done" } }
+ fun kind(k: String) = st("settings_plan_kind_" + if (k in setOf("ask", "prepare", "follow_up")) k else "remind")
+ fun status(s: String) = st("settings_plan_st_" + if (s in setOf("done", "declined", "ignored", "missed", "skipped", "moved", "dropped")) s else "planned")
+
+ Text(st("settings_plan_today"), color = Palette.secondary, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))
+ if (day == null) {
+ Note(st("settings_plan_none_today"))
+ } else {
+ Text(day.intent, color = Palette.text, fontSize = 14.sp, modifier = Modifier.padding(top = 6.dp))
+ for (it in day.items.sortedBy { i -> i.time.ifEmpty { "99" } }) {
+ val live = it.status == "planned"
+ Row(Modifier.fillMaxWidth().padding(top = 6.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ "${it.time.ifEmpty { it.slot }.ifEmpty { "·" }} ${kind(it.kind)} ${it.what}",
+ color = if (live) Palette.label else Palette.secondary, fontSize = 13.sp,
+ modifier = Modifier.weight(1f),
+ )
+ Text(status(it.status), color = Palette.muted, fontSize = 12.sp, modifier = Modifier.padding(horizontal = 8.dp))
+ if (live) {
+ Text("✕", color = Palette.accent, fontSize = 13.sp, modifier = Modifier.clickable {
+ plans.dropItemByUser(day.date, it.id)
+ DesktopScheduler.syncPlan()
+ rev++
+ }.padding(4.dp))
+ }
+ }
+ }
+ if (day.quiet.isNotEmpty()) Note(st("settings_plan_quiet", day.quiet.joinToString(if (zh) ";" else "; ")))
+ }
+ Text(st("settings_plan_directions"), color = Palette.secondary, fontSize = 12.sp, modifier = Modifier.padding(top = 14.dp))
+ if (dirs.isEmpty()) Note(st("settings_plan_none_directions"))
+ for (d in dirs) {
+ val paused = d.status == "paused"
+ Row(Modifier.fillMaxWidth().padding(top = 6.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ d.title + if (d.howIHelp.isNotEmpty()) " — ${d.howIHelp}" else "",
+ color = if (paused) Palette.secondary else Palette.label, fontSize = 13.sp, modifier = Modifier.weight(1f),
+ )
+ Text(st(if (paused) "settings_plan_resume" else "settings_plan_pause"), color = Palette.accent, fontSize = 12.sp,
+ modifier = Modifier.clickable { plans.setDirectionByUser(d.id, if (paused) "active" else "paused"); rev++ }.padding(6.dp))
+ Text(st("settings_plan_remove"), color = Palette.accent, fontSize = 12.sp,
+ modifier = Modifier.clickable { plans.setDirectionByUser(d.id, "dropped"); rev++ }.padding(6.dp))
+ }
+ }
+ var line by remember { mutableStateOf("") }
+ var sent by remember { mutableStateOf(false) }
+ GlassField(st("settings_plan_tell"), line, { line = it; sent = false }, hint = st("settings_plan_tell_hint"))
+ Row(Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
+ Pill(st("settings_plan_send")) {
+ val text = line.trim()
+ if (text.isNotEmpty()) { Assistant.say(text); line = ""; sent = true }
+ }
+ if (sent) Text(st("settings_plan_sent"), color = Palette.secondary, fontSize = 12.sp, modifier = Modifier.padding(start = 10.dp))
+ }
+}
+
@Composable
private fun Note(text: String) {
Text(text, color = Palette.secondary, fontSize = 12.sp, modifier = Modifier.padding(top = 6.dp))
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UiShot.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UiShot.kt
index 804b579..7e6695b 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UiShot.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UiShot.kt
@@ -21,7 +21,7 @@ import kotlin.system.exitProcess
* directory seeded with a short conversation and two topics, so nothing of the user's
* is read or shown.
*
- * screen: chat | settings | notebook | scenes | vault | selfcheck | expressions | artifacts | topic:1
+ * screen: chat | settings | notebook | scenes | vault | selfcheck | expressions | artifacts | topic:1 | ask | bubble
*/
@OptIn(ExperimentalComposeUiApi::class)
fun main(args: Array<String>) {
@@ -52,6 +52,16 @@ fun main(args: Array<String>) {
val doc = File(System.getProperty("andee.home"), "季度复盘-final.pdf").also { it.writeText("%PDF") }
ChatPreview.attachments = listOfNotNull(Attachments.fromBytes("a.png", png), Attachments.fromBytes("b.png", png), Attachments.fromFile(doc))
}
+ // `settings … plan`: the settings page with an invented plan, in a throwaway notebook. Nothing real.
+ if (args.getOrElse(4) { "" } == "plan") {
+ DesktopNotebook.storeOverride = object : net.kuafuai.andee.config.NotebookStore {
+ var s: String? = null
+ override fun read() = s
+ override fun write(plain: String): Boolean { s = plain; return true }
+ override fun wipe() { s = null }
+ }
+ seedPlan()
+ }
if (screen == "gear") {
DesktopNotebook.storeOverride = object : net.kuafuai.andee.config.NotebookStore {
var s: String? = null
@@ -83,7 +93,11 @@ fun main(args: Array<String>) {
System.currentTimeMillis() + 20_000,
) else null
val scene = ImageComposeScene(width = w * 2, height = h * 2, density = density) {
- if (askCard != null) AskShot(askCard) else AppRoot(nav)
+ when {
+ askCard != null -> AskShot(askCard)
+ screen == "bubble" -> BubbleShot()
+ else -> AppRoot(nav)
+ }
}
// Let the backdrop (decoded off the main thread) and the layout settle.
repeat(12) { scene.render(it * 50_000_000L); Thread.sleep(60) }
@@ -94,6 +108,19 @@ fun main(args: Array<String>) {
exitProcess(0)
}
+/** The two shapes of bubble — words only, and words with buttons — on a plain ground. */
+@Composable
+private fun BubbleShot() {
+ val far = Long.MAX_VALUE
+ androidx.compose.foundation.layout.Column(
+ Modifier.background(Color(0xFFB9C0C8)).padding(24.dp),
+ verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(16.dp),
+ ) {
+ BubbleCard(net.kuafuai.andee.brain.Nudge("该喝水啦 💧", emptyList(), null, "water", far, false))
+ BubbleCard(net.kuafuai.andee.brain.Nudge("12点了,要帮你点外卖吗?", listOf("好", "不用"), "不用", "meal", far, false))
+ }
+}
+
/** One question card on a plain ground, so the card's edges and its corner button are unambiguous. */
@Composable
private fun AskShot(p: AskGate.Pending) {
@@ -118,6 +145,23 @@ private fun seed() {
Scrollback.add(Scrollback.Role.ASSISTANT, "我先打开浏览器搜一下,稍等。")
}
+/** An invented plan, so 它的打算 has rows to show. */
+private fun seedPlan() {
+ val p = DesktopNotebook.plans
+ p.handle("note.directions", org.json.JSONObject().put("action", "add").put("title", "Andee 发布")
+ .put("how_i_help", "每天下午问一次进度").put("source", "10-26: 这周要把 0.6.2 发出去"), 8)
+ p.handle("note.directions", org.json.JSONObject().put("action", "add").put("title", "规律喝水")
+ .put("how_i_help", "上午下午各提醒一次").put("source", "10-25: 我老忘了喝水"), 8)
+ p.handle("note.day_plan", org.json.JSONObject().put("action", "write").put("date", "today")
+ .put("intent", "今天我想帮他把发布收个尾,别的事少打扰。")
+ .put("items", org.json.JSONArray()
+ .put(org.json.JSONObject().put("time", "23:58").put("kind", "remind").put("what", "该喝水啦 💧").put("because", "规律喝水"))
+ .put(org.json.JSONObject().put("time", "23:59").put("kind", "ask").put("what", "发布的视频剪完了吗?")
+ .put("buttons", org.json.JSONArray().put("剪完了").put("还没")).put("dismiss", "还没").put("because", "Andee 发布"))
+ .put(org.json.JSONObject().put("slot", "他第一次找我时").put("kind", "prepare").put("what", "整理一份发布前检查清单").put("because", "Andee 发布")))
+ .put("quiet", org.json.JSONArray().put("上午他在开会,12 点前不出气泡")), 8)
+}
+
/** A few invented apps, in the throwaway home, so the gear card has something to show. Nothing real. */
private fun seedGear() {
val g = Assistant.gear.gear
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt
index a7ec72d..f449443 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/UserPrompts.kt
@@ -44,6 +44,8 @@ class UiTools : DesktopBrainHost.ToolProvider {
override fun handles(method: String) = method.startsWith("ui.")
+
+
override fun turnStarted(kind: String) = Pages.beginTurn()
override fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any? = when (method) {
@@ -72,6 +74,21 @@ class UiTools : DesktopBrainHost.ToolProvider {
.put("answered", r.button != null || r.heard != null)
.apply { r.heard?.let { put("heard", it) } }
}
+ "ui.nudge" -> {
+ // Malformed → throws for the model to fix; over budget → a normal result that says why.
+ val n = Nudges.book.parse(p, untrusted)
+ val refusal = Nudges.book.admit(n, Nudges.level(), Nudges.muted())
+ if (refusal != null) {
+ JSONObject().put("queued", false).put("reason", refusal)
+ } else {
+ Nudges.post(n)
+ JSONObject().put("queued", true).put(
+ "note",
+ "Queued. It goes up when the user is free and is dropped after its ttl. You will hear back only " +
+ "if they tap a button that is not `dismiss` — do not wait for it, and do not also say it out loud.",
+ )
+ }
+ }
"ui.alert" -> {
val text = p.optString("text").trim().ifEmpty { throw IllegalArgumentException("ui.alert requires text") }
val timeoutMs = p.optLong("timeout_ms", 30_000L).coerceIn(5_000, 120_000)
diff --git a/desktop/src/main/resources/strings_en.properties b/desktop/src/main/resources/strings_en.properties
index 01d5759..0a12167 100644
--- a/desktop/src/main/resources/strings_en.properties
+++ b/desktop/src/main/resources/strings_en.properties
@@ -181,6 +181,38 @@ s_settings_section_notify=Notifications
s_settings_notify_chat=Chat apps
s_settings_notify_all=Everything
s_settings_notify_note=When a message arrives it decides for itself whether it is worth your attention: lets the noise go, says the useful part out loud, handles what needs handling. "Chat apps" means the ones with a person on the other end — WeChat, QQ, DingTalk, Lark, SMS. "Everything" watches the rest too, minus progress bars and permanent notifications. It only puts a card up when it cannot decide. Off means nothing interrupts you — the messages are all still there, and you can ask about them whenever.
+s_settings_section_nudge=Speaking first
+s_settings_nudge_few=Rarely
+s_settings_nudge_normal=Normal
+s_settings_nudge_note=Now and then a small bubble appears beside the ball — "Time for some water", "Want me to order lunch?". It makes no sound and fades by itself if you ignore it, and it never shows while you are busy, while it is talking, while you are away from the Mac or at night (22:30–8:00). With the chat window in front it becomes a line in the chat instead. "Rarely" is at most 1 an hour and 4 a day, "Normal" 2 an hour and 8 a day. Long-press a bubble and that kind never comes back.
+s_settings_nudge_muted=Turned off by long-press: %1$s
+s_settings_nudge_unmute=Bring them all back
+s_nudge_muted_row=OK, nothing like "%1$s" again. To bring it back: Settings → Speaking first.
+s_settings_section_plan=Its plans
+s_settings_plan_today=Today
+s_settings_plan_none_today=No plan for today yet. It writes one when it looks back over a quiet stretch.
+s_settings_plan_quiet=Not bothering you today about: %1$s
+s_settings_plan_directions=What it is helping you with
+s_settings_plan_none_directions=Nothing yet. It only writes these from things you have said.
+s_settings_plan_pause=Pause
+s_settings_plan_resume=Resume
+s_settings_plan_remove=Remove
+s_settings_plan_tell=Tell it something
+s_settings_plan_tell_hint=e.g. no water reminders today
+s_settings_plan_send=Send
+s_settings_plan_sent=Passed on — it will adjust its plan.
+s_settings_plan_kind_remind=remind
+s_settings_plan_kind_ask=ask
+s_settings_plan_kind_prepare=prepare
+s_settings_plan_kind_follow_up=follow up
+s_settings_plan_st_planned=to do
+s_settings_plan_st_done=done
+s_settings_plan_st_declined=declined
+s_settings_plan_st_ignored=ignored
+s_settings_plan_st_missed=missed
+s_settings_plan_st_skipped=skipped
+s_settings_plan_st_moved=moved
+s_settings_plan_st_dropped=removed
s_settings_section_typing=Typing
s_settings_typing_no_ime=ADBKeyboard is the only keyboard on this device and it has no keyboard UI, so nothing can be typed right now. Enable one in system settings and it will show up here.
s_settings_typing_current=Your keyboard
diff --git a/desktop/src/main/resources/strings_zh.properties b/desktop/src/main/resources/strings_zh.properties
index 34d1a44..41b14a4 100644
--- a/desktop/src/main/resources/strings_zh.properties
+++ b/desktop/src/main/resources/strings_zh.properties
@@ -181,6 +181,38 @@ s_settings_section_notify=消息提醒
s_settings_notify_chat=聊天类
s_settings_notify_all=全部
s_settings_notify_note=来消息的时候,它先自己看一眼值不值当:没事的就放过,要紧的说一声,该办的直接去办。「聊天类」是微信、QQ、钉钉、飞书、短信这些有人在那头的;「全部」连其它 App 也一起看(进度条、常驻通知除外)。拿不准的才弹牌子问你。关掉就谁也不打扰你 —— 消息都还在,想知道的时候问它一声就行。
+s_settings_section_nudge=主动招呼
+s_settings_nudge_few=少
+s_settings_nudge_normal=正常
+s_settings_nudge_note=它有时会在球旁边冒一个小气泡,比如「该喝水啦」「要帮你点外卖吗?」。不出声,不理它几秒后就自己消失;你在忙、它在说话、你离开电脑或者夜里(22:30–8:00)都不会出。聊天窗口在前面时,改成在对话里写一行。「少」是每小时最多 1 个、每天 4 个,「正常」是每小时 2 个、每天 8 个。长按某个气泡,这一类以后就不再提。
+s_settings_nudge_muted=长按关掉的:%1$s
+s_settings_nudge_unmute=全部恢复
+s_nudge_muted_row=好,像「%1$s」这样的以后不提了。想恢复,到 设置 → 主动招呼。
+s_settings_section_plan=它的打算
+s_settings_plan_today=今天
+s_settings_plan_none_today=今天还没有计划。它会在你们安静一阵后的复盘里写出来。
+s_settings_plan_quiet=今天不打扰:%1$s
+s_settings_plan_directions=长期在帮你做的事
+s_settings_plan_none_directions=还没有。它只会根据你说过的话来写。
+s_settings_plan_pause=暂停
+s_settings_plan_resume=恢复
+s_settings_plan_remove=移除
+s_settings_plan_tell=告诉它一句
+s_settings_plan_tell_hint=比如:今天别提喝水了
+s_settings_plan_send=发送
+s_settings_plan_sent=已转告,它会自己调整计划。
+s_settings_plan_kind_remind=提醒
+s_settings_plan_kind_ask=问一句
+s_settings_plan_kind_prepare=准备
+s_settings_plan_kind_follow_up=跟进
+s_settings_plan_st_planned=待做
+s_settings_plan_st_done=已做
+s_settings_plan_st_declined=不用了
+s_settings_plan_st_ignored=没理
+s_settings_plan_st_missed=错过
+s_settings_plan_st_skipped=跳过
+s_settings_plan_st_moved=推迟
+s_settings_plan_st_dropped=已移除
s_settings_section_typing=打字
s_settings_typing_no_ime=这台设备上只有 ADBKeyboard(它没有键盘界面),所以现在打不了字。去系统设置里启用一个输入法,这里就会出现。
s_settings_typing_current=你现在的输入法
diff --git a/docs/design/proactive-nudge.zh-CN.md b/docs/design/proactive-nudge.zh-CN.md
new file mode 100644
index 0000000..a666b63
--- /dev/null
+++ b/docs/design/proactive-nudge.zh-CN.md
@@ -0,0 +1,449 @@
+# 设计草案:主动 —— 从"被叫醒"到"有打算"
+
+状态:第一部分(气泡)已在 Android 和 Mac 实现,Android 真机验证过(见 §11);第 2、3、4、6 期已在两端实现(见 §12、§13);第 5 期(准备回合)**不做** · 适用:Android 与 Mac 两个身体,仅本机大脑 · 2026-10-27
+
+已定(2026-10-27):否定按钮不开回合;新设备默认档位「少」;计划在设置里给用户看到,那一节叫「它的打算」;用户在设置里只能删除和暂停,其他通过"告诉它一句"交给模型;手机和电脑各有一份计划;第 5 期"你不在时替你准备"不做(§6.3、§6.4 保留为记录)。
+
+## 1. 要解决什么
+
+现在的 Andee 更像一件工具:几乎每件事都由人发起。一个真正的个人助理会自己记挂事情、自己想起来、自己先把事情准备好,在合适的时候轻轻提一句。
+
+第一部分上线后用户的反馈是:**"没感受到主动",而且即使让它主动,没有总体思路也会零散、随机,没有灵魂。** 所以主动不能只是"偶尔想一下有没有话说",它要有自己的打算:一个长期方向、一份每日计划,主动的每一次都能说出"为什么是现在"。
+
+这份草案分三部分:
+
+- **第一部分:小气泡(`nudge`)**——已实现。最弱的一种开口方式:不出声、不阻塞、不理它就自己消失。它是后面一切主动的出口。
+- **第二部分:计划**。长期方向(这段时间我在帮他做成什么)和今日计划(今天我打算怎么过),**在设置里对用户可见、可改**。
+- **第三部分:执行与回顾**。计划里到点的条目变成气泡;"念头"对照计划判断现在该不该做;不在时先替他准备;晚上对照计划和实际,修正明天和长期方向。
+
+不在范围内:hub 大脑(它在别处,它的主动由它自己负责);主动截屏、主动看摄像头(隐私代价最大,一律不做,见 §9)。
+
+## 2. 现状:已有的主动,都是条件反射
+
+| 机制 | 由什么触发 | 能做什么 | 代码位置 |
+|---|---|---|---|
+| `todo` → `WAKE` 回合 | 过去的自己定的闹钟 | 到点跑一整轮 agent | `BodyCoreService.wakeForTodo`,`LocalBrain.TurnKind.WAKE` |
+| 夜间复盘 `SWEEP` / `HARVEST` | 用户安静了一阵 | 静默,只有 `note.*` | `LocalBrain.REVIEW_RULES` |
+| 通知分诊 act / tell / ignore | 外部应用发来通知 | 判断要不要管 | `brain/NotificationTriage.kt` |
+| 提议情景 | 同类会话反复出现 | 记下"下次提议" | `REVIEW_RULES` 第 6 条 |
+
+`REVIEW_RULES` 第 5 条已经在问"你接下来想做什么",可答案只能写成一条 `remember`,第二天没有任何东西会去读它、执行它。
+
+缺的是:
+
+1. **没有自己的议程。** 小本本里记的是关于用户的事实、做事的路径、承诺过的待办;没有地方记"我在意什么、正推进到哪、怎样算完"。待办是承诺,不是目标,而且必须事先知道时间。
+2. **想和做断开。** 复盘是它唯一独处的时间,但想到什么都只能写下来。
+3. **没有自发的念头。** 唯一的时钟是闹钟。
+4. **开口只有一种强度。** 要么不说,要么用卡片 / 语音把人拽进一场对话(见 §4.2)。
+5. **没有总体思路。** 就算补上前四条,每次主动也只是临场判断,彼此之间没有关系,用户感受到的是零散和随机。
+
+## 3. 原则
+
+1. **主动的代价不对称。** 少主动一次,用户只是多问一句;错误的打扰多了,用户会把球静音,以后连对的主动也听不到。这和 `NotificationTriage` 偏向沉默的理由完全一样。所以**默认是不说**,说要有理由,还要有预算。
+2. **主动分三层,门槛逐层升高:**
+ - **想**:不出声,只更新自己的计划。可以频繁。
+ - **做**:后台准备,不打扰,不做不可逆的事(查资料、比价、做好一页放着)。
+ - **说**:打扰用户。优先用最弱的方式:气泡,而不是语音。
+3. **边界写进机制,不只写进 prompt。** 能不能动保险箱、能不能发送 / 支付,都由 dispatcher 和 `TurnGuards` 决定,和现有的 `untrusted` 守卫同一个理由:模型被说服时,这一半照样成立。
+4. **主动必须是真的。** 它说"我昨晚帮你看了",就必须真的有一次回合做过这件事。它不能为了显得有温度而编造"我一直惦记着你"。这和 `stopped_by`、`reviveNote` 一样:讲给用户的话必须属实。
+5. **省钱也是设计的一部分。** 一整轮 agent 光 prompt 就约 22k token。凡是能不经过模型的路径(比如一句"该喝水啦"),都不该经过模型。
+
+---
+
+## 4. 第一部分:小气泡(`nudge`)
+
+### 4.1 三种形态
+
+```
+ ╭────────────╮ ╭──────────────────────╮
+ │ 该喝水啦 💧 │ │ 12点了,要帮你点外卖吗? │
+ ╰─────┬──────╯ │ [好] [不用] │
+ ● ╰──────────┬───────────╯
+ ●
+ ① 只说一句 ② 确认 / 选择(≤ 3 个按钮)
+```
+
+1. **只说一句**:没有按钮。点一下或者不理它,它都会消失,不会进入任何回合。
+2. **确认 / 选择**:最多 3 个短按钮。点了按钮,就开始一轮回合(§4.5)。点"不用"这一类否定按钮,只记录结果,**不开回合**,因为否定不需要模型回应,开一轮只是白花钱。哪个按钮算否定,由发气泡的一方用 `dismiss` 标出来,不靠设备猜字面意思。
+3. **点气泡正文**(不是按钮):开始一次正常对话,相当于用户说"嗯?你说"。
+
+### 4.2 它和现有卡片(`CardUi`)的区别
+
+`CardUi` 已经是挂在球上的看板(`FloatingWindowUi.showSignboard`),`ask_user`、`alert_user` 和通知看板都用它。它是强打扰,小气泡几乎处处相反:
+
+| | 卡片(现有) | 小气泡(新增) |
+|---|---|---|
+| 声音 | 读出来 | **不出声** |
+| 麦克风 | 读完打开 | 不开 |
+| 球 | holding 脸,停掉闲置小动作 | 做一个手势就收(Andee 用 `WAVE`,其他形象用 `CURIOUS`) |
+| 大脑 | 阻塞,等回答或超时 | 发出就返回 |
+| 优先级 | 新卡片顶掉旧卡片 | **永远让位**(§4.3),也从不顶掉卡片 |
+| 结束 | 超时关闭,算"没回答" | 淡出,算"没理" |
+| 尺寸 | 最宽 560 dp | 窄,一到两行字 |
+
+### 4.3 让位规则:什么时候不出
+
+满足任何一条,气泡就**先不出**,等条件解除且 TTL 还没过期时再出:
+
+- 有卡片在等用户(`CardUi.isAsking()`);
+- 正在说话、正在听(`audio.isStreamPlaying()`、`asr.isActive()`),也就是 `waitForQuiet` 现在检查的三件事;
+- 正在执行任务(`dispatcher.isTaskActive()`),这时候 Andee 在替用户干活,不要分心;
+- 正在开会录音(`meeting.isActive()`)或通话中;
+- 熄屏或锁屏:先暂存,解锁后再看 TTL;
+- 前台是全屏视频或游戏:第一版用沉浸模式(系统栏被隐藏)来判断,不维护应用名单;
+- 卡片处于展开状态:**不出气泡,改成在对话记录里写一行**,因为用户正看着对话记录,气泡挂在全屏卡片上反而奇怪;
+- 用户开了"勿扰"(系统勿扰模式,或者 Andee 自己的设置,见 §4.7)。
+
+暂存的气泡同一时间**只留一个**,新来的替换旧的。排成一串的气泡,就是推送轰炸换了个样子,这和 `CardUi` "一次一张"的理由相同。
+
+### 4.4 生命周期
+
+- **TTL(保质期)**:每个气泡都有,默认 30 分钟,最长 12 小时。下午三点的"该喝水啦",到六点解锁时再弹就是噪音。过期就作废,作废也要记结果(`expired`)。
+- **停留时长**:出现后挂 12 秒(只说一句的)或 30 秒(带按钮的),然后淡出,结果记为 `ignored`。用户的手指一碰到球,就重新计时。
+- **淡出不是关闭**:淡出之后,在对话记录里留一行灰色小字,用户回头还能看到"它刚才说过什么",并且仍然可以点那一行。这一行只在对话记录里,**不进入模型的上下文**,除非用户点了它。
+
+### 4.5 用户点了之后
+
+点按钮或点正文时,以一轮用户回合(`TurnKind.USER`)进入大脑,消息由设备拼好:
+
+```
+[You offered in a bubble: "12点了,要帮你点外卖吗?" — the user tapped "好"]
+```
+
+用英文方括号,理由和 `notifyPageClosed` 一样:这是设备在说话,模型据此判断用户语言时会跳过它(`LocalPrompt` §9)。
+
+**信任要继承,不能洗白。** 这是这一部分最该记住的一条。气泡的文字是模型写的;如果写它的那一轮是 `NOTIFY`(内容来自陌生人的通知),那么陌生人的话就可能借一个"好"按钮,变成一轮 `USER` 回合,重新拿到保险箱和情景的权限。`Todo.untrusted` 已经为闹钟解决过同一个问题(`NotebookTypes.kt:38`),气泡照抄:
+
+- 气泡记录 `untrusted`,取自创建它的那一轮;
+- 点击后的回合按这个标记跑:`untrusted` 的气泡回来仍是不可信回合;
+- **静默回合(`SWEEP` / `HARVEST`)不能直接发气泡**,因为它们只许用 `note.*`。复盘想第二天说的话,写进今日计划(§5.4),或走"见面时说"(§6.4)。
+
+否定按钮和"没理"都不开回合,只写一条结果记录(§4.8)。
+
+### 4.6 气泡从哪里来
+
+**① 模型在回合中顺手留一个:新工具 `nudge`。**
+
+```
+nudge(text, buttons?, dismiss?, ttl_minutes?, kind?)
+```
+
+- `text`:一句话,最好 20 个字以内;
+- `buttons`:0–3 个;
+- `dismiss`:哪个按钮表示"不用"(点它不开回合);
+- `ttl_minutes`:默认 30,最大 720;
+- `kind`:一个短标签,比如 `water`、`meal`,用来做冷却和学习(§4.7、§4.8)。
+
+它不阻塞,立刻返回 `{queued: true}` 或者带理由的拒绝(预算用完、冷却中、被用户关掉了这一类)。拒绝时要说清楚条件,和 `fold_topic` 的写法一样,不要让模型重试。
+
+工具描述里要讲清楚:**它和 `ask_user` 的分界**——需要用户现在就决定的事用 `ask_user`;可有可无、不理也没关系的才用 `nudge`。还要讲清楚:**发了气泡就别再口头重复一遍。**
+
+**② 不经过模型的待办:`todo` 新增 `nudge` 形态。** 现在待办到点会跑一整轮 agent(约 22k token 的 prompt),只为说一句"该喝水啦",太浪费。
+
+```
+todo(cron="0 10,14,16 * * *", nudge={text:"该喝水啦 💧", kind:"water"})
+```
+
+设定时,文案就已经由模型写好。到点后 `Scheduler` 直接弹气泡,**不调用模型**。只有用户点了气泡,才开始真正的回合。气泡对应的待办在到点弹出时就算完成,`what` 可以留空。需要到点再判断一下的(比如"如果他还没吃饭就提醒"),仍然用普通 `todo`,由模型醒来判断后再调 `nudge`。
+
+**③ 计划和念头:今日计划里到点的条目(§6.1)和念头回合(§6.2)的出口。**
+
+### 4.7 预算、冷却、开关
+
+预算、冷却和开关都由设备执行,不靠 prompt:
+
+- **全局上限**:每小时最多 2 个,每天最多 8 个(初值,要真机调)。超了就拒绝,并告诉模型原因。
+- **同类冷却**:同一个 `kind`,两次之间至少间隔 45 分钟;`todo` 的 nudge 形态也受这条约束。
+- **安静时段**:默认 22:30–8:00 不出。设备熄屏期间暂存,开屏后再按 TTL 判断。
+- **开关**:设置里加一项"主动招呼:关 / 少 / 正常",**最左边是"关"**,规则和其他选择器一样,读不到时取最左。新设备默认"少":每小时 1 个,每天 4 个。
+- **长按气泡**:弹出"这类别再提醒"。选了之后把这个 `kind` 关掉,并写一条 `remember(type=feedback)`,让模型也知道。
+
+### 4.8 记下用户的反应,交给复盘学习
+
+每个气泡的结果都记下来,存在小本本里的一个环形缓冲区,留最近 200 条:
+
+```
+{at, kind, text, outcome: tapped(button)|opened|dismissed|ignored|expired|suppressed}
+```
+
+- 复盘时,把最近一天的统计**按 kind 汇总成几行**交给模型,不给原始记录。这样像"喝水:5 次没理,1 次点开"这样的模式,模型一眼就能看出来。
+- `REVIEW_RULES` 加一条:某类招呼连续被忽略,就改频率(`todos` 暂停或改 cron),或者写一条 feedback;某类总被点开,可以考虑多做。**同样不允许为了显得主动而硬加。**
+- 这一步才让它慢慢像"懂这个人",而不只是一个定时器。
+
+### 4.9 两个身体
+
+- **core**:`BrainHost` 加 `nudge(spec): NudgeResult`;预算、冷却、TTL 和结果记录都放在 core(`NudgeBook`,纯函数,可以单测),两个身体共用,不各写一份。
+- **Android**:气泡**必须挂在球自己的窗口里**,复用 `FloatingWindowUi.showSignboard` 的托管方式(`FloatingWindowUi.kt:677`),和 `CardUi` 共用一个槽位。**不能另开一个 overlay 窗口**:多一个窗口,不透明度一叠加超过 0.80,系统就会静默丢掉大脑注入的所有点击。根节点同样要调 `hideFromAccessibility()`,否则大脑会在界面树里读到自己的气泡。卡片要来时,气泡立刻让出槽位,并转成暂存。
+- **Mac**:贴着 `FloatingBall` 弹出,复用 `PromptWindow` 的定位逻辑。Mac 上的球可能在用户没在看的那块屏幕上,这正好符合气泡的性质:错过了也没关系,**所以不配声音**。这一点和好友请求不一样,好友请求会先响一声,因为那件事有人在等。
+
+### 4.10 验收(第一部分)
+
+- 四条路径真机走一遍:只说一句后淡出;点按钮开回合;点"不用"不开回合;点正文开对话。
+- 让位规则:有卡片、在说话、在执行任务、熄屏时各试一次,确认气泡**不出、也不丢**,条件解除后再出,过期就作废。
+- 信任继承:在 `NOTIFY` 回合里发气泡,点击后的回合拿不到保险箱。`TurnGuards` 要有单测。
+- 气泡出现时,大脑执行一次 `tap_by_coordinates`,确认点击没有被丢(不透明度上限那条)。
+- 界面树里看不到气泡。
+- 用 `todo` 的 nudge 形态到点弹出,确认 `brain_trace.jsonl` 里**没有**模型调用。
+
+---
+
+## 5. 第二部分:计划
+
+### 5.1 三层,上层指导下层
+
+| 层 | 回答的问题 | 多久变一次 | 谁写 |
+|---|---|---|---|
+| 长期方向 | 这段时间我在帮他做成什么?他在意什么? | 每周复盘,或他明确说了 | 模型起草,用户可删改 |
+| 今日计划 | 今天我打算怎么过?什么时候、为什么找他? | 每天一份 | 凌晨起草,早上定稿 |
+| 此刻 | 计划里有没有哪条现在该做、或该调整? | 随时 | 设备按时间执行,念头回合判断 |
+
+没有上层的下层,就是用户说的"零散和随机"。所以**每一次主动开口,都必须能指回今日计划里的一条,每条今日计划都必须能指回一条长期方向或一个待办**。指不回去的,就不说。
+
+### 5.2 长期方向
+
+小本本新增一类条目(替代早先草案里的"心事"):
+
+```
+{id, title, why, how_i_help, good_when, source, status: active|paused|done|dropped, updated_at}
+```
+
+例子:
+
+- `title`:Andee 发布
+- `why`:他 10 月 26 日说"这周要把 0.6.2 发出去,官网和视频也要跟上"
+- `how_i_help`:盯住还没完成的几件事,每天下午问一次进度;他让我做的检查我先做
+- `good_when`:他说发完了,或者说不发了
+
+规则:
+
+- **只能来自用户说过的话或做过的事**,`source` 记下出处(哪天、哪句话)。不能替他编目标;不能把"大家都该多运动"写成他的方向。
+- **刚开始几乎是空的。** 这时它最早的主动应该是认识他:今日计划里可以有一条"找个他不忙的时候问一句:最近主要在忙什么?有什么想让我帮你盯着的?"。第一周最多问三次,被忽略就停。
+- 同时活跃的方向最多 5 条,多了说明它没有重点。
+- 用户删掉的方向不再出现;删除本身记一条 `remember(type=feedback)`,免得模型换个说法又写回来。
+
+### 5.3 今日计划
+
+每天一份,用它自己的口吻写,也存在小本本里:
+
+```
+{date, intent, items: [{id, when, kind, what, because, status}], quiet: [...]}
+```
+
+- `intent`:一句话今天的打算,第一人称。例如"今天我想帮他把发布收个尾,别的事少打扰。"
+- `items`:
+ - `when`:时间(`10:00`)或时段(`午饭前`、`下午`),也可以是"他第一次找我时";
+ - `kind`:`remind`(提醒)、`ask`(问一句)、`prepare`(不打扰地先做好)、`follow_up`(跟进没收尾的事);
+ - `what`:要做什么、要说什么;
+ - `because`:指回哪条方向或哪个待办,**不能为空**;
+ - `status`:`planned` / `done` / `ignored`(气泡没人理)/ `moved`(推到明天)/ `dropped`。
+- `quiet`:今天**不打扰**他的事,和要做的事同样重要。例如"他上午在开会,12 点前不出气泡"。
+
+上限:一份计划里最多 5 次会打扰他的条目(`remind` + `ask`),并且照样受「主动招呼」档位、冷却和夜间时段约束。
+
+### 5.4 什么时候写
+
+- **凌晨起草**:夜间复盘(`SWEEP`)结束时多做一步:看长期方向、未完成的待办、昨天计划里推迟的条目,写出明天的草稿。静默回合,只用 `note.*`,不需要新权限。
+- **早上定稿**:他当天第一次出现时(手机解锁、Mac 有键盘鼠标输入),跑一次**不带工具的便宜调用**(约 1–2k token,和通知分诊同一种做法),按现在的时间、今天已经发生的事微调草稿:删掉已经过时的条目,补上今天才知道的事。不需要一整轮 agent。
+- **白天随时可改**:他在对话里说"今天下午别打扰我"或"帮我记得 5 点前交报告",模型用工具改今日计划,而不是只记一条笔记。
+
+### 5.5 在设置里可见
+
+设置里新增一节「它的打算」(手机在设置卡片里,Mac 在设置页里),两块内容:
+
+- **长期方向**:每条一行标题,展开能看到"为什么"和"我怎么帮",以及出处。每条可以**删除**或**暂停**。
+- **今日计划**:先显示那句 `intent`,再按时间列出条目和状态(已做 / 没理 / 推迟),以及"今天不打扰的事"。每条可以**删除**;底部有一个输入框"告诉它一句",写的话作为一条用户消息交给模型,比如"今天别提喝水了"。
+
+为什么放进设置、而不是只藏在模型脑子里:
+
+- **看得见,主动才不突兀。**用户知道它下午三点会来问周会材料,到时候气泡出现就不是打扰,而是"它记着呢"。
+- **改得了,才不会被偷偷安排。**用户删掉的条目,设备直接执行删除,不经过模型同意;模型下次看到的计划里就没有它了。
+- **它也是"有灵魂"最直接的证据:**一份用它自己口吻写的、每天在变的打算。
+
+聊天里问"你今天打算做什么"也能回答,内容和设置里一致,因为读的是同一份数据。
+
+### 5.6 每轮带上
+
+今日计划里接下来的一两条和剩余条目数,跟着每轮 user message 带一行,和 notebook 索引放在同一位置,理由相同:**不破坏 prefix cache**。长期方向只带标题。这样用户在对话里提到相关的事,模型知道它和计划的关系。
+
+---
+
+## 6. 第三部分:执行与回顾
+
+### 6.1 到点的条目直接变成气泡
+
+今日计划里带具体时间的 `remind` / `ask` 条目,定稿时由设备自动转成气泡型待办(原第二期的 `todo` nudge 形态):
+
+- 到点由调度器直接弹气泡,**不调用模型**;
+- 气泡的结果(点了 / 不用 / 没理 / 过期)回写到那条计划条目的 `status`;
+- 用户在设置里删掉条目,对应的待办一起取消。
+
+这样大部分主动是"按计划执行",确定、便宜、可预期,而不是每次都临场决定。
+
+### 6.2 念头回合:对照计划,而不是凭空想
+
+只用于计划里写的是时段而不是具体时间的条目("午饭前""他空下来时"),以及计划需要调整的情况。触发时机:
+
+- 用户空下来(手机:解锁后、亮屏且空闲一阵;Mac:一段时间没有在 Andee 里说话,但人在电脑前);
+- 进入某个时段(例如 11:30 进入"午饭前")。
+
+做法和通知分诊同构:**不带工具、约 500 token 的单次调用**,输入是今日计划、现在时间、最近几条气泡结果。输出只有四种:`hold`(现在不合适)、`nudge{条目}`(就是现在,弹它)、`act{条目}`(需要先做点事,开一轮回合,权限同 §6.3)、`adjust{…}`(今天的情况变了,改计划)。
+
+预算:每天最多 16 次预判、2 次完整回合。调用失败一律当作 `hold`:念头失败时的旧行为就是什么都不做。
+
+### 6.3 准备回合(PREPARE)——已决定不做
+
+`kind=prepare` 的条目,在用户不在时跑一轮完整回合,先把事情做好:
+
+- **每晚最多 1 轮**,白天在用户离开时最多 1 轮,各有独立的 token 预算,超了就停下并写一条记录;
+- 能做的:查资料、看网页、比价、做一页 `show_html` 存进产物面板(**不弹出来**)、写笔记;
+- 不能做的(在 dispatcher 里拦):`device.vault.*`、发送消息、下单 / 支付、删除、`peer.ask`、情景的 save / enter,以及任何打开摄像头或麦克风的东西;
+- 手机上只在**充电且熄屏或锁屏**时允许驱动其他应用,否则只能用不碰屏幕的工具;Mac 上只在用户离开时允许;
+- 做完后把成果挂在那条计划条目上:`prepared: {artifact_id, summary}`。
+
+### 6.4 见面时说
+
+准备好的东西,在用户下次出现时提:可以是一个气泡「昨晚帮你看了下周去上海的车次」,按钮 [看看] [不用];也可以在他下次说话时,由设备在 user message 里附一行 `[Prepared while they were away: …]`,模型自己决定怎么提。**只说真的做过的事。**
+
+### 6.5 晚上对照,修正明天和长期方向
+
+夜间复盘时,把今日计划和实际情况放在一起看:
+
+- 每条的结局:做了、他没理、推到明天、取消;
+- 按 `kind` 汇总的气泡结果(第一部分 §4.8 的记录),例如"喝水提醒:3 次没理";
+- 据此写明天的草稿(§5.4):没理的减少或换时间,做成的继续,推迟的带上;
+- **每周一次**看长期方向:哪条已经完成、哪条一周都没有进展、有没有新出现的方向。
+
+`REVIEW_RULES` 第 5 条("你接下来想做什么")就落在这里,而不是一条没人读的笔记。
+
+---
+
+## 7. 分期
+
+| 期 | 内容 | 主要改动 | 用户能感受到什么 |
+|---|---|---|---|
+| 1 | 气泡(已完成) | `NudgeBook`、`NudgeUi`、`Nudges`、`nudge` 工具 | 模型偶尔会用气泡 |
+| 2 | 计划的存储 + 设置里可见 + 复盘起草明天的计划 + 长期方向 | 小本本新增两类条目和工具,复盘规则,两端设置页新增「它的打算」 | 设置里能看到它的打算,能删改 |
+| 3 | 到点条目变成气泡 + 气泡结果回写 | `todo` 的 nudge 形态,调度器分支,结果记录 | **第一次真正感受到主动**:按计划、按时间出现 |
+| 4 | 早上定稿 + 念头回合 | 首次出现的检测,便宜调用,`adjust` 写回计划 | 计划会跟着当天情况变 |
+| 5 | ~~准备回合 + 见面时说~~(不做) | `PREPARE` 回合类型,dispatcher 守卫 | "它在我不在时替我想过" |
+| 6 | 晚上对照 + 每周方向 | 复盘规则,统计汇总 | 越用越贴合 |
+
+**建议第 2、3 期一起做**:只有计划没有执行,用户还是感受不到;只有执行没有计划,就回到了零散随机。
+
+每期都要同步更新的:金标准文件(`tool_schemas.json`、`local_prompt*.txt`);`CLAUDE.md`;两端的 `BrainHost` 实现。
+
+### 成本估算(DeepSeek)
+
+- 凌晨起草:附在已有的夜间复盘里,多几百个输出 token;
+- 早上定稿:一次约 1–2k token 的便宜调用;
+- 到点气泡:不调用模型;
+- 念头预判:最多 16 次 × 约 500 token;
+- 准备回合:最多 2 轮完整回合,每轮约 20–40k token。
+
+合计每天几毛钱以内,其中大头是准备回合,所以它的预算单独设、单独计账。
+
+## 8. 衡量
+
+- 每类气泡的点开率、忽略率(§4.8 的记录);
+- 今日计划条目的完成率,以及用户删改计划的次数(删得多,说明计划不贴合);
+- 用户关闭「主动招呼」的比例;
+- 准备回合产出的页面,被打开过的比例;
+- 每天在主动上花的 token(起草、定稿、念头、准备分开计账)。
+
+如果某一期上线后点开率明显低、删改和关闭的人多,**那一期就该回退,而不是加更多主动**。
+
+## 9. 不做什么
+
+- **不主动截屏、不主动看摄像头、不主动听。** 被叫去看和主动去看,在隐私上是两回事。
+- **不在主动回合里做不可逆的事。** 发送、支付、删除、登录都必须等用户在场、并且亲口同意。
+- **不替用户编目标。** 长期方向只来自他说过的话或做过的事。
+- **不用语音主动开口。** 语音是最强的打扰,要等气泡的数据说明这个人欢迎主动之后再考虑,而且到那时也应该是一个单独的开关。
+- **不排队。** 暂存的气泡最多一个。
+
+## 10. 未决问题
+
+1. 气泡停留多久?12 秒 / 30 秒是拍脑袋的数字,要真机试。
+2. ~~否定按钮要不要也开一轮回合~~ **已定:不开。**
+3. 设置里那一节叫什么:「它的打算」「计划」还是「今天」?
+4. 用户在设置里能做到哪一步:只能删和暂停,还是也能直接编辑条目文字?倾向于只删和暂停,其他通过"告诉它一句"交给模型改,免得设备侧维护一个编辑器。
+5. 两个身体各有一份计划,还是共用一份?用户的手机和 Mac 已经是"朋友",计划共用更像一个人,但要解决同步。倾向于第一版各自一份,以后再合。
+6. 早上定稿用便宜调用够不够?如果需要看待办和昨天的对话细节,可能要升级成一轮静默的完整回合。
+7. Hub 大脑:继续不支持(`nudge` 已标 `localOnly`)。
+8. 情景能不能调整主动程度?倾向于可以,写进情景规则里,不另设开关。
+
+## 11. 第一期的实际做法(与上文的出入)
+
+代码位置:`core/.../brain/NudgeBook.kt`(校验、预算、冷却、安静时段,有 `NudgeBookTest`);`app/.../ui/NudgeUi.kt`(暂存、让位、TTL、点击结果);`CardUi.bubble`(绘制,和卡片共用球上的一个槽位);`CommandDispatcher` 的 `ui.nudge`;`BodyCoreService.nudgeGate` / `answerNudge`;设置卡片的「主动招呼」一节。
+
+- **对话记录**:气泡第一次到达用户时(弹出,或卡片展开时直接写成一行),把文字记成一条普通的助手消息。不是 §4.4 说的"灰色、可点的小字",第一期先不做。
+- **长按**:直接静音这一类,不弹确认;在对话记录里写一句告诉用户,设置里有「全部恢复」。没有写 `remember(type=feedback)`:模型下次发同类气泡时,拒绝理由会告诉它用户关掉了。
+- **全屏视频 / 游戏、通话**:还没有检测。这两项列在 §4.3,第一期没做。
+- **预算计数在内存里**:服务重启后清零,偏向多出一个气泡。
+- **球的反应**:借用任务结束时的表情闪现通道,换成 `WAVE` + 跳一下;不支持手势的形象显示 `WAVE` 那一行的普通表情。
+- **不响应语音**:气泡上的按钮不能用说话来按,因为气泡没有读出来,用户说的「好」不一定是在回答它。
+- **Mac**:见下面「Mac 版」一节。
+
+真机验收按 §4.10 走一遍。没有 `adb` 的情况下,可以从 9008 调试口直接调:`tools/body.py ui.nudge '{"text":"该喝水啦","kind":"water"}'`。
+
+### 真机结果(荣耀 AMM-AN00,Android 15,2026-10-27)
+
+已验证:
+- 卡片展开时,气泡写成对话记录里的一行;
+- 收起时弹出气泡,宽度贴合文字,尾巴对准球头,球挥手;在其他应用(Google Play)上方也正常;
+- 超出预算时返回 `queued: false` 和原因;同类冷却、静音的拒绝理由正确;
+- 点"不用"只关闭气泡、不开回合;点"好"开回合,对话记录里依次有气泡的话、「好」、回答;
+- 真卡片来时气泡让位(`superseded`),卡片关闭约 5 秒后回来,12 秒后淡出(`timeout`);对话记录只记一次;
+- 气泡挂着时,注入的点击正常落地,日志里没有不受信任触摸的拦截;
+- 长按静音写入 `nudge_muted`,设置里显示静音列表,「全部恢复」能清掉;
+- 设置里的「主动招呼」选择器保存正确。
+
+真机测出并已修复:`answerNudge` 原来先 `submit` 后 `beginTask`。没有 key 时 `submit` 同步回答,"任务结束"排在"任务开始"之前,边缘任务光要亮到 5 分钟兜底才灭。改成先开始任务再提交后,回答完任务光即灭。
+
+还没在真机上验证:熄屏 / 锁屏 / 勿扰 / 夜间时段的暂存,以及不可信回合(通知触发)点击后仍是不可信回合。后者有逻辑但没有专门的单测。
+
+### Mac 版(2026-10-27)
+
+和手机共用 core 里的 `NudgeBook`(校验、预算、冷却、安静时段)和同一个工具定义;Mac 自己的部分在 `desktop/NudgeBubble.kt`(`Nudges` 负责暂存、让位和保质期,`BubbleWindow` 负责显示),`UiTools` 处理 `ui.nudge`,`Assistant.answerNudge` 开回合。
+
+和手机不同的地方:
+- **气泡是一个独立窗口**,贴在球旁边,不抢焦点。Mac 的问答卡片和字幕也是这样做的;Mac 没有手机那条 0.80 不透明度上限,球的窗口又只有球那么大。没有指向球的小尾巴。
+- **"卡片展开"换成"聊天窗口在最前面"**:这时气泡改成写在对话记录里的一行。
+- **"熄屏 / 锁屏"换成"5 分钟没有键盘鼠标输入"**(读 `ioreg` 的 `HIDIdleTime`):人离开了或锁屏了,气泡先存着。
+- **让位**:问答卡片或命令确认卡片出现时,气泡让开,卡片走后再回来。
+- 设置页加了「主动招呼」一节(关 / 少 / 正常)和「全部恢复」。
+
+验证情况:编译和测试通过;`./gradlew :desktop:uishot --args='bubble 360 220 /tmp/b.png'` 画出了日间和夜间两套主题下的卡片,设置页也截图确认过。**还没有在真实运行的 Mac 版上试过**:这台 Mac 上正在运行用户自己的 Andee,同时再起一个开发版会共用数据目录,所以没有启动。
+
+## 12. 第 2、3 期的实际做法(2026-10-27)
+
+代码位置:
+- `core/.../config/Plans.kt`:长期方向和每日计划的存储(小本本里的 `plan` 分区,和 `Gear` 同一种做法)、两个工具的处理、每轮索引那一行、到点气泡的对账(`reconcile`)、到点时判断要不要弹(`bubbleFor`)、结果回写(`recordOutcome`)。两端共用,有 `PlansTest`(13 个用例)。
+- 工具:`plan_directions`(`note.directions`)和 `day_plan`(`note.day_plan`),都在 `note.*` 下,所以复盘回合能用;都是 `localOnly`。
+- `Todo` 新增 `nudge` 字段(气泡规格的 JSON)。有这个字段的待办到点时**不唤醒大脑**,直接弹气泡。
+- `TurnGuards`:不可信回合(通知触发)不能改计划。理由同 `Todo.untrusted`:计划里的条目会变成气泡,用户一点就是一轮可信回合。
+- 复盘规则 `REVIEW_RULES` 第 8 条:维护今天的计划,20:00 以后起草明天的;长期方向只来自用户说过的话;还没有方向时,每天最多一个"认识你"的问题。
+- 每轮 user message 带一行计划(紧跟小本本索引)。
+- Android:`Notebook.plans()`、`Scheduler.syncPlan()`(写计划后、启动时对账闹钟)、`BodyCoreService.postPlanBubble()`;闹钟到点时服务不在、或开机补发时,气泡待办只标记为"错过",不发系统通知,也不留言给大脑。设置卡片新增「它的打算」一节。
+- Mac:`DesktopNotebook.plans`、`DesktopScheduler.syncPlan()`、`Nudges.postPlanned()`;`Nudges.book` 改为 `nudge` 工具和计划气泡共用的同一份预算。设置页新增「它的打算」一节;`./gradlew :desktop:uishot --args='settings 1020 3000 /tmp/p.png plan'` 能画出带假计划的设置页。
+
+和上文的出入:
+- **计划由复盘起草,而复盘需要有对话可回顾。**完全没聊过天的设备不会出现计划。早上定稿(第 4 期)还没做。
+- **20:00 以后才起草明天的计划**;白天的复盘只维护今天的。
+- 状态多了 `skipped`(超出档位预算或被静音)和 `missed`(到点时设备没在运行,或已过保质期 60 分钟)。
+- 一天最多 12 个条目,其中最多 5 个会打扰用户;同时活跃的长期方向最多 5 条。
+
+验证情况:单元测试和金标准通过;两端编译通过;Mac 版已装上并正常启动;Mac 设置页离屏截图确认过。**还没有在真机上走过"复盘写出计划 → 到点弹气泡 → 结果回写 → 设置里看到状态"这条完整链路。**手机上可以直接用调试口写一份计划来测:`tools/body.py note.day_plan '{"action":"write","date":"today","intent":"…","items":[{"time":"HH:mm","kind":"remind","what":"该喝水啦","because":"规律喝水"}]}'`。
+
+## 13. 第 4、6 期的实际做法(2026-10-27)
+
+- **`core/.../brain/PlanMind.kt`**:两次不带工具的便宜调用,和通知分诊同一种做法。
+ - `morning`:每天第一次见到用户时(手机解锁、Mac 有键盘鼠标输入),读长期方向、昨天每条的结果、今天的草稿、今天到期的待办、小本本索引,写出今天的计划,或回答 `{"keep": true}`。写入走 `day_plan` 同一套校验。**这也让没被复盘过的设备第一次有了计划。**
+ - `muse`:今天还有"只写了时段"的提醒或提问时,判断现在是不是时候,最多选一条;选中后照样经过气泡预算(`Plans.bubbleForItem`),被挡下会在条目上记 `skipped` 和原因。
+ - 都是失败即不动:没有 key、调用失败、读不懂回答,计划就保持原样。早上定稿不论成败当天只做一次。
+- **时机**由 `Plans` 判定,状态存在计划分区的 `meta` 里,重启不会重来:早上定稿每天一次、5:00 以后;念头间隔至少 40 分钟、每天最多 12 次、夜间(22:30–8:00)不跑,而且只在有"只写了时段"的条目时才跑。
+- **触发**:手机在 `USER_PRESENT`(解锁)和每 10 分钟巡检时,要求屏幕亮着且已解锁;念头还要求没在执行任务、没在说话、没在开会,且「主动招呼」不是关。Mac 每 5 分钟巡检,要求 5 分钟内有键盘鼠标输入;念头另要求没有卡片、没在工作、没在开会。
+- **第 6 期**:复盘规则第 8 条加上"写明天之前先读今天的结果:做成的保留,没理或拒绝的减少或换时间,推迟的带上"。计划索引在一周没看过长期方向时加一句提示,复盘时 `plan_directions list` 一次即清除(`directions_reviewed_at`)。
+- 测试:`PlansTest` 增至 19 个用例,覆盖早上一次、念头的间隔 / 次数 / 夜间 / 无可选条目、念头选中后的气泡与被挡、每周提示、早上上下文里带上昨天的结果。
+
+**真机结果(Mac,2026-10-27 19:29)**:新版装上后第一次巡检就跑了早上定稿,真实模型根据小本本写出今天的计划("今天先把两件悬着的事收个尾……其余不打扰你"),其中一条带时间的提醒排进了定时器。观察到的一点:没有长期方向时,模型在 `because` 里引用的是小本本里的笔记,而不是方向或待办。设备没有拦,因为它确实指向了一件具体的事。
+