Skip to content

armgit / andee

Public Imported from GitHub
0

Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。

fix(mac): stop leaking ball threads, tap-to-talk from the mic, honest self-check

booboosui5ac1e0c7a603
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/App.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/App.kt
index 52b3910..b429354 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/App.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/App.kt
@@ -45,6 +45,7 @@ fun AppRoot(nav: Nav) {
else -> ChatScreen(
onOpenArtifacts = { nav.go("artifacts") },
onOpenTopic = { nav.push("topic:$it") },
+ onOpenSettings = { nav.go("settings") },
// 继续话题 from the card itself: the same two steps as on the topic page.
onContinueTopic = { Assistant.beginTopic(it); ComposerFocus.pending = 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 0fa3d7e..87798d5 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
@@ -61,11 +61,28 @@ class BallRenderer(val width: Int, val height: Int, calmFrameNs: Long = CALM_FRA
private val thread = thread(name = "BallGL", isDaemon = true) {
runCatching { run() }.onFailure {
+ if (stopRequested) return@onFailure
failure = it.message ?: it.toString()
Log.e(TAG, "the ball cannot be drawn", it)
}
}
+ /**
+ * Wait up to [ns], or less: a queued command (a tap, a new face) ends the wait so the very next frame
+ * carries it — at the resting rate the loop used to sleep through up to 250 ms of a click. False when
+ * [stop] asked us to leave.
+ */
+ private fun nap(ns: Long): Boolean {
+ val end = System.nanoTime() + ns
+ while (true) {
+ if (stopRequested) return false
+ if (!commands.isEmpty()) return true
+ val left = end - System.nanoTime()
+ if (left <= 0) return true
+ java.util.concurrent.locks.LockSupport.parkNanos(left)
+ }
+ }
+
private fun run() {
val ctx = createContext()
try {
@@ -102,16 +119,22 @@ class BallRenderer(val width: Int, val height: Int, calmFrameNs: Long = CALM_FRA
if (delay == HOLD && frame != null) {
// Holding the last frame: draw nothing, but wake often enough that
// a change of face is picked up in POLL_MS, not a calm period later.
- Thread.sleep(POLL_NS)
+ if (!nap(POLL_NS)) break
continue
}
+ val g0 = System.nanoTime()
renderer.onDrawFrame()
+ val g1 = System.nanoTime()
buf.clear()
GL11.glReadPixels(0, 0, width, height, org.lwjgl.opengl.GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, buf)
+ val g2 = System.nanoTime()
frame = flipped(buf)
+ if (TRACE) GlTrace.record(g1 - g0, g2 - g1, System.nanoTime() - g2)
onFrame()
- val sleep = (delay - (System.nanoTime() - t0)) / 1_000_000
- if (sleep > 0) Thread.sleep(sleep)
+ // Nanoseconds, not truncated milliseconds: that rounding plus the sleep's own overshoot
+ // measured 25 fps for a requested 30.
+ val left = delay - (System.nanoTime() - t0)
+ if (left > 0 && !nap(left)) break
}
FBO.glDeleteRenderbuffers(depth)
FBO.glDeleteRenderbuffers(color)
@@ -174,7 +197,7 @@ class BallRenderer(val width: Int, val height: Int, calmFrameNs: Long = CALM_FRA
fun signalOutcome(ok: Boolean) = post { renderer.signalOutcome(ok); markActive() }
fun trigger(action: Action) = post { renderer.request(action); markActive() }
- private fun post(f: () -> Unit) { commands.offer(f) }
+ private fun post(f: () -> Unit) { commands.offer(f); java.util.concurrent.locks.LockSupport.unpark(thread) }
/**
* Full rate while there is something to watch — listening, speaking, thinking,
@@ -196,12 +219,21 @@ class BallRenderer(val width: Int, val height: Int, calmFrameNs: Long = CALM_FRA
/** Hold full rate for a beat, so a pop or a nod finishes before it slows. */
private fun markActive() { activeUntilNs = System.nanoTime() + ACTIVE_NS }
+ /**
+ * Ask the render thread to finish and return at once. It used to `join(2000)` on the caller, which is
+ * the UI thread (this runs from a view's onDispose): a thread parked in its frame sleep, or in a GL call,
+ * then cost the whole 2 s on every page switch — and when the join timed out the thread simply stayed,
+ * with its GL context and framebuffer, one more on every switch. The thread now notices on its own
+ * (an unpark ends the wait), frees its GL objects and exits.
+ */
fun stop() {
stopRequested = true
- thread.join(2000)
+ onFrame = {}
+ java.util.concurrent.locks.LockSupport.unpark(thread)
}
companion object {
+ private val TRACE = System.getProperty("andee.ballTrace") != null
const val TAG = "Ball"
/**
* 30 fps. The ball's motion is slow springs and breathing, which read the
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt
index 35efc9e..b4c33ba 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt
@@ -61,13 +61,20 @@ fun SelfCheckCard(onDone: () -> Unit, onOpenSettings: () -> Unit) {
add(CheckRow("fda", if (zh) "完全磁盘访问" else "Full Disk Access", fda,
if (fda) if (zh) "能读通知" else "Can read notifications" else if (zh) "读不到通知数据库" else "Cannot read the notification store",
{ openPane("Privacy_AllFiles") }))
- val backend = Settings.get("llm_api_key").isNotBlank()
+ // Asked of the backend in force, not of one key's name: under CodeFlying the key is codeflying_key,
+ // and the same key carries the voice. Reading llm_api_key there said "missing" for a Mac that worked.
+ val cf = Assistant.config().mode == net.kuafuai.andee.config.BrainConfig.BRAIN_CODEFLYING
+ val backend = Assistant.config().apiKey.isNotBlank()
add(CheckRow("backend", if (zh) "大脑 Key" else "Model key", backend,
- if (backend) if (zh) "已配置" else "Configured" else if (zh) "还没配,回答不了" else "Missing — Andee cannot answer",
+ if (backend) if (zh) (if (cf) "已配置(CodeFlying)" else "已配置") else (if (cf) "Configured (CodeFlying)" else "Configured")
+ else if (cf) if (zh) "还没填 CodeFlying 密钥,回答不了" else "No CodeFlying key — Andee cannot answer"
+ else if (zh) "还没配,回答不了" else "Missing — Andee cannot answer",
{ onOpenSettings() }))
val voice = net.kuafuai.andee.desktop.voice.MacVoice.configured()
add(CheckRow("voice", if (zh) "语音 Key" else "Voice key", voice,
- if (voice) if (zh) "能听能说" else "Can hear and speak" else if (zh) "还没配,说不了话" else "Missing — Andee cannot speak",
+ if (voice) if (zh) (if (cf) "能听能说(用同一个 CodeFlying 密钥)" else "能听能说") else (if (cf) "Can hear and speak (same CodeFlying key)" else "Can hear and speak")
+ else if (cf) if (zh) "还没填 CodeFlying 密钥,说不了话" else "No CodeFlying key — Andee cannot speak"
+ else if (zh) "还没配,说不了话" else "Missing — Andee cannot speak",
{ onOpenSettings() }))
}
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt
index 264d6e8..083876a 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt
@@ -1,8 +1,6 @@
package net.kuafuai.andee.desktop
-import androidx.compose.foundation.gestures.detectHorizontalDragGestures
-import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.graphics.graphicsLayer
@@ -121,7 +119,7 @@ private fun openLink(url: String) {
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
-fun ChatScreen(onOpenArtifacts: () -> Unit, onOpenTopic: (Long) -> Unit = {}, onContinueTopic: (Scrollback.Topic) -> Unit = {}) {
+fun ChatScreen(onOpenArtifacts: () -> Unit, onOpenTopic: (Long) -> Unit = {}, onContinueTopic: (Scrollback.Topic) -> Unit = {}, onOpenSettings: () -> Unit = {}) {
var rows by remember { mutableStateOf(Scrollback.snapshot()) }
var progress by remember { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
@@ -163,11 +161,9 @@ fun ChatScreen(onOpenArtifacts: () -> Unit, onOpenTopic: (Long) -> Unit = {}, on
LaunchedEffect(Unit) { pending = Assistant.pending }
LaunchedEffect(items.size) { if (items.isNotEmpty()) list.animateScrollToItem(items.size - 1) }
- // The ball is the phone's way in: a tap talks, a second tap says "done".
- fun toggleMic() {
- if (Meeting.isActive()) { Meeting.stopFromUser(); return }
- if (!net.kuafuai.andee.desktop.voice.MacVoice.toggle()) progress = noVoiceKey()
- }
+ // The microphone does exactly what a tap on the floating ball does (tapToTalk): it stops whatever was
+ // running, listens, and a second tap says "done".
+ fun toggleMic() = tapToTalk { askToOpenSettings(onOpenSettings) }
/** Pictures and files from any door — the clip button, a paste, a drop — end up on the same strip. */
fun attach(items: List<Attachment>) {
@@ -244,18 +240,6 @@ fun ChatScreen(onOpenArtifacts: () -> Unit, onOpenTopic: (Long) -> Unit = {}, on
)
Column(Modifier.weight(1f).fillMaxWidth().padding(horizontal = 16.dp)) {
- // The ball above the conversation, as on the phone's unfolded card: the same Andee as the floating
- // one (it wears the same face, see MacBall), and a tap talks to it. 产物 has its own sidebar door.
- // Same taps as the floating ball; sideways swipe switches character, like the full card's ball on the phone.
- val chatBall = remember { ballActions(onType = { ComposerFocus.pending = true }, onNoVoice = { progress = noVoiceKey() }) }
- Box(Modifier.fillMaxWidth().padding(bottom = 6.dp), contentAlignment = Alignment.Center) {
- // Holds its last frame at rest, unlike the floating ball, which keeps
- // breathing: this one shares a window with the conversation, so each of
- // its frames redraws all of it. It animates from the moment something
- // happens — listening, speaking, thinking, a tap — and settles after.
- BallView(150.dp, onClick = null, modifier = Modifier.ballTaps(chatBall).lookSwipe(),
- calmFrameNs = BallRenderer.HOLD)
- }
LazyColumn(
state = list, modifier = Modifier.weight(1f).fillMaxWidth().fadeTop(36.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(top = 4.dp, bottom = 18.dp),
@@ -329,8 +313,8 @@ fun ChatScreen(onOpenArtifacts: () -> Unit, onOpenTopic: (Long) -> Unit = {}, on
verticalAlignment = Alignment.CenterVertically,
) {
Text(
- if (Strings.lang() == "zh") "点小球说话 · 双击打字 · 左右拖动切换形象"
- else "Tap the ball to talk · double-tap to type · drag sideways to switch character",
+ if (Strings.lang() == "zh") "点小球说话 · 双击打字 · 设置里切换性格"
+ else "Tap the ball to talk · double-tap to type · switch character in Settings",
color = Palette.photoInk, fontSize = 11.sp,
)
Box(Modifier.clickable { openLink(GITHUB_URL) }.padding(horizontal = 5.dp, vertical = 2.dp)) { Icon(AndeeIcon.GITHUB, Palette.photoInk, 13.dp) }
@@ -405,7 +389,7 @@ private fun InputBar(
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
RoundButton(false.not(), onAttach, AndeeIcon.PAPERCLIP, quiet = true)
- RoundButton(listening, onMic, if (listening) AndeeIcon.STOP else AndeeIcon.MIC)
+ RoundButton(listening, onMic, if (listening) AndeeIcon.STOP else AndeeIcon.MIC, alwaysClickable = true)
Box(
Modifier.weight(1f).background(Palette.well, RoundedCornerShape(18.dp))
.border(1.dp, Palette.hairline, RoundedCornerShape(18.dp)).padding(horizontal = 14.dp, vertical = 10.dp),
@@ -474,14 +458,18 @@ private fun AttachmentStrip(items: List<Attachment>, onRemove: (Attachment) -> U
}
@Composable
-private fun RoundButton(enabled: Boolean, onClick: () -> Unit, icon: AndeeIcon, danger: Boolean = false, quiet: Boolean = false) {
+private fun RoundButton(
+ enabled: Boolean, onClick: () -> Unit, icon: AndeeIcon, danger: Boolean = false, quiet: Boolean = false,
+ /** Drawn as active (filled) when [enabled], but clickable either way: the microphone is both a state and a button. */
+ alwaysClickable: Boolean = false,
+) {
// A quiet button is always available but never the main action: no fill, the same rim as a disabled one.
val filled = enabled && !quiet
Box(
Modifier.size(40.dp)
.background(if (!filled) Palette.well else if (danger) Palette.danger else Palette.accent, CircleShape)
.border(1.dp, if (filled) Color.Transparent else Palette.hairline, CircleShape)
- .clickable(enabled = enabled) { onClick() },
+ .clickable(enabled = enabled || alwaysClickable) { onClick() },
contentAlignment = Alignment.Center,
) {
Icon(icon, if (filled) Color(0xFF0A2540) else if (quiet) Palette.label else Palette.secondary, 18.dp)
@@ -554,8 +542,13 @@ object ComposerFocus {
var pending by androidx.compose.runtime.mutableStateOf(false)
}
-fun noVoiceKey() =
- if (Strings.lang() == "zh") "还没配语音 Key:在设置的「语音」里填上。" else "No voice key yet: add it under Voice in Settings."
+fun noVoiceKey() = when {
+ // Under CodeFlying the one key covers the voice too, and there is no voice block to point at.
+ Assistant.config().mode == net.kuafuai.andee.config.BrainConfig.BRAIN_CODEFLYING ->
+ if (Strings.lang() == "zh") "还没有 CodeFlying 密钥:在设置的「后端」里填上。" else "No CodeFlying key yet: add it under Backend in Settings."
+ Strings.lang() == "zh" -> "还没配语音 Key:在设置的「语音」里填上。"
+ else -> "No voice key yet: add it under Voice in Settings."
+}
@Composable
private fun Bubble(r: Scrollback.Row) {
@@ -611,16 +604,3 @@ private fun Modifier.fadeTop(height: androidx.compose.ui.unit.Dp): Modifier = th
)
}
-/** A clearly sideways drag across the ball steps to the next or previous character, once per drag. */
-private fun Modifier.lookSwipe(): Modifier = this.pointerInput(Unit) {
- var dx = 0f
- var done = false
- detectHorizontalDragGestures(
- onDragStart = { dx = 0f; done = false },
- onHorizontalDrag = { change, amount ->
- change.consume()
- dx += amount
- if (!done && kotlin.math.abs(dx) > 48.dp.toPx()) { done = true; MacBall.stepLook(if (dx < 0) 1 else -1) }
- },
- )
-}
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 51a39de..ca439fd 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
@@ -167,9 +167,11 @@ fun BallView(
fun paint(f: ByteArray) {
if (queued.compareAndSet(false, true)) javax.swing.SwingUtilities.invokeLater {
queued.set(false)
+ val t0 = System.nanoTime()
bitmap.installPixels(f)
bitmap.notifyPixelsChanged()
tick++
+ if (System.getProperty("andee.ballTrace") != null) PaintTrace.record(System.nanoTime() - t0)
}
}
renderer.onFrame = { renderer.frame?.let(::paint) }
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 59646ff..17404a1 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
@@ -87,7 +87,7 @@ fun main() {
}
FloatingBall(
- actions = ballActions(onType = { openChat(typing = true) }, onNoVoice = { openChat("settings") })
+ actions = ballActions(onType = { openChat(typing = true) }, onNoVoice = { askToOpenSettings { openChat("settings") } })
.let { a -> BallActions(a.onTap, a.onDoubleTap, a.onTripleTap) { openChat() } },
onWindow = { ballWindow = it },
)
@@ -203,18 +203,38 @@ private fun defaultChatSize(): Pair<androidx.compose.ui.unit.Dp, androidx.compos
* with the cursor in the box; a long press is the caller's (the floating ball opens the window, the chat's own
* ball has nothing to open).
*/
-fun ballActions(onType: () -> Unit, onNoVoice: () -> Unit) = BallActions(
- onTap = {
- when {
- Meeting.isActive() -> Meeting.stopFromUser()
- else -> {
- // The phone's rule: a tap is "listen to me now". Whatever was running or being read out stops
- // first, and the mic opens in the same tap rather than needing a second one.
- if (Assistant.working()) Assistant.stop()
- if (!net.kuafuai.andee.desktop.voice.MacVoice.toggle()) onNoVoice()
- }
+/**
+ * The phone's rule for a ball that cannot listen (BodyCoreService.reportVoiceFailure): say what is missing on
+ * a card, and put the way out on the same card — the settings door is a button, not something the tap does
+ * to you. A tap that silently throws a window open reads as the app misbehaving.
+ */
+fun askToOpenSettings(open: () -> Unit) {
+ val zh = Strings.lang() == "zh"
+ val go = if (zh) "打开设置" else "Open settings"
+ val ack = if (zh) "知道了" else "Got it"
+ Thread {
+ val r = AskGate.ask(noVoiceKey(), listOf(go, ack), 60_000)
+ if (r.button == go) javax.swing.SwingUtilities.invokeLater(open)
+ }.start()
+}
+
+/**
+ * One tap on the ball, or on the chat window's microphone: "listen to me now". A meeting being recorded is
+ * ended instead. Whatever was running or being read out stops first, and the mic opens in the same tap rather
+ * than needing a second one. One function, so the two doors cannot drift apart.
+ */
+fun tapToTalk(onNoVoice: () -> Unit) {
+ when {
+ Meeting.isActive() -> Meeting.stopFromUser()
+ else -> {
+ if (Assistant.working()) Assistant.stop()
+ if (!net.kuafuai.andee.desktop.voice.MacVoice.toggle()) onNoVoice()
}
- },
+ }
+}
+
+fun ballActions(onType: () -> Unit, onNoVoice: () -> Unit) = BallActions(
+ onTap = { tapToTalk(onNoVoice) },
// Typing is a new request too: whatever was running or being read out stops first, as the tap does.
onDoubleTap = { if (Assistant.working()) Assistant.stop(); onType() },
onTripleTap = { if (Meeting.isActive()) Meeting.stopFromUser() else Assistant.stop() },
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/PaintTrace.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/PaintTrace.kt
new file mode 100644
index 0000000..3753d5a
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/PaintTrace.kt
@@ -0,0 +1,27 @@
+package net.kuafuai.andee.desktop
+
+/** Dev only (-Dandee.ballTrace): what the ball's per-frame UI-thread work costs, logged every 3 s. */
+internal object PaintTrace {
+ private var n = 0; private var sum = 0L; private var max = 0L; private var t0 = System.nanoTime()
+ @Synchronized fun record(ns: Long) {
+ n++; sum += ns; if (ns > max) max = ns
+ val now = System.nanoTime()
+ if (now - t0 > 3_000_000_000L) {
+ net.kuafuai.andee.util.Log.i("BallTrace", "frames=$n avg=${sum / n / 1000}us max=${max / 1000}us fps=${n * 1e9 / (now - t0)}")
+ n = 0; sum = 0; max = 0; t0 = now
+ }
+ }
+}
+
+/** Dev only: the render thread's own per-frame cost, split into draw / readback / flip. */
+internal object GlTrace {
+ private var n = 0; private var d = 0L; private var r = 0L; private var f = 0L; private var rMax = 0L; private var t0 = System.nanoTime()
+ @Synchronized fun record(draw: Long, read: Long, flip: Long) {
+ n++; d += draw; r += read; f += flip; if (read > rMax) rMax = read
+ val now = System.nanoTime()
+ if (now - t0 > 3_000_000_000L) {
+ net.kuafuai.andee.util.Log.i("BallTrace", "gl frames=$n draw=${d / n / 1000}us readback=${r / n / 1000}us(max ${rMax / 1000}) flip=${f / n / 1000}us")
+ n = 0; d = 0; r = 0; f = 0; rMax = 0; t0 = now
+ }
+ }
+}