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: click accuracy — a vision model finds the target, and the Mac gets the phone's guards

booboosui0c381d93606d
diff --git a/CLAUDE.md b/CLAUDE.md
index 039fdd0..956d7c2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -144,6 +144,7 @@ Ported from generic_bridge (phone.sh), whose finding is the founding rule here:
- **A cell now has fifteen parts, not nine** (`PART_COLS = 3` × `PART_ROWS = 5`, in `ScreenController.PARTS`: `top-left` … `bottom-right`). The old nine names still parse as **aliases** mapped to the outer rows, so a payload written against the previous vocabulary aims where it used to — that was deliberate, and it is why the tool text can say "nine thirds **or**, vertically, upper/lower".
- **`popup_open` / `popups` come from the window list, which survives a withheld tree.** The brain could not tell an open menu from a closed one by eye and reopened one six times; the result now carries the fact, and a blind tap *inside* a popup is refused. Prompt side: close a small menu by tapping its **opener** again, not with `back` — the menu is unfocused, so `back` left Moments entirely — and keep list progress instead of restarting from item 1.
- **The markers are magenta (`#E000FF`), not red.** Every other obvious colour is already taken by real UI (red is every unread badge in every Chinese app, and a red crosshair beside WeChat's red dot read as part of the app), and the ring is the one piece of evidence about where a tap landed. `TapMarkerUi`'s caption sits **above** the ring, not below, because below is where the next target is.
+- **`tap_target`: the brain describes, a vision model locates** (`brain/Locator.kt`, design: `docs/design/click-accuracy.zh-CN.md`). One no-tool call, on a grid-free screenshot, answering 0-1000 — **with the model the user configured for the brain, on every backend** (`locator_model` overrides; Doubao `Locator.DOUBAO` is the fast, precise choice on Ark/CodeFlying). It used to pick Doubao by address and hide the tool anywhere else, on the false assumption that only Doubao could see; measured through api.openai-next.com, `gpt-6.1-sol` was 12 px off on average (Doubao 6 px) and said "not there" correctly, just slower (5–16 s against 2 s). **Fallback, not a gate:** a 4xx (a model that takes no images) withdraws it for the run at once, three unreadable answers in a row do too, and a readable one resets the count — then the tool is gone from the list and the brain aims by grid as before. Two prompt choices are measurements: Chinese wording (English missed by 25–37 px on three targets), and `<seen>` before `<point>` (without it 「红色的删除按钮」 on a screen with none pointed at ✕). On the phone the located point counts as aimed (`tapLocated` records it as a zoom), so the blind-app zoom rule passes; the repetition guard still applies.
- `take_screenshot` downscales to **1280 on the long side** before base64 — proportions are preserved and the 0-1000 protocol is scale-invariant, so this is free token savings.
- **Stuck-loop guard**: per-location counting, not consecutive-with-no-change (the real dead-loop interleaves menu opens, wrong pages and backs, and apps emit content events constantly — both naive conditions miss it). Gestures within 120 px of each other share a bucket; within 5 minutes, the 4th tap on the same bucket is refused with an error telling the brain to stop, re-observe, and ask the user. Swipes are exempt (list scrolling legitimately repeats); e-taps are exempt (re-tapping a confirmed element is normal operation).
- **NO_TREE policy** (empty-list hint): prefer `back`/`home` to exit and retry via a different route over blind coordinate taps — a wrong exit costs one tap, a wrong tap can cost the task.
@@ -662,6 +663,7 @@ meetings, gear, friends) and lists exactly the tools some provider handles. What
character.
- **Notifications come from `usernoted`'s SQLite store, and where it is depends on the macOS version** (`notifCandidates` in `AndeeMac.swift`): macOS 15 keeps it in `~/Library/Group Containers/group.com.apple.usernoted/db2`, earlier systems under `confstr(_CS_DARWIN_USER_DIR)` + `com.apple.notificationcenter/db2` (never derive that from `$TMPDIR` — the JVM replaces it). Only the first was tried, and a store that was not there was reported as missing Full Disk Access, so the user granted it and was told the same thing forever. `andee_notif_latest_id` now answers -2 for "no store anywhere" (`State.NOT_FOUND`, no permission button) and -1 for "exists but refuses us" (`NO_ACCESS`), and reads in process through `libsqlite3` (read-only, busy timeout, since `usernoted` is writing the WAL) instead of forking `/usr/bin/sqlite3`, which swallowed the reason.
- **`type_text` pastes even when the front app reports no focused element** (`MacScreen.typeBlind`). Mac WeChat answers `focused: false` to accessibility, and refusing there sent the model to the shell (`osascript` + ⌘V), which a notification's turn may not use — so a message Andee could read, it could not answer. The blind path sends ⌘V only (no ⌘A: with focus unknown, select-all may take the chat history), refuses when Andee's own window is active, and returns `unverified` with a note to check the screenshot and not to reach for the shell. Verified in WeChat's 文件传输助手 by reading the box back with ⌘A ⌘C. The pasteboard is still not restored afterwards — that was a deliberate choice (see `andee_set_pasteboard`).
+- **A click on an inactive app only activates it, so every click brings its app forward first** (`MacScreen.click` → `andee_activate_at`; keystrokes → `andee_activate_target`). Measured 2026-10-28 in Chrome with Finder in front: one click left focus on the page (`AXWebArea`), the second focused the text box. In the trace that turned into a sidebar click that "did nothing" and a `type_text` that pasted into the page and reported success — the task stalled on a box the model concluded it "cannot type into". Not verified end-to-end after the fix (the test window was the user's live Chrome).
- **A prompt card appears beside the ball** (`PromptWindow`), which may be on a screen the user is not looking
at. A friend's request therefore plays a sound and waves the ball first — the first one timed out unseen.
diff --git a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
index 121427f..87f403d 100644
--- a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
+++ b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt
@@ -93,7 +93,14 @@ class AndroidBrainHost(
}
override fun toolLists(): List<JSONArray> = listOfNotNull(
- ToolSchemas.all(), registry.tools(), market.tools(),
+ // tap_target only where a pointing model can answer it: on a backend without one it would fail every tap.
+ ToolSchemas.subset { m ->
+ // drag is the Mac's: on the phone a swipe already is a finger moving, and there is nothing to implement.
+ m != "screen.drag" && (m != "screen.tap_target" || net.kuafuai.andee.brain.Locator.modelFor(
+ net.kuafuai.andee.config.VoiceConfig.brainConfig(ctx), net.kuafuai.andee.config.VoiceConfig.locatorModel(ctx),
+ ) != null)
+ },
+ registry.tools(), market.tools(),
// A tool that can only ever answer "nothing is paired" is a promise made to every user who never set this up.
net.kuafuai.andee.peer.PeerTasks.TOOLS.takeIf { peers.store.all().isNotEmpty() },
)
@@ -126,6 +133,7 @@ class AndroidBrainHost(
BrainText.ERROR_400 -> R.string.brain_error_400
BrainText.ERROR_402 -> R.string.brain_error_402
BrainText.ERROR_404 -> R.string.brain_error_404
+ BrainText.ERROR_MOVED -> R.string.brain_error_moved
BrainText.ERROR_429 -> R.string.brain_error_429
BrainText.ERROR_5XX -> R.string.brain_error_5xx
BrainText.ERROR_AUTH -> R.string.brain_error_auth
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 3718539..b4bbbad 100644
--- a/app/src/main/java/net/kuafuai/andee/config/VoiceConfig.kt
+++ b/app/src/main/java/net/kuafuai/andee/config/VoiceConfig.kt
@@ -856,6 +856,10 @@ object VoiceConfig {
).key
/** Bubble kinds the user long-pressed away. Written directly, like `scene`: it is a set, not a field. */
+ /** The pointing model for `tap_target`, if the user named one; blank = [net.kuafuai.andee.brain.Locator.modelFor] picks. */
+ fun locatorModel(context: Context): String =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("locator_model", "").orEmpty()
+
fun nudgeMuted(context: Context): Set<String> =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getStringSet("nudge_muted", emptySet()).orEmpty().toSet()
@@ -942,6 +946,7 @@ object VoiceConfig {
"grounding",
"notify",
"nudge",
+ "locator_model",
"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 399f9e3..5b97f75 100644
--- a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
+++ b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt
@@ -1199,6 +1199,33 @@ class CommandDispatcher(
}
}
+ // tap_target: the brain describes, a pointing model locates, the device taps. See `Locator`.
+ "screen.tap_target" -> {
+ val target = params?.optString("target")?.trim().orEmpty()
+ require(target.isNotEmpty()) { "tap_target requires target — the element to tap, described in words" }
+ val cfg = VoiceConfig.brainConfig(appContext)
+ val model = net.kuafuai.andee.brain.Locator.modelFor(cfg, VoiceConfig.locatorModel(appContext))
+ ?: throw IllegalStateException("No locating model is available on this backend. Use tap_screen_element or tap_by_coordinates (zoom first).")
+ // No grid: the lines and rulers are for an eye that counts cells, and only get in a pointing model's way.
+ val shot = blankedForCapture { requireScreen().screenshot("locate", grid = false) }
+ val png = shot.optString("png_base64").ifEmpty { throw IllegalStateException("could not take the screenshot to locate on") }
+ val loc = net.kuafuai.andee.brain.Locator(cfg, model) { warn, msg ->
+ if (warn) android.util.Log.w("Locator", msg) else android.util.Log.i("Locator", msg)
+ }.locate(png, target)
+ when (loc) {
+ is net.kuafuai.andee.brain.Locator.Result.Found -> passthroughForGesture {
+ requireScreen().tapLocated(loc.x, loc.y, target, params?.optBoolean("long", false) == true)
+ }.put("saw", loc.seen)
+ net.kuafuai.andee.brain.Locator.Result.Absent -> JSONObject().put("found", false).put("target", target).put(
+ "note",
+ "The locating model looked at the current screen and does not see this. Nothing was tapped. Look at the screen " +
+ "(take_screenshot) and describe it differently, or scroll — do not send the same words again.",
+ )
+ is net.kuafuai.andee.brain.Locator.Result.Failed -> JSONObject().put("found", false).put("target", target)
+ .put("error", loc.why).put("note", "Nothing was tapped. Fall back to tap_by_coordinates with a zoom.")
+ }
+ }
+
"screen.tap_id" -> {
// tap_screen_element: by eid from the latest element list. The old
// resource-id form is gone — WeChat nodes mostly have none,
diff --git a/app/src/main/java/net/kuafuai/andee/screen/ScreenController.kt b/app/src/main/java/net/kuafuai/andee/screen/ScreenController.kt
index 2b1b45d..9c02192 100644
--- a/app/src/main/java/net/kuafuai/andee/screen/ScreenController.kt
+++ b/app/src/main/java/net/kuafuai/andee/screen/ScreenController.kt
@@ -461,6 +461,25 @@ class ScreenController(
)
}
+ /**
+ * Tap the point the locating model found for a described target (`tap_target`, see `Locator`).
+ *
+ * It counts as aimed, which is the point of it: the tree-blind zoom rule ([requireZoomedOnBlind]), the
+ * send-after-typing rule ([requireAimedSend]) and the popup guard all exist because the BRAIN's eye was
+ * the aim, and a model trained to point, asked one question per tap, is not that eye — it was 1–8 px off
+ * on every target measured. So the point is recorded as a fresh zoom on itself, the typing mark is
+ * cleared, and the tap goes straight to [tapNorm]: the repetition guard still applies, and nothing is
+ * snapped, since the point is the model's measured answer and not a guess near a shape.
+ */
+ fun tapLocated(nx: Int, ny: Int, target: String, long: Boolean): JSONObject {
+ requireNorm(nx, "x"); requireNorm(ny, "y")
+ zoomRegion = intArrayOf((nx - 12).coerceAtLeast(0), (ny - 12).coerceAtLeast(0), (nx + 12).coerceAtMost(NORM_MAX), (ny + 12).coerceAtMost(NORM_MAX))
+ zoomAtMs = SystemClock.uptimeMillis()
+ typedBlindAt = 0L
+ val r = if (long) longPressNorm(nx, ny, 600L) else tapNorm(nx, ny)
+ return r.put("located", "$nx,$ny").put("target", target)
+ }
+
fun tapAim(on: String?, x: Int?, y: Int?, cell: String?, part: String?): JSONObject {
val a = resolveAim(on, x, y, cell, part)
val blind = treeBlind()
@@ -701,7 +720,7 @@ class ScreenController(
else "{\"cell\": \"$cell\", \"part\": \"${part.trim()}\"}"
return out.put("aimed_at", a.label).put(
"aim_check",
- "The RED CROSSHAIR is exactly where tap_by_coordinates $args would land. " +
+ "The MAGENTA CROSSHAIR is exactly where tap_by_coordinates $args would land. " +
"If it sits on the target, tap with those same arguments. If it does " +
"not, do NOT nudge the screen cell: name the lowercase cell (+ part) " +
"of THIS image where the target is, with on=\"zoom\".",
diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml
index 348cce3..02420a0 100644
--- a/app/src/main/res/values-en/strings.xml
+++ b/app/src/main/res/values-en/strings.xml
@@ -519,6 +519,7 @@
<string name="brain_error_auth">The backend refused the request (HTTP %1$d): the key is wrong, expired or disabled. Check the key in Settings → Backend, and generate a new one on the provider\'s website if needed.</string>
<string name="brain_error_400">The backend rejected the request: %1$s\nThe usual cause is a misspelled model name. Check it in Settings → Backend.</string>
<string name="brain_error_404">The backend could not find that address (HTTP 404). Check the endpoint URL and the model name in Settings → Backend.</string>
+ <string name="brain_error_moved">The backend did not answer as an API — the address may be wrong, or the service has moved (it pointed to: %1$s). Check the address in Settings → Backend; if you use CodeFlying, the problem is on the service side, and you can switch to On-device for now.</string>
<string name="brain_error_429">The backend is busy or being asked too often (HTTP 429). Say it again in a moment. If it keeps happening, check on the provider\'s website whether your quota has run out.</string>
<string name="brain_error_5xx">The backend itself is having trouble (HTTP %1$d). Your settings are not the problem. Try again in a few minutes, or check the provider\'s website for maintenance notices.</string>
<string name="brain_error_timeout">The backend took too long to answer. Check that the network is working and try again in a moment.</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 9982b74..a1c6a48 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -595,6 +595,7 @@
<string name="brain_error_auth">后端拒绝了请求(HTTP %1$d):Key 填错、过期或被停用了。到「设置」→「后端」检查 Key,必要时去服务商官网重新生成一个。</string>
<string name="brain_error_400">后端说请求有问题:%1$s\n最常见的原因是模型名写错了,到「设置」→「后端」核对一下模型名。</string>
<string name="brain_error_404">后端找不到这个地址(HTTP 404)。到「设置」→「后端」检查接口地址和模型名有没有填错。</string>
+ <string name="brain_error_moved">后端没有按接口回答,地址可能填错了,或者服务换了地址(它指向:%1$s)。到「设置」→「后端」检查地址;如果用的是 CodeFlying,这是服务那边的问题,可以先切到「本机」。</string>
<string name="brain_error_429">后端现在太忙或者请求太频繁了(HTTP 429),过一会儿再说一遍就行。如果一直这样,去服务商官网看看额度有没有用完。</string>
<string name="brain_error_5xx">后端服务自己出了问题(HTTP %1$d),不是你这边的设置有误。过几分钟再试;一直不行就去服务商官网看看是否在维护。</string>
<string name="brain_error_timeout">后端半天没有回应。先看看网络通不通,稍后再试一次。</string>
diff --git a/app/src/test/resources/golden/local_prompt.txt b/app/src/test/resources/golden/local_prompt.txt
index 9acca00..fb522bc 100644
--- a/app/src/test/resources/golden/local_prompt.txt
+++ b/app/src/test/resources/golden/local_prompt.txt
@@ -6,8 +6,8 @@ Things to keep in mind:
- Some high-security actions — bringing up a payment, entering a password — you may not be able to see, because the tablet's security policy shows you only a black frame. Ask the user to do that step for you.
- Use your device's abilities to the full. If they ask whether something looks good on them, you probably need to open the camera and interact with them live from what it captures (and if you cannot see, you may need to switch to the front camera).
- You are a thinking Andee, not a machine. If they ask you to send someone a message, you may lightly improve the wording — but broadly respect what they said.
-- Prefer get_screen_element plus tap_screen_element: it is faster, and its targeting and tapping are more accurate. Only fall back to take_screenshot + tap_by_coordinates when that does not work.
-- When you do have to aim by eye, use the grid: every screenshot carries one, labelled A1 (top-left) to H12 (bottom-right) — letters along the top edge, numbers down the left edge, nothing printed inside a cell. Follow the target's column up and its row left, and name that cell and which third of that cell it is in — {"cell": "D7", "part": "bottom-right"}; part is one of top-left, top, top-right, upper-left, upper, upper-right, center-left, center, center-right, lower-left, lower, lower-right, bottom-left, bottom, bottom-right — five rows, not three, because one row of the grid is 83 units and a third of that was 74 px, taller than the buttons you are usually aiming at; use upper/lower when the target sits between two named thirds. A cell alone is too coarse to tap with, so give the part every time unless the target fills the cell. For anything not clearly bigger than a cell — an icon, a ✕ close button, a small chip — check before you fire: call zoom_screen_region with the SAME cell and part; it returns a magnified view with a magenta crosshair exactly where that tap would land. Crosshair on the target → tap with those same arguments. Not on it → aim off that magnified image instead (its labels are lowercase; send them with on="zoom"). A wrong tap can open something you did not want; one look costs one step. Read the cell, do not measure pixels and do not rescale: the arithmetic you would otherwise do is where the misses come from.
+- Prefer get_screen_element plus tap_screen_element: it is faster, and its targeting and tapping are more accurate. For anything that has no e-number — an icon, an app that hides its elements (WeChat), a web page or canvas — use tap_target if you have it: describe the one element in words (its text or icon, and where it is) and the device finds and taps it, far more precisely than aiming by eye. Only fall back to take_screenshot + tap_by_coordinates when neither works.
+- When you do have to aim by eye (no tap_target, or it could not find the target), use the grid: every screenshot carries one, labelled A1 (top-left) to H12 (bottom-right) — letters along the top edge, numbers down the left edge, nothing printed inside a cell. Follow the target's column up and its row left, and name that cell and which third of that cell it is in — {"cell": "D7", "part": "bottom-right"}; part is one of top-left, top, top-right, upper-left, upper, upper-right, center-left, center, center-right, lower-left, lower, lower-right, bottom-left, bottom, bottom-right — five rows, not three, because one row of the grid is 83 units and a third of that was 74 px, taller than the buttons you are usually aiming at; use upper/lower when the target sits between two named thirds. A cell alone is too coarse to tap with, so give the part every time unless the target fills the cell. For anything not clearly bigger than a cell — an icon, a ✕ close button, a small chip — check before you fire: call zoom_screen_region with the SAME cell and part; it returns a magnified view with a magenta crosshair exactly where that tap would land. Crosshair on the target → tap with those same arguments. Not on it → aim off that magnified image instead (its labels are lowercase; send them with on="zoom"). A wrong tap can open something you did not want; one look costs one step. Read the cell, do not measure pixels and do not rescale: the arithmetic you would otherwise do is where the misses come from.
- For anything in a browser, prefer the Chrome on this device.
- If something needs an account, always try Google sign-in first. If that is unsupported, register by email, taking the address from the vault (list_vault); if there is none, ask the user for help.
- **A tool saying "I pressed it" is not the same as the thing being done.** Two of yours report only that much: type_text counts only if the field really holds the text, and request_permissions counts only if its `result` says granted — a request that was fired and a permission that is actually on are two different facts, and only the second one lets you carry on. After either of them, look before you carry on: confirm with the screen reader or a screenshot; if it does not match, treat it as a failure (retry at most once).
diff --git a/app/src/test/resources/golden/local_prompt_persona.txt b/app/src/test/resources/golden/local_prompt_persona.txt
index caf2528..b218de4 100644
--- a/app/src/test/resources/golden/local_prompt_persona.txt
+++ b/app/src/test/resources/golden/local_prompt_persona.txt
@@ -6,8 +6,8 @@ Things to keep in mind:
- Some high-security actions — bringing up a payment, entering a password — you may not be able to see, because the tablet's security policy shows you only a black frame. Ask the user to do that step for you.
- Use your device's abilities to the full. If they ask whether something looks good on them, you probably need to open the camera and interact with them live from what it captures (and if you cannot see, you may need to switch to the front camera).
- You are a thinking Andee, not a machine. If they ask you to send someone a message, you may lightly improve the wording — but broadly respect what they said.
-- Prefer get_screen_element plus tap_screen_element: it is faster, and its targeting and tapping are more accurate. Only fall back to take_screenshot + tap_by_coordinates when that does not work.
-- When you do have to aim by eye, use the grid: every screenshot carries one, labelled A1 (top-left) to H12 (bottom-right) — letters along the top edge, numbers down the left edge, nothing printed inside a cell. Follow the target's column up and its row left, and name that cell and which third of that cell it is in — {"cell": "D7", "part": "bottom-right"}; part is one of top-left, top, top-right, upper-left, upper, upper-right, center-left, center, center-right, lower-left, lower, lower-right, bottom-left, bottom, bottom-right — five rows, not three, because one row of the grid is 83 units and a third of that was 74 px, taller than the buttons you are usually aiming at; use upper/lower when the target sits between two named thirds. A cell alone is too coarse to tap with, so give the part every time unless the target fills the cell. For anything not clearly bigger than a cell — an icon, a ✕ close button, a small chip — check before you fire: call zoom_screen_region with the SAME cell and part; it returns a magnified view with a magenta crosshair exactly where that tap would land. Crosshair on the target → tap with those same arguments. Not on it → aim off that magnified image instead (its labels are lowercase; send them with on="zoom"). A wrong tap can open something you did not want; one look costs one step. Read the cell, do not measure pixels and do not rescale: the arithmetic you would otherwise do is where the misses come from.
+- Prefer get_screen_element plus tap_screen_element: it is faster, and its targeting and tapping are more accurate. For anything that has no e-number — an icon, an app that hides its elements (WeChat), a web page or canvas — use tap_target if you have it: describe the one element in words (its text or icon, and where it is) and the device finds and taps it, far more precisely than aiming by eye. Only fall back to take_screenshot + tap_by_coordinates when neither works.
+- When you do have to aim by eye (no tap_target, or it could not find the target), use the grid: every screenshot carries one, labelled A1 (top-left) to H12 (bottom-right) — letters along the top edge, numbers down the left edge, nothing printed inside a cell. Follow the target's column up and its row left, and name that cell and which third of that cell it is in — {"cell": "D7", "part": "bottom-right"}; part is one of top-left, top, top-right, upper-left, upper, upper-right, center-left, center, center-right, lower-left, lower, lower-right, bottom-left, bottom, bottom-right — five rows, not three, because one row of the grid is 83 units and a third of that was 74 px, taller than the buttons you are usually aiming at; use upper/lower when the target sits between two named thirds. A cell alone is too coarse to tap with, so give the part every time unless the target fills the cell. For anything not clearly bigger than a cell — an icon, a ✕ close button, a small chip — check before you fire: call zoom_screen_region with the SAME cell and part; it returns a magnified view with a magenta crosshair exactly where that tap would land. Crosshair on the target → tap with those same arguments. Not on it → aim off that magnified image instead (its labels are lowercase; send them with on="zoom"). A wrong tap can open something you did not want; one look costs one step. Read the cell, do not measure pixels and do not rescale: the arithmetic you would otherwise do is where the misses come from.
- For anything in a browser, prefer the Chrome on this device.
- If something needs an account, always try Google sign-in first. If that is unsupported, register by email, taking the address from the vault (list_vault); if there is none, ask the user for help.
- **A tool saying "I pressed it" is not the same as the thing being done.** Two of yours report only that much: type_text counts only if the field really holds the text, and request_permissions counts only if its `result` says granted — a request that was fired and a permission that is actually on are two different facts, and only the second one lets you carry on. After either of them, look before you carry on: confirm with the screen reader or a screenshot; if it does not match, treat it as a failure (retry at most once).
diff --git a/app/src/test/resources/golden/tool_schemas.json b/app/src/test/resources/golden/tool_schemas.json
index 47ab7ee..43263f2 100644
--- a/app/src/test/resources/golden/tool_schemas.json
+++ b/app/src/test/resources/golden/tool_schemas.json
@@ -33,6 +33,68 @@
"required": ["eid"]
}
},
+ {
+ "localOnly": true,
+ "method": "screen.drag",
+ "name": "drag",
+ "description": "Press at one point, move to another while holding, and release \u2014 a real drag, on the Mac. swipe_by_coordinates\nSCROLLS there; use drag when something has to be grabbed: a slider or a progress/volume bar, a splitter, a\nwindow by its title bar, a file onto a folder, a list row to reorder, a text or range selection.\n\nAim each end the way you aim a tap: `from_x`/`from_y` and `to_x`/`to_y` in 0-1000 of the screen, or describe\nit in words with `from_target` / `to_target` (resolved like tap_target \u2014 you never compute a coordinate).\nA slider's end is where its handle should END UP, not where the handle is now.\n\nThe result carries `screen_changed` and an `after_shot` with a magenta ring at the release point. Look at it:\na drag that grabbed nothing leaves the screen unchanged. Do not repeat the same drag blindly \u2014 re-aim from a\nfresh look, or use the control's own keyboard handling.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "duration_ms": {
+ "default": 700,
+ "description": "How long the move takes, 200-5000. Default 700; slower for fussy controls.",
+ "type": "integer"
+ },
+ "to_x": {
+ "description": "End x, 0-1000.",
+ "type": "integer"
+ },
+ "to_y": {
+ "description": "End y, 0-1000.",
+ "type": "integer"
+ },
+ "to_target": {
+ "description": "Where to drop it, in words (instead of to_x/to_y).",
+ "type": "string"
+ },
+ "from_target": {
+ "description": "The thing to grab, in words (instead of from_x/from_y).",
+ "type": "string"
+ },
+ "from_x": {
+ "description": "Start x, 0-1000.",
+ "type": "integer"
+ },
+ "from_y": {
+ "description": "Start y, 0-1000.",
+ "type": "integer"
+ }
+ },
+ "required": []
+ }
+ },
+ {
+ "localOnly": true,
+ "method": "screen.tap_target",
+ "name": "tap_target",
+ "description": "Tap something you can SEE but that has no e-number \u2014 an icon, a button in an app that hides its\nelement tree (WeChat), anything on a canvas, mini-program or web page \u2014 by describing it in words.\nThe device takes a fresh screenshot, a vision model trained to point finds the element, and the\ndevice taps its centre. You never give a coordinate, so nothing can be off by your arithmetic.\n\nUse it INSTEAD of tap_by_coordinates whenever there is no e-number for the target; tap_by_coordinates\nand zoom are the fallback for when this says it cannot find the target.\n\nDescribe the one element you mean so that nothing else on the screen fits: its visible text or icon,\nand where it is (\"the 发送 button right of the comment box at the bottom\", \"the 「··」 button at the\nright end of 好友3's post\", \"the red 删除 in the menu that just opened\"). Name what it looks like,\nnot what it will do. Relational words alone (\"the second one\") are where it errs most.\n\nThe result has `located` (0-1000), `saw` (what the element it tapped shows), `after_shot` with a\nmagenta ring where it tapped, and `screen_changed` where the device can tell. If `saw` is not what\nyou meant, the tap went to the wrong thing \u2014 look before you go on. `found: false` means the model looked and does not see\nit \u2014 do not repeat the same words; look at the screen and describe it differently, or scroll.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "long": {
+ "default": false,
+ "description": "Long-press (phone) / right-click (Mac) instead of a tap. Default false.",
+ "type": "boolean"
+ },
+ "target": {
+ "description": "The one element to tap, described by its visible text or icon and where it is, in any language.",
+ "type": "string"
+ }
+ },
+ "required": ["target"]
+ }
+ },
{
"method": "screen.tap",
"name": "tap_by_coordinates",
@@ -240,7 +302,7 @@
{
"method": "screen.look_region",
"name": "zoom_screen_region",
- "description": "[PRECISION AIMING · SCREEN, NOT CAMERA] Despite the method name,\nthis is a magnified capture of a screen REGION and has nothing to\ndo with the physical camera (camera_turn). A magnified look at ONE region of the screen \u2014\n4x the pixel density of a full screenshot around wherever you point.\n\nUse it to CHECK an aim before tapping anything not clearly bigger\nthan a grid cell (an icon, a ✕ close button, a small chip): pass the\ncell and part you were about to tap \u2014 {\"cell\": \"D9\", \"part\":\n\"bottom-right\"} \u2014 and you get a magnified view two cells each way,\ncentred on that point, with a RED CROSSHAIR exactly where the tap\nwould land. Crosshair on the target → tap with the same cell and\npart. Off it → aim off this image instead (below). Targets often sit\nright on a grid line; this view is centred on the aim, so they are\nnever cut in half.\n\nThe other form is x/y marking the region's CENTER plus w/h for its\nsize (try 200x300 for one control, 400x600 for a card) \u2014 a plain\nmagnified look, no crosshair. All four are 0-1000 of the WHOLE SCREEN,\nnever pixels of an image you were shown: a screenshot arrives\ndownscaled (often ~576 wide as you see it), so a position measured in\nits pixels is the wrong number here. Read the position off the grid\ninstead \u2014 cell D is 375-500 across, row 7 is 500-583 down, each column\n125 wide and each row ~83 tall \u2014 or simply use the cell form above,\nwhich needs no numbers at all. Every zoom reports the screen rectangle\nit actually showed (`region`); if that is not where you meant to look,\nyour numbers were in the wrong space.\n\nThis image is a magnified region, and it carries the SAME 8x12 grid in\nLOWERCASE (a1..h12), labels at each cell's centre, so a label read off\nit can never be confused with a cell of the full screen. Aim your tap\nstraight from one of those labels: {\"cell\": \"d7\", \"part\": \"top\",\n\"on\": \"zoom\"} on tap_by_coordinates, and the device\nconverts it \u2014 no arithmetic. (The old route still works and is\nequivalent: the response carries the region's screen bounds and\nscale_x/scale_y, and a point (px,py) read off the image maps to\nscreen-relative (region.left + px/scale_x, region.top + py/scale_y).)\n\nAfter a tap that reported screen_changed=false, its miss_shot field\nis exactly this \u2014 aim your retry from that image.",
+ "description": "[PRECISION AIMING · SCREEN, NOT CAMERA] Despite the method name,\nthis is a magnified capture of a screen REGION and has nothing to\ndo with the physical camera (camera_turn). A magnified look at ONE region of the screen \u2014\n4x the pixel density of a full screenshot around wherever you point.\n\nUse it to CHECK an aim before tapping anything not clearly bigger\nthan a grid cell (an icon, a ✕ close button, a small chip): pass the\ncell and part you were about to tap \u2014 {\"cell\": \"D9\", \"part\":\n\"bottom-right\"} \u2014 and you get a magnified view two cells each way,\ncentred on that point, with a MAGENTA CROSSHAIR exactly where the tap\nwould land. Crosshair on the target → tap with the same cell and\npart. Off it → aim off this image instead (below). Targets often sit\nright on a grid line; this view is centred on the aim, so they are\nnever cut in half.\n\nThe other form is x/y marking the region's CENTER plus w/h for its\nsize (try 200x300 for one control, 400x600 for a card) \u2014 a plain\nmagnified look, no crosshair. All four are 0-1000 of the WHOLE SCREEN,\nnever pixels of an image you were shown: a screenshot arrives\ndownscaled (often ~576 wide as you see it), so a position measured in\nits pixels is the wrong number here. Read the position off the grid\ninstead \u2014 cell D is 375-500 across, row 7 is 500-583 down, each column\n125 wide and each row ~83 tall \u2014 or simply use the cell form above,\nwhich needs no numbers at all. Every zoom reports the screen rectangle\nit actually showed (`region`); if that is not where you meant to look,\nyour numbers were in the wrong space.\n\nThis image is a magnified region, and it carries the SAME 8x12 grid in\nLOWERCASE (a1..h12), letters along the top edge and numbers down the left\nlike a map's rulers, so a label read off\nit can never be confused with a cell of the full screen. Aim your tap\nstraight from one of those labels: {\"cell\": \"d7\", \"part\": \"top\",\n\"on\": \"zoom\"} on tap_by_coordinates, and the device\nconverts it \u2014 no arithmetic. (The old route still works and is\nequivalent: the response carries the region's screen bounds and\nscale_x/scale_y, and a point (px,py) read off the image maps to\nscreen-relative (region.left + px/scale_x, region.top + py/scale_y).)\n\nAfter a tap that reported screen_changed=false, its miss_shot field\nis exactly this \u2014 aim your retry from that image.",
"parameters": {
"type": "object",
"properties": {
diff --git a/app/src/test/resources/golden/tool_schemas_hub.json b/app/src/test/resources/golden/tool_schemas_hub.json
index 1557a15..adb685f 100644
--- a/app/src/test/resources/golden/tool_schemas_hub.json
+++ b/app/src/test/resources/golden/tool_schemas_hub.json
@@ -240,7 +240,7 @@
{
"method": "screen.look_region",
"name": "zoom_screen_region",
- "description": "[PRECISION AIMING · SCREEN, NOT CAMERA] Despite the method name,\nthis is a magnified capture of a screen REGION and has nothing to\ndo with the physical camera (camera_turn). A magnified look at ONE region of the screen \u2014\n4x the pixel density of a full screenshot around wherever you point.\n\nUse it to CHECK an aim before tapping anything not clearly bigger\nthan a grid cell (an icon, a ✕ close button, a small chip): pass the\ncell and part you were about to tap \u2014 {\"cell\": \"D9\", \"part\":\n\"bottom-right\"} \u2014 and you get a magnified view two cells each way,\ncentred on that point, with a RED CROSSHAIR exactly where the tap\nwould land. Crosshair on the target → tap with the same cell and\npart. Off it → aim off this image instead (below). Targets often sit\nright on a grid line; this view is centred on the aim, so they are\nnever cut in half.\n\nThe other form is x/y marking the region's CENTER plus w/h for its\nsize (try 200x300 for one control, 400x600 for a card) \u2014 a plain\nmagnified look, no crosshair. All four are 0-1000 of the WHOLE SCREEN,\nnever pixels of an image you were shown: a screenshot arrives\ndownscaled (often ~576 wide as you see it), so a position measured in\nits pixels is the wrong number here. Read the position off the grid\ninstead \u2014 cell D is 375-500 across, row 7 is 500-583 down, each column\n125 wide and each row ~83 tall \u2014 or simply use the cell form above,\nwhich needs no numbers at all. Every zoom reports the screen rectangle\nit actually showed (`region`); if that is not where you meant to look,\nyour numbers were in the wrong space.\n\nThis image is a magnified region, and it carries the SAME 8x12 grid in\nLOWERCASE (a1..h12), labels at each cell's centre, so a label read off\nit can never be confused with a cell of the full screen. Aim your tap\nstraight from one of those labels: {\"cell\": \"d7\", \"part\": \"top\",\n\"on\": \"zoom\"} on tap_by_coordinates, and the device\nconverts it \u2014 no arithmetic. (The old route still works and is\nequivalent: the response carries the region's screen bounds and\nscale_x/scale_y, and a point (px,py) read off the image maps to\nscreen-relative (region.left + px/scale_x, region.top + py/scale_y).)\n\nAfter a tap that reported screen_changed=false, its miss_shot field\nis exactly this \u2014 aim your retry from that image.",
+ "description": "[PRECISION AIMING · SCREEN, NOT CAMERA] Despite the method name,\nthis is a magnified capture of a screen REGION and has nothing to\ndo with the physical camera (camera_turn). A magnified look at ONE region of the screen \u2014\n4x the pixel density of a full screenshot around wherever you point.\n\nUse it to CHECK an aim before tapping anything not clearly bigger\nthan a grid cell (an icon, a ✕ close button, a small chip): pass the\ncell and part you were about to tap \u2014 {\"cell\": \"D9\", \"part\":\n\"bottom-right\"} \u2014 and you get a magnified view two cells each way,\ncentred on that point, with a MAGENTA CROSSHAIR exactly where the tap\nwould land. Crosshair on the target → tap with the same cell and\npart. Off it → aim off this image instead (below). Targets often sit\nright on a grid line; this view is centred on the aim, so they are\nnever cut in half.\n\nThe other form is x/y marking the region's CENTER plus w/h for its\nsize (try 200x300 for one control, 400x600 for a card) \u2014 a plain\nmagnified look, no crosshair. All four are 0-1000 of the WHOLE SCREEN,\nnever pixels of an image you were shown: a screenshot arrives\ndownscaled (often ~576 wide as you see it), so a position measured in\nits pixels is the wrong number here. Read the position off the grid\ninstead \u2014 cell D is 375-500 across, row 7 is 500-583 down, each column\n125 wide and each row ~83 tall \u2014 or simply use the cell form above,\nwhich needs no numbers at all. Every zoom reports the screen rectangle\nit actually showed (`region`); if that is not where you meant to look,\nyour numbers were in the wrong space.\n\nThis image is a magnified region, and it carries the SAME 8x12 grid in\nLOWERCASE (a1..h12), letters along the top edge and numbers down the left\nlike a map's rulers, so a label read off\nit can never be confused with a cell of the full screen. Aim your tap\nstraight from one of those labels: {\"cell\": \"d7\", \"part\": \"top\",\n\"on\": \"zoom\"} on tap_by_coordinates, and the device\nconverts it \u2014 no arithmetic. (The old route still works and is\nequivalent: the response carries the region's screen bounds and\nscale_x/scale_y, and a point (px,py) read off the image maps to\nscreen-relative (region.left + px/scale_x, region.top + py/scale_y).)\n\nAfter a tap that reported screen_changed=false, its miss_shot field\nis exactly this \u2014 aim your retry from that image.",
"parameters": {
"type": "object",
"properties": {
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 e0217b9..17ac50a 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/BrainHost.kt
@@ -159,6 +159,7 @@ enum class BrainText {
ERROR_400,
ERROR_402,
ERROR_404,
+ ERROR_MOVED,
ERROR_429,
ERROR_5XX,
ERROR_AUTH,
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/LlmClient.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/LlmClient.kt
index 2f7e498..99d8331 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/LlmClient.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/LlmClient.kt
@@ -14,6 +14,13 @@ import java.util.concurrent.TimeUnit
* sentence the user can act on; this class has none and must not grow one.
* The message stays `LLM HTTP <code>: <body>` so logs read as they always did.
*/
+/**
+ * The backend address answered with something other than the API: a redirect, or a page that is not JSON. The
+ * address is wrong or the service moved; [where] is where it pointed, [sample] what came back instead.
+ */
+class LlmMovedException(val code: Int, val where: String, val sample: String = "") :
+ IllegalStateException("the backend did not answer as an API (HTTP $code${if (where.isNotEmpty()) " → $where" else ""}${if (sample.isNotEmpty()) ": $sample" else ""})")
+
class LlmHttpException(val code: Int, val body: String) :
IllegalStateException("LLM HTTP $code: ${body.take(600)}") {
@@ -88,6 +95,12 @@ class LlmClient(
* network should say so quickly.
*/
private val http = OkHttpClient.Builder()
+ // Never follow a redirect. OkHttp turns a POST that meets a 301 into a GET of the new address, which on a
+ // moved gateway is a web page: the turn then died on "A JSONObject text must begin with '{'", which tells
+ // nobody anything (measured 2026-10-28: codeflying.net → www.codeflying.net, an nginx page). A redirect
+ // here is an address that is wrong or has moved, and it is reported as that — see [LlmMovedException].
+ .followRedirects(false)
+ .followSslRedirects(false)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(180, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
@@ -173,6 +186,9 @@ class LlmClient(
// and a bare "HTTP 400" sends whoever is debugging to the wrong
// place entirely.
val raw = resp.body?.string().orEmpty()
+ if (resp.code in 300..399) {
+ throw LlmMovedException(resp.code, resp.header("Location").orEmpty())
+ }
if (!resp.isSuccessful) {
throw LlmHttpException(resp.code, raw)
}
@@ -182,7 +198,10 @@ class LlmClient(
current = null
}
- val root = JSONObject(text)
+ // A 200 that is not JSON is a web server answering where the API should: a proxy page, a login wall.
+ val root = runCatching { JSONObject(text) }.getOrElse {
+ throw LlmMovedException(200, "", text.trim().take(80).replace(Regex("\\s+"), " "))
+ }
val choice = root.optJSONArray("choices")?.optJSONObject(0)
?: throw IllegalStateException("LLM reply has no choices: ${text.take(400)}")
val msg = choice.optJSONObject("message")
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 a47d5fe..f5b5f98 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalBrain.kt
@@ -545,6 +545,7 @@ class LocalBrain(
private fun explainFailure(t: Throwable): String {
fun s(id: BrainText, vararg args: Any) = host.text(id, *args)
+ if (t is LlmMovedException) return s(BrainText.ERROR_MOVED, t.where.ifEmpty { "HTTP ${t.code}" })
if (t is LlmHttpException) {
return when (t.code) {
402 -> s(BrainText.ERROR_402)
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalPrompt.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalPrompt.kt
index d733aa3..42c3ee9 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/brain/LocalPrompt.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/LocalPrompt.kt
@@ -106,8 +106,8 @@ Things to keep in mind:
- Some high-security actions — bringing up a payment, entering a password — you may not be able to see, because the tablet's security policy shows you only a black frame. Ask the user to do that step for you.
- Use your device's abilities to the full. If they ask whether something looks good on them, you probably need to open the camera and interact with them live from what it captures (and if you cannot see, you may need to switch to the front camera).
- You are a thinking Andee, not a machine. If they ask you to send someone a message, you may lightly improve the wording — but broadly respect what they said.
-- Prefer get_screen_element plus tap_screen_element: it is faster, and its targeting and tapping are more accurate. Only fall back to take_screenshot + tap_by_coordinates when that does not work.
-- When you do have to aim by eye, use the grid: every screenshot carries one, labelled A1 (top-left) to H12 (bottom-right) — letters along the top edge, numbers down the left edge, nothing printed inside a cell. Follow the target's column up and its row left, and name that cell and which third of that cell it is in — {"cell": "D7", "part": "bottom-right"}; part is one of top-left, top, top-right, upper-left, upper, upper-right, center-left, center, center-right, lower-left, lower, lower-right, bottom-left, bottom, bottom-right — five rows, not three, because one row of the grid is 83 units and a third of that was 74 px, taller than the buttons you are usually aiming at; use upper/lower when the target sits between two named thirds. A cell alone is too coarse to tap with, so give the part every time unless the target fills the cell. For anything not clearly bigger than a cell — an icon, a ✕ close button, a small chip — check before you fire: call zoom_screen_region with the SAME cell and part; it returns a magnified view with a magenta crosshair exactly where that tap would land. Crosshair on the target → tap with those same arguments. Not on it → aim off that magnified image instead (its labels are lowercase; send them with on="zoom"). A wrong tap can open something you did not want; one look costs one step. Read the cell, do not measure pixels and do not rescale: the arithmetic you would otherwise do is where the misses come from.
+- Prefer get_screen_element plus tap_screen_element: it is faster, and its targeting and tapping are more accurate. For anything that has no e-number — an icon, an app that hides its elements (WeChat), a web page or canvas — use tap_target if you have it: describe the one element in words (its text or icon, and where it is) and the device finds and taps it, far more precisely than aiming by eye. Only fall back to take_screenshot + tap_by_coordinates when neither works.
+- When you do have to aim by eye (no tap_target, or it could not find the target), use the grid: every screenshot carries one, labelled A1 (top-left) to H12 (bottom-right) — letters along the top edge, numbers down the left edge, nothing printed inside a cell. Follow the target's column up and its row left, and name that cell and which third of that cell it is in — {"cell": "D7", "part": "bottom-right"}; part is one of top-left, top, top-right, upper-left, upper, upper-right, center-left, center, center-right, lower-left, lower, lower-right, bottom-left, bottom, bottom-right — five rows, not three, because one row of the grid is 83 units and a third of that was 74 px, taller than the buttons you are usually aiming at; use upper/lower when the target sits between two named thirds. A cell alone is too coarse to tap with, so give the part every time unless the target fills the cell. For anything not clearly bigger than a cell — an icon, a ✕ close button, a small chip — check before you fire: call zoom_screen_region with the SAME cell and part; it returns a magnified view with a magenta crosshair exactly where that tap would land. Crosshair on the target → tap with those same arguments. Not on it → aim off that magnified image instead (its labels are lowercase; send them with on="zoom"). A wrong tap can open something you did not want; one look costs one step. Read the cell, do not measure pixels and do not rescale: the arithmetic you would otherwise do is where the misses come from.
- For anything in a browser, prefer the Chrome on this device.
- If something needs an account, always try Google sign-in first. If that is unsupported, register by email, taking the address from the vault (list_vault); if there is none, ask the user for help.
- **A tool saying "I pressed it" is not the same as the thing being done.** Two of yours report only that much: type_text counts only if the field really holds the text, and request_permissions counts only if its `result` says granted — a request that was fired and a permission that is actually on are two different facts, and only the second one lets you carry on. After either of them, look before you carry on: confirm with the screen reader or a screenshot; if it does not match, treat it as a failure (retry at most once).
diff --git a/core/src/main/kotlin/net/kuafuai/andee/brain/Locator.kt b/core/src/main/kotlin/net/kuafuai/andee/brain/Locator.kt
new file mode 100644
index 0000000..763612b
--- /dev/null
+++ b/core/src/main/kotlin/net/kuafuai/andee/brain/Locator.kt
@@ -0,0 +1,143 @@
+package net.kuafuai.andee.brain
+
+import net.kuafuai.andee.config.BrainConfig
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.concurrent.ConcurrentHashMap
+
+/**
+ * Turns "the 发送 button under the comment box" into a point on a screenshot — the grounding half of a
+ * planner/grounder split. The brain says *what* to tap; this says *where*.
+ *
+ * Why it exists: the brain is a general model, and general models place points badly. Measured on the Mac
+ * traces (Oct 2026): e-number taps worked ~80% of the time, zoom-aimed coordinate taps ~43%, unaimed ones
+ * under 10%, and at least five misses were the model doing pixel→0-1000 arithmetic wrong. The literature says
+ * the same (GPT-4o 0.8 on ScreenSpot-Pro, specialists 50–74). A model trained to point, asked one question
+ * per tap, was 1–8 px off on every one of seven targets in our own phone screenshots, toolbar icons included.
+ *
+ * One call, no tools, thinking off: a grounding question is not a reasoning question.
+ *
+ * Which model: [modelFor]. The default is the Doubao Seed vision model on Volcengine Ark, because that is the
+ * platform the brain already uses on these devices — same key, no second account. A backend that cannot
+ * serve it (a gateway that does not forward it, a key not activated for it) is remembered as [unavailable]
+ * for the rest of the process, so the tool disappears instead of failing on every tap.
+ */
+class Locator(cfg: BrainConfig, private val model: String, private val log: (warn: Boolean, msg: String) -> Unit = { _, _ -> }) {
+
+ sealed class Result {
+ /** The target's centre, 0-1000 of the image, and what the model says that element shows. */
+ data class Found(val x: Int, val y: Int, val seen: String = "") : Result()
+ /** The model looked and says it is not on this screen. */
+ object Absent : Result()
+ /** No answer: the call failed or the reply was unreadable. */
+ data class Failed(val why: String) : Result()
+ }
+
+ private val key = cfg.baseUrl
+ private val llm = LlmClient(baseUrl = cfg.baseUrl, apiKey = cfg.apiKey, model = model, thinking = false, reasoningEffort = "low")
+
+ /** Blocks for one model call (~2 s). [pngBase64] is the screenshot exactly as captured, no grid on it. */
+ fun locate(pngBase64: String, target: String): Result {
+ val messages = listOf(
+ JSONObject().put("role", "user").put(
+ "content",
+ JSONArray()
+ .put(JSONObject().put("type", "image_url").put("image_url", JSONObject().put("url", "data:image/png;base64,$pngBase64")))
+ .put(JSONObject().put("type", "text").put("text", prompt(target))),
+ ),
+ )
+ val reply = try {
+ llm.complete(messages, JSONArray(), noThinking = true)
+ } catch (e: LlmHttpException) {
+ // A model this backend does not serve, or one that cannot take an image: not going to change this run.
+ if (e.code in setOf(400, 401, 403, 404, 415, 422)) withdraw("HTTP ${e.code}")
+ else failed("HTTP ${e.code}")
+ return Result.Failed("the locating model answered HTTP ${e.code}")
+ } catch (t: Throwable) {
+ failed(t.message ?: "no answer")
+ return Result.Failed(t.message ?: "the locating call failed")
+ }
+ val raw = reply.content.trim()
+ log(false, "locate \"${target.take(60)}\" → ${raw.take(80)} (tokens ${reply.promptTokens}/${reply.completionTokens})")
+ val r = parse(raw)
+ // A readable answer — a point or "not there" — is a working locator. Only unreadable ones count against it.
+ if (r is Result.Failed) failed(r.why) else misses.remove(slot)
+ return r
+ }
+
+ private val slot get() = key + "|" + model
+
+ /** Take the tool away for the rest of this run; the brain falls back to zoom-and-aim. */
+ private fun withdraw(why: String) {
+ unavailable[slot] = true
+ log(true, "locator unavailable with $model ($why); tap_target is withdrawn for this run and the brain aims by grid again")
+ }
+
+ /** Three unreadable or failed answers in a row withdraw it too: a slow tool that never works is worse than none. */
+ private fun failed(why: String) {
+ log(true, "locate failed: $why")
+ if (misses.merge(slot, 1, Int::plus)!! >= MAX_MISSES) withdraw("$MAX_MISSES failures in a row")
+ }
+
+ companion object {
+ /** What `locator_model` can be set to for the fastest and most precise answers, on Ark or the CodeFlying gateway. */
+ const val DOUBAO = "doubao-seed-2-1-lite-260915"
+
+ private val unavailable = ConcurrentHashMap<String, Boolean>()
+ private val misses = ConcurrentHashMap<String, Int>()
+ private const val MAX_MISSES = 3
+
+ /**
+ * The model to locate with: [override] (the `locator_model` setting) if there is one, otherwise **the
+ * model the user configured for the brain**, on every backend alike. Null only without a key, or once
+ * this model has been withdrawn for the run (see [withdraw]) — and then the brain aims by grid as before.
+ *
+ * One rule instead of "Doubao on Ark, nothing elsewhere": the first version picked a model by address and
+ * hid the tool on any backend it did not recognise, on the assumption that only Doubao could see. Current
+ * models are multimodal; measured through api.openai-next.com, `gpt-6.1-sol` averaged 12 px off on our
+ * screenshots (worst 45) and answered "not there" for things that were not — against Doubao's 6 px, which
+ * stays reachable as `locator_model` for anyone who wants the speed (2 s against 5–16 s).
+ */
+ fun modelFor(cfg: BrainConfig, override: String): String? {
+ if (cfg.apiKey.isEmpty()) return null
+ val m = override.trim().ifEmpty { cfg.model }
+ return m.takeIf { it.isNotBlank() && unavailable[cfg.baseUrl + "|" + it] != true }
+ }
+
+ /**
+ * Two things in it were measured, on our own phone screenshots with the default model:
+ *
+ * * **Chinese, whatever language the target is in.** The same twelve targets averaged 6.4 px off (worst
+ * 24) in Chinese; the English wording missed by 25–37 px on three of them.
+ * * **Say what you see before you point.** Asked bare, "红色的删除按钮" on a screen that had none came
+ * back as the ✕ close button — a confident point at something that does a similar job, which in a
+ * real app is the dangerous kind of miss. Made to name the element first (`<seen>`) and to check the
+ * description against it, the same question answered <none/>, every positive still landed, and it
+ * costs ~16 output tokens. The `seen` text also goes back to the brain with the tap.
+ */
+ fun prompt(target: String): String =
+ "这是一张屏幕截图。要找的界面元素:「${target.trim()}」。\n" +
+ "先用一句话写出截图上最符合的那个元素实际显示的文字或图标(<seen>…</seen>),再判断它是不是要找的元素:" +
+ "描述里提到的文字、颜色或图标在它身上都能对上,才算是。是,就输出 <point>x y</point>(中心点,x、y 是相对图片宽高的 0-1000 归一化坐标);" +
+ "不是或截图里没有,就输出 <none/>。不要把只是作用相近的东西当成它(比如不要把「关闭」当成「删除」)。"
+
+ /** `<point>x y</point>`, or a `<bbox>x1 y1 x2 y2</bbox>` (its centre), or `<none/>`; `<seen>` rides along. */
+ fun parse(raw: String): Result {
+ val seen = Regex("""<seen>(.*?)</seen>""", RegexOption.DOT_MATCHES_ALL).find(raw)?.groupValues?.get(1)?.trim()?.take(60).orEmpty()
+ // A point wins over a stray <none/>: the model sometimes writes both while it reasons, and a point is a commitment.
+ val hasPoint = raw.contains("<point>") || raw.contains("<bbox>")
+ if (!hasPoint && Regex("""<none\s*/?>""", RegexOption.IGNORE_CASE).containsMatchIn(raw)) return Result.Absent
+ Regex("""<point>\s*\(?\s*(\d{1,4})\s*[, ]\s*(\d{1,4})\s*\)?\s*</point>""").find(raw)?.let {
+ return found(it.groupValues[1].toInt(), it.groupValues[2].toInt(), raw, seen)
+ }
+ Regex("""<bbox>\s*(\d{1,4})[ ,]+(\d{1,4})[ ,]+(\d{1,4})[ ,]+(\d{1,4})\s*</bbox>""").find(raw)?.let {
+ val (a, b, c, d) = it.destructured
+ return found((a.toInt() + c.toInt()) / 2, (b.toInt() + d.toInt()) / 2, raw, seen)
+ }
+ return Result.Failed("the locating model did not answer with a point: ${raw.take(60)}")
+ }
+
+ private fun found(x: Int, y: Int, raw: String, seen: String): Result =
+ if (x in 0..1000 && y in 0..1000) Result.Found(x, y, seen) else Result.Failed("point outside 0-1000: ${raw.take(40)}")
+ }
+}
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 796754b..d201947 100644
--- a/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
+++ b/core/src/main/kotlin/net/kuafuai/andee/net/ToolSchemas.kt
@@ -192,6 +192,61 @@ object ToolSchemas {
"eid" to prop("string", "Element number from the latest get_screen_element list, e.g. \"e7\"."),
),
),
+ tool(
+ localOnly = true,
+ name = "drag",
+ method = "screen.drag",
+ description = """
+ Press at one point, move to another while holding, and release — a real drag, on the Mac. swipe_by_coordinates
+ SCROLLS there; use drag when something has to be grabbed: a slider or a progress/volume bar, a splitter, a
+ window by its title bar, a file onto a folder, a list row to reorder, a text or range selection.
+
+ Aim each end the way you aim a tap: `from_x`/`from_y` and `to_x`/`to_y` in 0-1000 of the screen, or describe
+ it in words with `from_target` / `to_target` (resolved like tap_target — you never compute a coordinate).
+ A slider's end is where its handle should END UP, not where the handle is now.
+
+ The result carries `screen_changed` and an `after_shot` with a magenta ring at the release point. Look at it:
+ a drag that grabbed nothing leaves the screen unchanged. Do not repeat the same drag blindly — re-aim from a
+ fresh look, or use the control's own keyboard handling.
+ """.trimIndent(),
+ required = emptyList(),
+ props = mapOf(
+ "from_x" to prop("integer", "Start x, 0-1000."), "from_y" to prop("integer", "Start y, 0-1000."),
+ "to_x" to prop("integer", "End x, 0-1000."), "to_y" to prop("integer", "End y, 0-1000."),
+ "from_target" to prop("string", "The thing to grab, in words (instead of from_x/from_y)."),
+ "to_target" to prop("string", "Where to drop it, in words (instead of to_x/to_y)."),
+ "duration_ms" to prop("integer", "How long the move takes, 200-5000. Default 700; slower for fussy controls.", default = 700),
+ ),
+ ),
+ tool(
+ localOnly = true,
+ name = "tap_target",
+ method = "screen.tap_target",
+ description = """
+ Tap something you can SEE but that has no e-number — an icon, a button in an app that hides its
+ element tree (WeChat), anything on a canvas, mini-program or web page — by describing it in words.
+ The device takes a fresh screenshot, a vision model trained to point finds the element, and the
+ device taps its centre. You never give a coordinate, so nothing can be off by your arithmetic.
+
+ Use it INSTEAD of tap_by_coordinates whenever there is no e-number for the target; tap_by_coordinates
+ and zoom are the fallback for when this says it cannot find the target.
+
+ Describe the one element you mean so that nothing else on the screen fits: its visible text or icon,
+ and where it is ("the 发送 button right of the comment box at the bottom", "the 「··」 button at the
+ right end of 好友3's post", "the red 删除 in the menu that just opened"). Name what it looks like,
+ not what it will do. Relational words alone ("the second one") are where it errs most.
+
+ The result has `located` (0-1000), `saw` (what the element it tapped shows), `after_shot` with a
+ magenta ring where it tapped, and `screen_changed` where the device can tell. If `saw` is not what
+ you meant, the tap went to the wrong thing — look before you go on. `found: false` means the model looked and does not see
+ it — do not repeat the same words; look at the screen and describe it differently, or scroll.
+ """.trimIndent(),
+ required = listOf("target"),
+ props = mapOf(
+ "target" to prop("string", "The one element to tap, described by its visible text or icon and where it is, in any language."),
+ "long" to prop("boolean", "Long-press (phone) / right-click (Mac) instead of a tap. Default false.", default = false),
+ ),
+ ),
tool(
name = "tap_by_coordinates",
method = "screen.tap",
@@ -328,7 +383,7 @@ object ToolSchemas {
than a grid cell (an icon, a ✕ close button, a small chip): pass the
cell and part you were about to tap — {"cell": "D9", "part":
"bottom-right"} — and you get a magnified view two cells each way,
- centred on that point, with a RED CROSSHAIR exactly where the tap
+ centred on that point, with a MAGENTA CROSSHAIR exactly where the tap
would land. Crosshair on the target → tap with the same cell and
part. Off it → aim off this image instead (below). Targets often sit
right on a grid line; this view is centred on the aim, so they are
@@ -347,7 +402,8 @@ object ToolSchemas {
your numbers were in the wrong space.
This image is a magnified region, and it carries the SAME 8x12 grid in
- LOWERCASE (a1..h12), labels at each cell's centre, so a label read off
+ LOWERCASE (a1..h12), letters along the top edge and numbers down the left
+ like a map's rulers, so a label read off
it can never be confused with a cell of the full screen. Aim your tap
straight from one of those labels: {"cell": "d7", "part": "top",
"on": "zoom"} on tap_by_coordinates, and the device
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/LlmClientMovedTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/LlmClientMovedTest.kt
new file mode 100644
index 0000000..1443684
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/LlmClientMovedTest.kt
@@ -0,0 +1,51 @@
+package net.kuafuai.andee.brain
+
+import com.sun.net.httpserver.HttpServer
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+import java.net.InetSocketAddress
+
+/** 2026-10-28: a gateway that moved answered a POST with 301 → an nginx page, and the turn died on a JSON parse error. */
+class LlmClientMovedTest {
+
+ private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
+ createContext("/moved/chat/completions") { ex ->
+ ex.responseHeaders.add("Location", "https://www.example.net/voice/llm/chat/completions")
+ ex.sendResponseHeaders(301, -1); ex.close()
+ }
+ createContext("/page/chat/completions") { ex ->
+ val b = "<html><body>welcome</body></html>".toByteArray()
+ ex.sendResponseHeaders(200, b.size.toLong()); ex.responseBody.use { it.write(b) }
+ }
+ start()
+ }
+
+ @After fun stop() = server.stop(0)
+
+ private fun call(path: String): LlmMovedException {
+ val c = LlmClient("http://127.0.0.1:${server.address.port}/$path", "k", "m", false, "low")
+ try {
+ c.complete(listOf(JSONObject().put("role", "user").put("content", "hi")), JSONArray())
+ } catch (e: LlmMovedException) {
+ return e
+ }
+ fail("no LlmMovedException"); throw AssertionError()
+ }
+
+ @Test fun aRedirectIsReportedWithWhereItPointed() {
+ val e = call("moved")
+ assertEquals(301, e.code)
+ assertEquals("https://www.example.net/voice/llm/chat/completions", e.where)
+ }
+
+ @Test fun aWebPageIsReportedAsNotTheApi() {
+ val e = call("page")
+ assertEquals(200, e.code)
+ assertTrue(e.sample.startsWith("<html>"))
+ }
+}
diff --git a/core/src/test/kotlin/net/kuafuai/andee/brain/LocatorTest.kt b/core/src/test/kotlin/net/kuafuai/andee/brain/LocatorTest.kt
new file mode 100644
index 0000000..032aebc
--- /dev/null
+++ b/core/src/test/kotlin/net/kuafuai/andee/brain/LocatorTest.kt
@@ -0,0 +1,91 @@
+package net.kuafuai.andee.brain
+
+import net.kuafuai.andee.config.BrainConfig
+import org.junit.Assert.assertEquals
+import com.sun.net.httpserver.HttpServer
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.net.InetSocketAddress
+
+class LocatorTest {
+
+ @Test fun readsAPoint() {
+ assertEquals(Locator.Result.Found(384, 741), Locator.parse("<point>384 741</point>"))
+ assertEquals(Locator.Result.Found(384, 741), Locator.parse("好的 <point>(384,741)</point>"))
+ assertEquals(Locator.Result.Found(894, 900, "↑"), Locator.parse("<seen>↑</seen>\n<point>894 900</point>"))
+ }
+
+ @Test fun readsTheCentreOfABox() {
+ assertEquals(Locator.Result.Found(150, 250), Locator.parse("<bbox>100 200 200 300</bbox>"))
+ }
+
+ @Test fun noneIsAbsentNotAGuess() {
+ assertEquals(Locator.Result.Absent, Locator.parse("<none/>"))
+ assertEquals(Locator.Result.Absent, Locator.parse("<none>"))
+ assertEquals(Locator.Result.Absent, Locator.parse("<seen>✕ 关闭图标</seen> 不是删除。<none/>"))
+ }
+
+ @Test fun anythingElseFails() {
+ assertTrue(Locator.parse("在右上角") is Locator.Result.Failed)
+ assertTrue(Locator.parse("<point>1384 741</point>") is Locator.Result.Failed)
+ }
+
+ private fun cfg(url: String, mode: String = BrainConfig.BRAIN_LOCAL, key: String = "k") = BrainConfig(mode, key, url, "m", false, "low")
+
+ @Test fun theConfiguredModelEverywhereUnlessOverridden() {
+ // cfg() names the brain's model "m"; the backend does not matter.
+ for (url in listOf("https://ark.cn-beijing.volces.com/api/v3", "https://api.deepseek.com", "https://api.openai-next.com/v1")) {
+ assertEquals("m", Locator.modelFor(cfg(url), ""))
+ }
+ assertEquals("m", Locator.modelFor(cfg("https://x/voice/llm", BrainConfig.BRAIN_CODEFLYING), ""))
+ assertEquals(Locator.DOUBAO, Locator.modelFor(cfg("https://api.deepseek.com"), Locator.DOUBAO))
+ assertNull(Locator.modelFor(cfg("https://ark.cn-beijing.volces.com/api/v3", key = ""), ""))
+ }
+
+ // ---- falling back ----
+
+ private fun serve(vararg replies: Pair<Int, String>): Pair<HttpServer, String> {
+ var n = 0
+ val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
+ createContext("/v1/chat/completions") { ex ->
+ val (code, body) = replies[minOf(n++, replies.lastIndex)]
+ val b = body.toByteArray()
+ ex.sendResponseHeaders(code, b.size.toLong()); ex.responseBody.use { it.write(b) }
+ }
+ start()
+ }
+ return server to "http://127.0.0.1:${server.address.port}/v1"
+ }
+
+ private fun answer(text: String) = 200 to """{"choices":[{"message":{"role":"assistant","content":${org.json.JSONObject.quote(text)}}}],"usage":{}}"""
+
+ @Test fun aModelThatCannotTakeImagesIsWithdrawnAtOnce() {
+ val (srv, url) = serve(400 to """{"error":{"message":"image input is not supported"}}""")
+ try {
+ val c = cfg(url)
+ val model = "no-vision-1"
+ assertEquals(model, Locator.modelFor(c, model))
+ assertTrue(Locator(c, model).locate("AAAA", "发送") is Locator.Result.Failed)
+ assertNull("the tool disappears", Locator.modelFor(c, model))
+ assertEquals("another model is unaffected", "other", Locator.modelFor(c, "other"))
+ } finally { srv.stop(0) }
+ }
+
+ @Test fun threeUnreadableAnswersInARowWithdrawItButASuccessResetsTheCount() {
+ val (srv, url) = serve(answer("在右上角"), answer("在右上角"), answer("<seen>⚙</seen><point>818 79</point>"), answer("不知道"), answer("不知道"), answer("不知道"))
+ try {
+ val c = cfg(url)
+ val model = "flaky-1"
+ val loc = Locator(c, model)
+ assertTrue(loc.locate("AAAA", "x") is Locator.Result.Failed)
+ assertTrue(loc.locate("AAAA", "x") is Locator.Result.Failed)
+ assertEquals(model, Locator.modelFor(c, model)) // two misses: still offered
+ assertEquals(Locator.Result.Found(818, 79, "⚙"), loc.locate("AAAA", "x")) // a hit clears the count
+ repeat(2) { loc.locate("AAAA", "x") }
+ assertEquals(model, Locator.modelFor(c, model)) // two more misses: still offered
+ loc.locate("AAAA", "x")
+ assertNull(Locator.modelFor(c, model)) // the third in a row: gone
+ } finally { srv.stop(0) }
+ }
+}
diff --git a/desktop/native/AndeeMac.swift b/desktop/native/AndeeMac.swift
index 0734537..e6ade20 100644
--- a/desktop/native/AndeeMac.swift
+++ b/desktop/native/AndeeMac.swift
@@ -44,10 +44,22 @@ public func andee_screen_capture_allowed(_ request: Int32) -> Int32 {
// MARK: - display / apps
+/// The scale of the display whose origin is (0,0) — the one we capture and aim at. Not `NSScreen.main`, which is
+/// the screen with keyboard focus and on a two-screen desk is often the other one.
+private func mainScale() -> CGFloat {
+ let id = CGMainDisplayID()
+ for s in NSScreen.screens {
+ if let n = s.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber, n.uint32Value == id {
+ return s.backingScaleFactor
+ }
+ }
+ return NSScreen.screens.first?.backingScaleFactor ?? 2
+}
+
@_cdecl("andee_main_display")
public func andee_main_display() -> UnsafeMutablePointer<CChar> {
let b = CGDisplayBounds(CGMainDisplayID())
- let scale = NSScreen.main?.backingScaleFactor ?? 2
+ let scale = mainScale()
return json(["x": b.origin.x, "y": b.origin.y, "w": b.width, "h": b.height, "scale": scale])
}
@@ -93,7 +105,12 @@ private func otherAppAt(_ x: Double, _ y: Double) -> pid_t? {
guard let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
as? [[String: Any]] else { return nil }
for w in list {
- guard let pid = w[kCGWindowOwnerPID as String] as? pid_t, pid != me,
+ // Ordinary app windows only (layer 0). Above them sit the Dock's full-screen transparent window, the menu
+ // bar and its extras — measured 2026-10-28: the Dock's window covers the whole display at layer 20, so
+ // "the topmost window here" was the Dock for every point, an e-number tap was refused as "now there:
+ // 通知中心", and activating the app under a click would have activated the Dock.
+ guard (w[kCGWindowLayer as String] as? Int) == 0,
+ let pid = w[kCGWindowOwnerPID as String] as? pid_t, pid != me,
(w[kCGWindowAlpha as String] as? Double ?? 1) > 0,
let b = w[kCGWindowBounds as String] as? [String: Any],
let r = CGRect(dictionaryRepresentation: b as CFDictionary),
@@ -151,6 +168,41 @@ private func actions(_ e: AXUIElement) -> [String] {
private var nodeBudget = 0
+/// The app being walked, for the hit test below; set by andee_ax_tree for the length of one walk.
+private var walkApp: AXUIElement? = nil
+private var hitBudget = 0
+
+/// Whether [a] is [b] or sits inside it, walking up from [a] at most [levels] parents.
+private func within(_ a: AXUIElement, _ b: AXUIElement, levels: Int = 12) -> Bool {
+ var cur: AXUIElement? = a
+ for _ in 0...levels {
+ guard let c = cur else { return false }
+ if CFEqual(c, b) { return true }
+ cur = attr(c, kAXParentAttribute).map { $0 as! AXUIElement }
+ }
+ return false
+}
+
+/// Is [e] what a click at its own centre would reach? False when something else is there — a menu that has
+/// closed but whose items the page keeps in the tree, a row scrolled out of its panel, a card under a dialog.
+/// Measured on the Mac traces: tapping such items by number hit the card beneath six times. Nil = not asked.
+private func reachable(_ e: AXUIElement, _ f: CGRect) -> Bool? {
+ guard let app = walkApp, hitBudget > 0 else { return nil }
+ hitBudget -= 1
+ var hit: AXUIElement?
+ guard AXUIElementCopyElementAtPosition(app, Float(f.midX), Float(f.midY), &hit) == .success, let h = hit else { return nil }
+ // The hit is the element or something inside it: the click lands on it.
+ if within(h, e) { return true }
+ // Or a container it sits in — web content often answers a hit test with an outer group several levels up
+ // (measured in Chrome: a visible nav link's centre returned its fourth-level group). Not the page or the
+ // window itself, though: that is exactly what a closed menu's item leaves at its centre.
+ if within(e, h, levels: 30) {
+ let role = str(h, kAXRoleAttribute) ?? ""
+ return !["AXWebArea", "AXWindow", "AXScrollArea", "AXApplication"].contains(role)
+ }
+ return false
+}
+
private func walk(_ e: AXUIElement, depth: Int) -> [String: Any]? {
nodeBudget -= 1
if nodeBudget < 0 || depth > 40 { return nil }
@@ -169,6 +221,11 @@ private func walk(_ e: AXUIElement, depth: Int) -> [String: Any]? {
let acts = actions(e)
if acts.contains(kAXPressAction as String) { n["press"] = true }
if let settable = settableValue(e), settable { n["editable"] = true }
+ // Only for what the model may press — a container's centre is often a child, which is fine and not asked.
+ if let f = frame(e), f.width > 1, f.height > 1,
+ n["press"] != nil || n["editable"] != nil || n["title"] != nil || n["desc"] != nil {
+ if reachable(e, f) == false { n["covered"] = true }
+ }
if let kids = attr(e, kAXChildrenAttribute) as? [AXUIElement], !kids.isEmpty {
let c = kids.compactMap { walk($0, depth: depth + 1) }
if !c.isEmpty { n["children"] = c }
@@ -193,6 +250,9 @@ public func andee_ax_tree(_ maxNodes: Int32) -> UnsafeMutablePointer<CChar> {
if let w = attr(ax, kAXFocusedWindowAttribute) { win = (w as! AXUIElement) }
else if let ws = attr(ax, kAXWindowsAttribute) as? [AXUIElement], let f = ws.first { win = f }
nodeBudget = Int(maxNodes)
+ walkApp = ax
+ hitBudget = 600
+ defer { walkApp = nil }
var out: [String: Any] = ["app": app.localizedName ?? "", "bundle": app.bundleIdentifier ?? "", "pid": Int(app.processIdentifier)]
if let w = win {
out["window_title"] = str(w, kAXTitleAttribute) ?? ""
@@ -201,7 +261,8 @@ public func andee_ax_tree(_ maxNodes: Int32) -> UnsafeMutablePointer<CChar> {
out["tree"] = [:]
out["no_window"] = true
}
- // The menu bar is part of the app a person can reach.
+ // The menu bar is part of the app a person can reach; its items are not hit-tested (they sit in closed menus).
+ walkApp = nil
if let mb = attr(ax, kAXMenuBarAttribute) {
nodeBudget = 400
out["menubar"] = walk(mb as! AXUIElement, depth: 0) ?? [:]
@@ -223,6 +284,23 @@ public func andee_ax_press_at(_ x: Double, _ y: Double) -> Int32 {
return AXUIElementPerformAction(e, kAXPressAction as CFString) == .success ? 1 : 0
}
+/// What a click at (x, y) would reach, with up to four of its containers: role and label of each. Lets an
+/// e-number tap check that the element it is about to press is still the one at that spot.
+@_cdecl("andee_ax_at")
+public func andee_ax_at(_ x: Double, _ y: Double) -> UnsafeMutablePointer<CChar> {
+ guard let pid = otherAppAt(x, y) else { return json(["found": false]) }
+ let app = AXUIElementCreateApplication(pid)
+ var el: AXUIElement?
+ guard AXUIElementCopyElementAtPosition(app, Float(x), Float(y), &el) == .success, var cur = el, !isOurs(cur) else { return json(["found": false]) }
+ var chain: [[String: String]] = []
+ for _ in 0..<5 {
+ chain.append(["role": str(cur, kAXRoleAttribute) ?? "", "label": [kAXTitleAttribute, kAXDescriptionAttribute, kAXValueAttribute].lazy.compactMap { str(cur, $0) }.first ?? ""])
+ guard let p = attr(cur, kAXParentAttribute) else { break }
+ cur = p as! AXUIElement
+ }
+ return json(["found": true, "chain": chain])
+}
+
/** Set the focused element's value (a text field), as a person pasting it would. */
@_cdecl("andee_ax_set_focused_value")
public func andee_ax_set_focused_value(_ text: UnsafePointer<CChar>) -> Int32 {
@@ -262,7 +340,13 @@ public func andee_click(_ x: Double, _ y: Double, _ button: Int32, _ count: Int3
@_cdecl("andee_drag")
public func andee_drag(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, _ ms: Int32) {
let steps = max(8, Int(ms) / 16)
+ // Move there first and let the pointer settle: pressing without arriving hovers nothing, and controls that
+ // react to hover (sliders, handles, list rows) only start a drag once they have seen the pointer over them.
+ post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: CGPoint(x: x1, y: y1), mouseButton: .left))
+ usleep(120_000)
post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: CGPoint(x: x1, y: y1), mouseButton: .left))
+ // A beat with the button down before moving — the press has to register as a grab, not as the start of a click.
+ usleep(100_000)
for i in 1...steps {
let t = Double(i) / Double(steps)
let p = CGPoint(x: x1 + (x2 - x1) * t, y: y1 + (y2 - y1) * t)
@@ -363,7 +447,7 @@ public func andee_screenshot(_ path: UnsafePointer<CChar>, _ maxSide: Int32) ->
let mine = content.applications.filter { $0.processID == getpid() }
let filter = SCContentFilter(display: display, excludingApplications: mine, exceptingWindows: [])
let cfg = SCStreamConfiguration()
- let scale = NSScreen.main?.backingScaleFactor ?? 2
+ let scale = mainScale()
var w = Double(display.width) * scale, h = Double(display.height) * scale
let longSide = max(w, h)
if maxSide > 0 && longSide > Double(maxSide) { let k = Double(maxSide) / longSide; w *= k; h *= k }
@@ -572,6 +656,36 @@ public func andee_notif_watch(_ cb: NotifCallback) -> Int32 {
}
private var notifKeep: [DispatchSourceFileSystemObject] = []
+/// Bring [pid] to the front and wait until it is there (up to ~0.8 s). True when it had to be moved.
+private func activate(_ pid: pid_t) -> Bool {
+ if NSWorkspace.shared.frontmostApplication?.processIdentifier == pid { return false }
+ guard let app = NSRunningApplication(processIdentifier: pid) else { return false }
+ app.activate(options: [])
+ for _ in 0..<16 {
+ usleep(50_000)
+ if NSWorkspace.shared.frontmostApplication?.processIdentifier == pid { break }
+ }
+ usleep(150_000) // the app's own key window and first responder, a beat after it is frontmost
+ return true
+}
+
+/// Make the app that owns the window at (x, y) the active one before a click lands there. A click on an
+/// inactive window only activates it: measured in Chrome, the first click on a text box left focus on the page
+/// (AXWebArea) and only the second focused the box — so a paste after one click went nowhere while the tool
+/// reported success. 1 when the app had to be brought forward, 0 when it already was (or none is there).
+@_cdecl("andee_activate_at")
+public func andee_activate_at(_ x: Double, _ y: Double) -> Int32 {
+ guard let pid = otherAppAt(x, y) else { return 0 }
+ return activate(pid) ? 1 : 0
+}
+
+/// Before keystrokes: if Andee itself is in front (the user just typed to it), bring the app being driven back.
+@_cdecl("andee_activate_target")
+public func andee_activate_target() -> Int32 {
+ guard NSWorkspace.shared.frontmostApplication?.processIdentifier == getpid(), let app = targetApp() else { return 0 }
+ return activate(app.processIdentifier) ? 1 : 0
+}
+
/// Whether a visible window of ours covers this point — only then does a click need us out of the way.
@_cdecl("andee_own_window_at")
public func andee_own_window_at(_ x: Double, _ y: Double) -> Int32 {
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 7a9ce13..77b7299 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
@@ -327,6 +327,27 @@ object Assistant {
progressClear()
}
+ /**
+ * 清空聊天记录: the conversation is gone — the rows the user reads **and** the one the model is holding.
+ *
+ * The settings button used to wipe only the rows (`Scrollback.wipe()`), and the brain kept its in-memory
+ * history word for word: the window was empty and the next sentence was still answered from the old chat
+ * (reported 2026-10-28; the phone's `clearChatHistory` has always rebuilt the brain for exactly this reason).
+ * Unlike [newConversation], nothing is folded away as a topic — the user asked to forget it, not to file it.
+ * A summary the review wrote into the history ("the user is waiting for…") goes with it, which is the
+ * other half of why this matters.
+ */
+ @Synchronized
+ fun clearConversation() {
+ stop()
+ Scrollback.wipe()
+ Pages.wipe()
+ brain?.stop()
+ brain = null
+ builtFor = null
+ progressClear()
+ }
+
private fun progressClear() { BallCaption.clear(); onProgress("") }
/** The quiet-hour review (also the sidebar's 整理 button). Silent: no answer, no voice, no task light. */
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 751a834..296e947 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
@@ -37,7 +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",
+ "nudge", "nudge_muted", "locator_model",
)
/**
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 f116c22..820ba5f 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
@@ -293,7 +293,7 @@ fun SettingsScreen(
Spacer(Modifier.height(16.dp))
when (confirm) {
"chat" -> ConfirmBlock(st("settings_clear_chat_confirm_title"), st("settings_clear_chat_confirm_body"), st("settings_clear_chat_confirm"),
- onNo = { confirm = "" }) { Assistant.stop(); Scrollback.wipe(); Pages.wipe(); confirm = "" }
+ onNo = { confirm = "" }) { Assistant.clearConversation(); confirm = "" }
"notes" -> ConfirmBlock(st("settings_clear_notes_confirm_title"), st("settings_clear_notes_confirm_body"), st("settings_clear_notes_confirm"),
onNo = { confirm = "" }) { DesktopNotebook.book.wipe(); confirm = "" }
"factory" -> ConfirmBlock(
@@ -420,22 +420,24 @@ private fun NoKeyHint(onPick: () -> Unit) {
}
@Composable
-private fun DangerButton(label: String, onClick: () -> Unit) {
+private fun DangerButton(label: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
Text(
label, color = Palette.danger, fontSize = 14.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
- modifier = Modifier.fillMaxWidth().glassPanel(14).clickable { onClick() }.padding(vertical = 11.dp),
+ // Like SecondaryButton, the caller owns the width: both fill, so in a Row each needs its own weight or the
+ // second one takes everything and the first is squeezed to a sliver (cancel read vertically, 2026-10-28).
+ modifier = modifier.fillMaxWidth().glassPanel(14).clickable { onClick() }.padding(vertical = 11.dp),
)
}
@Composable
-private fun ConfirmBlock(title: String, body: String, confirmLabel: String, onNo: () -> Unit, onYes: () -> Unit) {
+internal fun ConfirmBlock(title: String, body: String, confirmLabel: String, onNo: () -> Unit, onYes: () -> Unit) {
Column(Modifier.fillMaxWidth().glassPanel(12).padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(title, color = Palette.danger, fontSize = 14.sp)
Text(body, color = Palette.label, fontSize = 13.sp)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(st("common_cancel"), Modifier.weight(1f)) { onNo() }
- DangerButton(confirmLabel, onYes)
+ DangerButton(confirmLabel, Modifier.weight(1f), onYes)
}
}
}
@@ -447,9 +449,7 @@ private fun factoryItems(zh: Boolean): List<String> =
/** Wipes everything the card promised to. Irreversible; the confirmation lists it first. */
private fun factoryReset() {
- Assistant.stop()
- runCatching { Scrollback.wipe() }
- runCatching { Pages.wipe() }
+ runCatching { Assistant.clearConversation() }
runCatching { DesktopNotebook.book.wipe() }
runCatching { net.kuafuai.andee.desktop.mac.MacVault.wipe() }
runCatching { net.kuafuai.andee.desktop.shell.AndeeAgent.keys().forEach { net.kuafuai.andee.desktop.shell.AndeeAgent.delete(it.name) } }
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 7e6695b..87574c4 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 | ask | bubble
+ * screen: chat | settings | notebook | scenes | vault | selfcheck | expressions | artifacts | topic:1 | ask | bubble | confirm
*/
@OptIn(ExperimentalComposeUiApi::class)
fun main(args: Array<String>) {
@@ -96,6 +96,9 @@ fun main(args: Array<String>) {
when {
askCard != null -> AskShot(askCard)
screen == "bubble" -> BubbleShot()
+ screen == "confirm" -> Box(Modifier.background(Color(0xFF1C1C1E)).padding(24.dp)) {
+ ConfirmBlock("清空聊天记录?", "对话记录和它生成过的页面会删掉,这场对话聊过的内容它也会忘掉。小本本不受影响。", "确认清空", {}, {})
+ }
else -> AppRoot(nav)
}
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
index bf46139..0a12bc0 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
@@ -26,6 +26,9 @@ object Bridge {
fun andee_running_apps(): Pointer
fun andee_ax_tree(maxNodes: Int): Pointer
fun andee_ax_press_at(x: Double, y: Double): Int
+ fun andee_ax_at(x: Double, y: Double): Pointer
+ fun andee_activate_at(x: Double, y: Double): Int
+ fun andee_activate_target(): Int
fun andee_ax_set_focused_value(text: String): Int
fun andee_ax_focused_value(): Pointer
fun andee_click(x: Double, y: Double, button: Int, count: Int, holdMs: Int)
@@ -83,6 +86,13 @@ object Bridge {
fun runningApps(): JSONArray = JSONArray(str(need().andee_running_apps()))
fun axTree(maxNodes: Int): JSONObject = JSONObject(str(need().andee_ax_tree(maxNodes)))
fun axPressAt(x: Double, y: Double) = need().andee_ax_press_at(x, y) == 1
+ /** Bring the app under (x, y) to the front before clicking there; true when it had to be moved. */
+ fun activateAt(x: Double, y: Double) = lib?.andee_activate_at(x, y) == 1
+ /** Before keystrokes: bring the driven app back if Andee itself is in front; true when it had to be moved. */
+ fun activateTarget() = lib?.andee_activate_target() == 1
+
+ /** What a click at (x, y) would reach: `{found, chain: [{role, label}, …]}`, the hit element first. */
+ fun axAt(x: Double, y: Double): JSONObject = JSONObject(str(need().andee_ax_at(x, y)))
fun setFocusedValue(text: String) = need().andee_ax_set_focused_value(text) == 1
fun focusedValue(): JSONObject = JSONObject(str(need().andee_ax_focused_value()))
fun click(x: Double, y: Double, right: Boolean = false, count: Int = 1, holdMs: Int = 40) =
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
index 34acb33..418635d 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
@@ -43,7 +43,12 @@ class MacScreen(
@Volatile private var zoomAt = 0L
private val spots = HashMap<String, MutableList<Long>>()
- override fun handles(method: String) = method in METHODS
+ // tap_target only where a pointing model can answer it; DesktopBrainHost lists exactly what is handled.
+ override fun handles(method: String) = method in METHODS && (method != "screen.tap_target" || locatorModel() != null)
+
+ private fun locatorModel(): String? = net.kuafuai.andee.brain.Locator.modelFor(
+ net.kuafuai.andee.desktop.Assistant.config(), net.kuafuai.andee.desktop.Settings.get("locator_model"),
+ )
override fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any? {
if (!Bridge.available) throw IllegalStateException("The Mac screen bridge did not load; screen tools cannot run here.")
@@ -53,9 +58,11 @@ class MacScreen(
"screen.ui_tree" -> uiTree(p.optBoolean("with_shot", false))
"screen.tap_id" -> tapId(req(p, "eid"), long = false)
"screen.long_press_id" -> tapId(req(p, "eid"), long = true)
+ "screen.tap_target" -> tapTarget(req(p, "target"), p.optBoolean("long", false))
"screen.tap" -> tapAim(p, long = false)
"screen.long_press" -> tapAim(p, long = true)
"screen.swipe" -> swipe(p)
+ "screen.drag" -> drag(p)
"screen.type" -> type(p.optString("text"))
"screen.submit_input" -> submit()
"screen.wait" -> waitFor(p.optDouble("seconds", 2.0))
@@ -86,6 +93,7 @@ class MacScreen(
val idx = LinkedHashMap<String, El>()
var total = 0
var n = 0
+ var covered = 0
fun visit(o: JSONObject, depth: Int) {
total++
val f = o.optJSONArray("frame")
@@ -96,7 +104,11 @@ class MacScreen(
f.getDouble(0) < dw() && f.getDouble(1) < dh() && f.getDouble(0) + f.getDouble(2) > 0 && f.getDouble(1) + f.getDouble(3) > 0
val press = o.optBoolean("press")
val editable = o.optBoolean("editable") || role in setOf("TextField", "TextArea", "SearchField", "ComboBox")
- val useful = visible && !o.optBoolean("disabled") &&
+ // Something else is what a click at its centre would reach (see `reachable` in AndeeMac.swift): a closed
+ // menu's items, a row scrolled out of its panel. Listing it invites a tap that lands on whatever is there.
+ val hidden = o.optBoolean("covered")
+ if (hidden && visible) covered++
+ val useful = visible && !hidden && !o.optBoolean("disabled") &&
(press || editable || label.isNotBlank() || role in setOf("Button", "Link", "CheckBox", "RadioButton", "PopUpButton", "MenuButton", "Tab", "Cell", "Row"))
val kids = o.optJSONArray("children")
val decorative = role in setOf("Group", "ScrollArea", "SplitGroup", "Unknown", "LayoutArea", "") && label.isBlank() && !press
@@ -120,8 +132,25 @@ class MacScreen(
.put("window", raw.optString("window_title")).put("nodes_total", total).put("elements_listed", idx.size)
.put("elements", lines.joinToString("\n"))
if (idx.size > MAX_LINES) out.put("elements_dropped", idx.size - MAX_LINES)
- if (idx.isEmpty()) {
- out.put("empty", true).put(
+ if (covered > 0) out.put("covered_not_listed", covered)
+ val win = raw.optJSONObject("tree")?.optJSONArray("frame")
+ val offMain = win != null && win.getDouble(2) > 1 && run {
+ val l = maxOf(0.0, win.getDouble(0)); val t = maxOf(0.0, win.getDouble(1))
+ val r = minOf(dw(), win.getDouble(0) + win.getDouble(2)); val b = minOf(dh(), win.getDouble(1) + win.getDouble(3))
+ val inside = maxOf(0.0, r - l) * maxOf(0.0, b - t)
+ inside < 0.5 * win.getDouble(2) * win.getDouble(3)
+ }
+ // A window of real size with nothing in it but its own title-bar buttons: the app draws its own UI and
+ // tells accessibility nothing (Mac WeChat lists 4 elements — the window and three traffic lights).
+ val blind = !offMain && idx.size <= 6 && total <= 16 && win != null && win.getDouble(2) * win.getDouble(3) > 200_000
+ if (offMain) {
+ out.put("other_display", true).put(
+ "hint",
+ "${raw.optString("app")}'s window is mostly on another display. Andee can only see and click the main display, " +
+ "so this list and any screenshot do not show it. Ask the user to move the window to the main screen; do not aim at it.",
+ )
+ } else if (idx.isEmpty() || blind) {
+ out.put("empty", true).put("tree_withheld", blind).put(
"hint",
"This app gives the accessibility layer almost nothing (common for apps that draw their own UI, like " +
"WeChat for Mac). Work from the screenshot attached here: aim with the grid and tap_by_coordinates, " +
@@ -142,26 +171,128 @@ class MacScreen(
"unknown element $eid — the screen has changed or the number is from an older list. Re-dump with get_screen_element; do not guess.",
)
val (nx, ny) = toNorm(e.cx, e.cy)
+ stillThere(e)
// A Press action is not a pointer event and the hit test already skips our windows: nothing to step aside for.
+ val before = probe()
val pressed = !long && e.press && Bridge.axPressAt(e.cx, e.cy)
- if (!pressed) gesture(e.cx, e.cy) { Bridge.click(e.cx, e.cy, right = long, holdMs = 40) }
+ if (!pressed) click(e.cx, e.cy, long)
return afterTap(JSONObject().put("completed", true).put("eid", eid).put("label", e.label)
- .put("via", if (pressed) "press_action" else if (long) "right_click" else "click").put("x", nx).put("y", ny))
+ .put("via", if (pressed) "press_action" else if (long) "right_click" else "click").put("x", nx).put("y", ny), nx, ny, before)
}
private fun tapAim(p: JSONObject, long: Boolean): JSONObject {
val (nx, ny, label) = resolveAim(p)
guardSpot(nx, ny)
val (x, y) = toPx(nx, ny)
- gesture(x, y) { Bridge.click(x, y, right = long, holdMs = 40) }
+ val before = probe()
+ click(x, y, long)
return afterTap(JSONObject().put("completed", true).put("x", nx).put("y", ny).put("aimed_at", label)
- .put("via", if (long) "right_click" else "click"))
+ .put("via", if (long) "right_click" else "click"), nx, ny, before)
+ }
+
+ /**
+ * The brain describes, a model trained to point locates, the device clicks — see `Locator`. The picture it
+ * locates on is the plain screenshot (no grid: rulers are for an eye that counts cells), at the size the
+ * brain's own screenshots have, so "0-1000 of the image" is 0-1000 of the main display.
+ */
+ private fun tapTarget(target: String, long: Boolean): JSONObject {
+ val model = locatorModel() ?: throw IllegalStateException("No locating model is available on this backend. Use tap_screen_element or tap_by_coordinates (zoom first).")
+ if (!Bridge.screenCaptureAllowed()) throw IllegalStateException(SCREEN_RECORDING_NOTE)
+ val img = scale(capture(SHOT_MAX_SIDE), SHOT_MAX_SIDE)
+ val loc = net.kuafuai.andee.brain.Locator(net.kuafuai.andee.desktop.Assistant.config(), model) { warn, msg ->
+ if (warn) Log.w("Locator", msg) else Log.i("Locator", msg)
+ }.locate(png(img), target)
+ return when (loc) {
+ is net.kuafuai.andee.brain.Locator.Result.Found -> {
+ guardSpot(loc.x, loc.y)
+ val (x, y) = toPx(loc.x, loc.y)
+ val before = probe()
+ click(x, y, long)
+ afterTap(
+ JSONObject().put("completed", true).put("located", "${loc.x},${loc.y}").put("target", target).put("saw", loc.seen)
+ .put("via", if (long) "right_click" else "click"),
+ loc.x, loc.y, before,
+ )
+ }
+ net.kuafuai.andee.brain.Locator.Result.Absent -> JSONObject().put("found", false).put("target", target).put(
+ "note",
+ "The locating model looked at the current screen and does not see this. Nothing was clicked. Look at the screen " +
+ "and describe it differently, or scroll — do not send the same words again.",
+ )
+ is net.kuafuai.andee.brain.Locator.Result.Failed -> JSONObject().put("found", false).put("target", target)
+ .put("error", loc.why).put("note", "Nothing was clicked. Fall back to tap_by_coordinates with a zoom.")
+ }
}
- /** Taps are followed by a fresh picture, as on the phone, so the next step reads the result. */
- private fun afterTap(o: JSONObject): JSONObject {
- Thread.sleep(400)
- if (Bridge.screenCaptureAllowed()) o.put("after_shot", JSONObject().put("png_base64", shot(grid = true)))
+ /**
+ * The listed element is no longer what a click at its centre reaches — the list is older than the screen.
+ * The phone re-finds the node live before every e-number tap; this is the Mac's version of that check: the
+ * hit element or one of its containers must still carry the label the list showed.
+ */
+ private fun stillThere(e: El) {
+ if (e.label.isBlank()) return
+ val at = runCatching { Bridge.axAt(e.cx, e.cy) }.getOrNull() ?: return
+ if (!at.optBoolean("found")) return
+ val chain = at.optJSONArray("chain") ?: return
+ val labels = (0 until chain.length()).map { chain.getJSONObject(it).optString("label") }
+ val want = e.label.take(40)
+ if (labels.none { it.isNotBlank() && (it.contains(want) || want.contains(it.take(40))) }) {
+ throw IllegalStateException(
+ "${e.eid} (\"${e.label.take(30)}\") is not what is at that spot any more — the screen changed since the list " +
+ "(now there: \"${labels.firstOrNull { it.isNotBlank() }?.take(30) ?: "unlabelled"}\"). Re-dump with get_screen_element and pick again.",
+ )
+ }
+ }
+
+ /** A tiny capture to tell, after a tap, whether anything on the screen moved. Null without the grant. */
+ private fun probe(): BufferedImage? =
+ if (Bridge.screenCaptureAllowed()) runCatching { capture(PROBE_SIDE) }.getOrNull() else null
+
+ /** Share of probe pixels that differ noticeably — a tap that opened, closed or highlighted something. */
+ private fun changed(a: BufferedImage, b: BufferedImage): Double {
+ if (a.width != b.width || a.height != b.height) return 1.0
+ var diff = 0
+ var n = 0
+ for (y in 0 until a.height step 2) for (x in 0 until a.width step 2) {
+ val p = a.getRGB(x, y); val q = b.getRGB(x, y)
+ val d = Math.abs((p shr 16 and 255) - (q shr 16 and 255)) + Math.abs((p shr 8 and 255) - (q shr 8 and 255)) + Math.abs((p and 255) - (q and 255))
+ if (d > 48) diff++
+ n++
+ }
+ return diff.toDouble() / n
+ }
+
+ /**
+ * Taps are followed by a fresh picture, as on the phone, so the next step reads the result — and, as on the
+ * phone, a fact about it: whether the screen changed at all, and a ring where the click landed. Without
+ * those the model judged every click by eye, and in the traces it repeatedly took a menu for open that was
+ * not. The wait is a poll (the page may take a moment to answer), not a fixed sleep.
+ */
+ private fun afterTap(o: JSONObject, nx: Int = -1, ny: Int = -1, before: BufferedImage? = null): JSONObject {
+ var moved: Double? = null
+ if (before != null) {
+ val until = System.currentTimeMillis() + SETTLE_MAX_MS
+ Thread.sleep(150)
+ while (true) {
+ val now = runCatching { capture(PROBE_SIDE) }.getOrNull() ?: break
+ moved = changed(before, now)
+ if (moved > CHANGED_SHARE || System.currentTimeMillis() >= until) break
+ Thread.sleep(150)
+ }
+ // Something is moving: give it a beat to settle before the picture the model will read.
+ if ((moved ?: 0.0) > CHANGED_SHARE) Thread.sleep(250)
+ } else {
+ Thread.sleep(400)
+ }
+ if (moved != null) {
+ o.put("screen_changed", moved > CHANGED_SHARE)
+ if (moved <= CHANGED_SHARE) o.put(
+ "change_note",
+ "Nothing on the screen changed after this click. It most likely missed (or hit something inert). Do not assume a menu " +
+ "or page opened — look at after_shot, and zoom in before aiming again.",
+ )
+ }
+ if (Bridge.screenCaptureAllowed()) o.put("after_shot", JSONObject().put("png_base64", shot(grid = true, ringAt = if (nx >= 0) nx to ny else null)))
o.put("front_app", Bridge.frontmost().optString("name"))
return o
}
@@ -203,13 +334,17 @@ class MacScreen(
return (r[0] + lx * (r[2] - r[0]) / 1000) to (r[1] + ly * (r[3] - r[1]) / 1000)
}
- /** The phone's stuck-loop guard: a fourth tap within 120 px of a spot inside five minutes is refused. */
+ /**
+ * The phone's stuck-loop guard: a fourth tap within [SPOT_RADIUS_PT] of a spot inside five minutes is refused.
+ * The radius was 120 pt — about 240 Retina pixels — which refused aim corrections converging on a small target
+ * (9 of 56 coordinate taps in the traces, 4 in one turn). The phone made the same cut for the same reason.
+ */
private fun guardSpot(nx: Int, ny: Int) {
val (x, y) = toPx(nx, ny)
val now = System.currentTimeMillis()
synchronized(spots) {
spots.values.forEach { it.removeAll { t -> now - t > 300_000 } }
- val key = spots.keys.firstOrNull { k -> k.split(',').let { Math.hypot(it[0].toDouble() - x, it[1].toDouble() - y) < 120 } }
+ val key = spots.keys.firstOrNull { k -> k.split(',').let { Math.hypot(it[0].toDouble() - x, it[1].toDouble() - y) < SPOT_RADIUS_PT } }
?: "${x.toInt()},${y.toInt()}"
val list = spots.getOrPut(key) { mutableListOf() }
if (list.size >= 3) throw IllegalStateException(
@@ -222,6 +357,52 @@ class MacScreen(
// ---- swipes, typing, keys ---------------------------------------------
+ /**
+ * Press at the start, move to the end holding, release: a real drag. [swipe] on a Mac is a scroll — it moves
+ * the content under the pointer — so anything that has to be *grabbed* (a slider, a splitter, a window by its
+ * title bar, a file onto a folder, a list row, a range selection) had no tool, and the model reached for
+ * shell scripts that synthesise the mouse.
+ *
+ * Both ends are aimed like a tap: 0-1000 numbers, or `from_target`/`to_target` words resolved by the locating
+ * model when there is one. The app under the start point is brought forward first, as for a click.
+ */
+ private fun drag(p: JSONObject): JSONObject {
+ val (fx, fy) = dragEnd(p, "from")
+ val (tx, ty) = dragEnd(p, "to")
+ val ms = p.optInt("duration_ms", 700).coerceIn(200, 5_000)
+ val (ax, ay) = toPx(fx, fy); val (bx, by) = toPx(tx, ty)
+ require(Math.hypot(bx - ax, by - ay) >= 4) { "the start and the end are the same place — a drag needs somewhere to go" }
+ val before = probe()
+ gesture(ax, ay) {
+ Bridge.activateAt(ax, ay)
+ Bridge.drag(ax, ay, bx, by, ms)
+ }
+ return afterTap(
+ JSONObject().put("completed", true).put("from", "$fx,$fy").put("to", "$tx,$ty").put("via", "drag"),
+ tx, ty, before,
+ )
+ }
+
+ private fun dragEnd(p: JSONObject, side: String): Pair<Int, Int> {
+ val target = p.optString("${side}_target").trim()
+ if (target.isNotEmpty()) {
+ val model = locatorModel() ?: throw IllegalStateException("${side}_target needs a locating model, and none is available here. Give ${side}_x and ${side}_y instead.")
+ if (!Bridge.screenCaptureAllowed()) throw IllegalStateException(SCREEN_RECORDING_NOTE)
+ val loc = net.kuafuai.andee.brain.Locator(net.kuafuai.andee.desktop.Assistant.config(), model) { warn, msg ->
+ if (warn) Log.w("Locator", msg) else Log.i("Locator", msg)
+ }.locate(png(scale(capture(SHOT_MAX_SIDE), SHOT_MAX_SIDE)), target)
+ return when (loc) {
+ is net.kuafuai.andee.brain.Locator.Result.Found -> loc.x to loc.y
+ net.kuafuai.andee.brain.Locator.Result.Absent -> throw IllegalStateException("the locating model does not see \"$target\" on the screen. Nothing was dragged.")
+ is net.kuafuai.andee.brain.Locator.Result.Failed -> throw IllegalStateException("could not locate \"$target\" (${loc.why}). Nothing was dragged; give ${side}_x and ${side}_y instead.")
+ }
+ }
+ val x = p.optInt("${side}_x", Int.MIN_VALUE); val y = p.optInt("${side}_y", Int.MIN_VALUE)
+ require(x != Int.MIN_VALUE && y != Int.MIN_VALUE) { "give ${side}_x and ${side}_y (0-1000), or ${side}_target in words" }
+ requireNorm(x, "${side}_x"); requireNorm(y, "${side}_y")
+ return x to y
+ }
+
private fun swipe(p: JSONObject): JSONObject {
val x1 = p.getInt("x1"); val y1 = p.getInt("y1"); val x2 = p.getInt("x2"); val y2 = p.getInt("y2")
listOf(x1 to "x1", y1 to "y1", x2 to "x2", y2 to "y2").forEach { requireNorm(it.first, it.second) }
@@ -251,6 +432,8 @@ class MacScreen(
* even then it is keystrokes into a cleared field, never AXValue on top of a web editor.
*/
private fun type(text: String): JSONObject {
+ // Keys go to the frontmost app; if that is Andee (the user just typed to it), they would land in Andee.
+ Bridge.activateTarget()
val before = Bridge.focusedValue()
if (!before.optBoolean("focused")) return typeBlind(text)
// Keys go to the focused app, not to a point on screen: fading our windows changes nothing for them.
@@ -309,11 +492,13 @@ class MacScreen(
}
private fun submit(): JSONObject {
+ Bridge.activateTarget()
Bridge.key(Bridge.Keys.RETURN)
return JSONObject().put("performed", true).put("via", "return_key")
}
private fun global(action: String): JSONObject {
+ Bridge.activateTarget()
when (action.lowercase()) {
"back" -> Bridge.key(Bridge.Keys.LEFT_BRACKET, Bridge.Keys.CMD)
"home" -> Bridge.key(Bridge.Keys.F3, Bridge.Keys.CMD)
@@ -353,13 +538,26 @@ class MacScreen(
} finally { f.delete() }
}
- private fun shot(grid: Boolean): String {
+ private fun shot(grid: Boolean, ringAt: Pair<Int, Int>? = null): String {
var img = capture(SHOT_MAX_SIDE)
img = scale(img, SHOT_MAX_SIDE)
if (grid) drawGrid(img, zoom = false)
+ ringAt?.let { (nx, ny) -> ring(img, nx * img.width / 1000.0, ny * img.height / 1000.0) }
return png(img)
}
+ /** The magenta ring where a click landed — the one piece of evidence about aim, as on the phone. */
+ private fun ring(img: BufferedImage, mx: Double, my: Double) {
+ img.createGraphics().apply {
+ setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
+ val r = minOf(img.width, img.height) * 0.018
+ color = Color(224, 0, 255); stroke = BasicStroke((r * 0.22).toFloat().coerceAtLeast(2f))
+ drawOval((mx - r).toInt(), (my - r).toInt(), (2 * r).toInt(), (2 * r).toInt())
+ fillOval((mx - 2).toInt(), (my - 2).toInt(), 4, 4)
+ dispose()
+ }
+ }
+
private fun lookRegion(p: JSONObject): JSONObject {
if (!Bridge.screenCaptureAllowed()) throw IllegalStateException(SCREEN_RECORDING_NOTE)
val (cx, cy, w, h, mark) = if (p.optString("cell").isNotBlank()) {
@@ -465,6 +663,19 @@ class MacScreen(
private fun <T> gesture(x: Double, y: Double, block: () -> T): T =
if (Bridge.ownWindowAt(x, y)) stepAside(block) else block()
+ /**
+ * A click, made to land: the app under the point is brought to the front first. On a Mac a click on an
+ * inactive window only activates it — measured in Chrome, the first click on a text box left focus on the
+ * page, so the paste that followed went nowhere while type_text reported success, and the first click on a
+ * sidebar link did nothing at all. Both were in the traces of one task.
+ */
+ private fun click(x: Double, y: Double, right: Boolean) {
+ gesture(x, y) {
+ Bridge.activateAt(x, y)
+ Bridge.click(x, y, right = right, holdMs = 40)
+ }
+ }
+
private fun <T> stepAside(block: () -> T): T {
// The hide is inside the try: if it fails half-way, the windows must still come back.
try {
@@ -486,10 +697,16 @@ class MacScreen(
private const val GRID_ROWS = 12
private const val SHOT_MAX_SIDE = 1600
private const val MAX_LINES = 300
+ private const val SPOT_RADIUS_PT = 30.0
+ /** Long side of the before/after probes; enough to see a menu open, cheap to capture. */
+ private const val PROBE_SIDE = 480
+ private const val SETTLE_MAX_MS = 1_200L
+ /** Share of probe pixels that must change for a click to count as having done something. */
+ private const val CHANGED_SHARE = 0.002
val METHODS = setOf(
- "screen.ui_tree", "screen.tap_id", "screen.tap", "screen.long_press_id", "screen.long_press",
- "screen.swipe", "screen.type", "screen.submit_input", "screen.wait", "screen.look_region",
+ "screen.ui_tree", "screen.tap_id", "screen.tap", "screen.tap_target", "screen.long_press_id", "screen.long_press",
+ "screen.swipe", "screen.drag", "screen.type", "screen.submit_input", "screen.wait", "screen.look_region",
"screen.screenshot", "screen.global",
)
@@ -499,7 +716,7 @@ class MacScreen(
"This image carries an 8x12 aim grid, A1 (top-left) to H12 (bottom-right): letters run along the TOP edge and numbers " +
"down the LEFT edge like a map's rulers, and nothing is printed inside a cell. " +
"To click something, name its cell and which part of the cell — {\"cell\": \"D7\", \"part\": \"bottom-right\"} on " +
- "tap_by_coordinates. Andee's own windows are never in this picture."
+ "tap_by_coordinates. Andee's own windows are never in this picture. A magenta ring marks where the last click landed."
init { Log.i("MacScreen", "screen tools registered") }
}
diff --git a/desktop/src/main/resources/strings_en.properties b/desktop/src/main/resources/strings_en.properties
index 0a12167..578a034 100644
--- a/desktop/src/main/resources/strings_en.properties
+++ b/desktop/src/main/resources/strings_en.properties
@@ -7,6 +7,7 @@ ERROR=Something broke on my side: %1$s
ERROR_400=The backend rejected the request: %1$s\nThe usual cause is a misspelled model name. Check it in Settings → Backend.
ERROR_402=The backend answered 402, which most likely means the account is out of balance. Open Settings → Backend to see which provider you are using, then top up on that provider's website and try again.
ERROR_404=The backend could not find that address (HTTP 404). Check the endpoint URL and the model name in Settings → Backend.
+ERROR_MOVED=The backend did not answer as an API — the address may be wrong, or the service has moved (it pointed to: %1$s). Check the address in Settings → Backend; if you use CodeFlying, the problem is on the service side, and you can switch to On-device for now.
ERROR_429=The backend is busy or being asked too often (HTTP 429). Say it again in a moment. If it keeps happening, check on the provider's website whether your quota has run out.
ERROR_5XX=The backend itself is having trouble (HTTP %1$d). Your settings are not the problem. Try again in a few minutes, or check the provider's website for maintenance notices.
ERROR_AUTH=The backend refused the request (HTTP %1$d): the key is wrong, expired or disabled. Check the key in Settings → Backend, and generate a new one on the provider's website if needed.
diff --git a/desktop/src/main/resources/strings_zh.properties b/desktop/src/main/resources/strings_zh.properties
index 41b14a4..173b0ab 100644
--- a/desktop/src/main/resources/strings_zh.properties
+++ b/desktop/src/main/resources/strings_zh.properties
@@ -7,6 +7,7 @@ ERROR=我这边出错了:%1$s
ERROR_400=后端说请求有问题:%1$s\n最常见的原因是模型名写错了,到「设置」→「后端」核对一下模型名。
ERROR_402=后端服务返回了 402,多半是账户余额不足了。到「设置」→「后端」看看当前用的是哪家服务商,打开它的官网充值后再试。
ERROR_404=后端找不到这个地址(HTTP 404)。到「设置」→「后端」检查接口地址和模型名有没有填错。
+ERROR_MOVED=后端没有按接口回答,地址可能填错了,或者服务换了地址(它指向:%1$s)。到「设置」→「后端」检查地址;如果用的是 CodeFlying,这是服务那边的问题,可以先切到「本机」。
ERROR_429=后端现在太忙或者请求太频繁了(HTTP 429),过一会儿再说一遍就行。如果一直这样,去服务商官网看看额度有没有用完。
ERROR_5XX=后端服务自己出了问题(HTTP %1$d),不是你这边的设置有误。过几分钟再试;一直不行就去服务商官网看看是否在维护。
ERROR_AUTH=后端拒绝了请求(HTTP %1$d):Key 填错、过期或被停用了。到「设置」→「后端」检查 Key,必要时去服务商官网重新生成一个。
diff --git a/docs/design/click-accuracy.zh-CN.md b/docs/design/click-accuracy.zh-CN.md
new file mode 100644
index 0000000..739cd57
--- /dev/null
+++ b/docs/design/click-accuracy.zh-CN.md
@@ -0,0 +1,79 @@
+# 点击准确度:调研结论与第一版优化
+
+状态:第一版已实现(2026-10-28),Mac 已装上并在真实任务里用到了 `tap_target`;手机端未上真机 · 适用:Android 与 Mac
+
+## 1. 问题出在哪(我们自己的数据)
+
+Mac 日志,10 月 21–27 日,108 次点击:
+
+| 瞄准方式 | 执行 | 大致成功 |
+|---|---|---|
+| 元素编号(`tap_screen_element`) | 51 | 约 80% |
+| 先放大再按格子点 | 23 | 约 43% |
+| 不放大,直接按格子 / 坐标 | 24 | 不到 10% |
+| 模型自己跑 `osascript` 点 | 10 | 2 |
+
+Android 已有记录:放大后瞄准 33/41 改变了屏幕,按截图瞄准 124/211;一条朋友圈评论 64 步、341 秒。
+
+错误分成两半:
+
+- **模型"指不准"**:小图标偏几十像素;不给结构的应用(微信)只能看图点;至少 5 次是模型把截图像素当成 0–1000 坐标、自己算错。
+- **工程缺陷**(多数在 Mac 上,Android 十月已补过):
+ - 列表里有点不到的元素(关闭的菜单项),按编号点到了底下的卡片;
+ - 点完不告诉模型"屏幕变了没有",也不画落点;
+ - 连点保护半径 120pt,把正在修正的瞄准也拒了(56 次里 9 次);
+ - 认不出微信这类"不给结构"的应用;
+ - 按编号点时不确认元素还在原处;
+ - 多显示器时用错了缩放比例。
+
+## 2. 外部调研结论
+
+- **通用大模型"指"得很差,专门训练过的定位模型好得多。**ScreenSpot-Pro(小图标、密集界面):GPT-4o 0.8、Claude Sonnet 4 19.1、Gemini 2.5 Pro 7.0;专门模型 UI-TARS-1.5-7B 49.6、MAI-UI-8B 65.7、UI-Venus-2-9B 73.0。
+- **业内的通用解法是"规划和定位分开"**:大脑只用文字描述要点什么,由专门的模型给出坐标(Agent S2/S3、Midscene 单独配 Locate 模型、MEGA-GUI)。对 DeepSeek 这类视觉弱的大脑,这是收益最大的一招。
+- **放大再定位**是不用训练就有效的手段(MEGA-GUI 在 ScreenSpot-Pro 上 +28.5 个百分点),和我们自己的数据一致。
+- **点完要看结果**(Mobile-Agent v2 前后截图对比、Claude/OpenAI 文档都要求)。
+- **坐标格式按模型族适配**:Qwen3、豆包、GLM 用 0–1000,正好和我们的协议一致;Qwen2.5 和 UI-TARS-1.5 用缩放后的绝对像素。
+- 完整报告(含链接)在这次会话的两份调研结果里,要点已摘入本文。
+
+## 3. 这一版做了什么
+
+### 3.1 新工具 `tap_target`(两端,仅本机大脑)
+
+大脑用一句话描述要点的东西,比如"右下角蓝色的发送按钮"。设备截一张不带网格的图,交给一个会"指"的视觉模型一次问答,拿到 0–1000 的点后点击。大脑全程不碰坐标。
+
+- **用哪个模型**:**统一用用户给大脑配置的那个模型**,所有后端一样;设置项 `locator_model` 可以覆盖(想要更快更准可以填 `doubao-seed-2-1-lite-260915`,前提是后端是方舟或 CodeFlying)。最初的版本按地址挑模型,认不出的后端就把工具藏起来,理由是“只有豆包看得懂图”,这是错的:现在的模型基本都是多模态。实测 `api.openai-next.com` 上的 `gpt-6.1-sol` 在同一批目标上平均偏差 12 px(最大 45),豆包是 6 px;慢一些(5–16 秒对 2 秒),但比大脑自己数格子好得多,不存在的目标也都答“没有”。
+- **降级**:后端返回 400/401/403/404/415/422(模型不收图片等),本次运行内立刻撤下这个工具;连续 3 次答不出可读的结果也撤下,中间只要有一次成功就重新计数。撤下之后大脑回到按格子瞄准的老办法。
+- **实测**(我们自己的手机截图,10 个有正确答案的目标):平均偏差 6.4 像素,最大 24;每次约 2 秒、约 1400 个输入 token。
+- **提示词里两处是实测出来的**:
+ - 用中文问:同一批目标,英文问法有 3 个偏了 25–37 像素。
+ - 先说出看到了什么(`<seen>`),再判断是不是要找的:不这样问的话,问"红色的删除按钮"会自信地指向"关闭"按钮。改了之后答"没有",正例照样都对。`seen` 会随结果返回给大脑。
+- **安全**:手机上这次点击视为"已瞄准",满足不给结构的应用"必须先放大"的规则,但连点保护照常生效。
+- 系统提示词改为:没有元素编号时优先用 `tap_target`,它不可用或找不到时才按格子瞄准。
+
+### 3.2 Mac 补上 Android 已有的保护
+
+- **点完反馈**:点前点后各截一张小图做对比,返回 `screen_changed`;没变化时提示"多半没点中,别以为菜单开了"。等待从固定 400ms 改成轮询,最多 1.2 秒。截图上画品红色落点圈。
+- **点不到的元素不再列出**:读界面树时,对每个可点元素在其中心做一次命中测试,命中的不是它自己或它的容器就标为被遮挡,不进列表(`covered_not_listed` 给出数量)。在 Chrome 上实测,123 个可见元素无误判。
+- **按编号点之前确认**:点的位置上现在的元素标签对不上列表里的,就拒绝并让模型重新读列表。
+- **连点保护半径**从 120pt 改为 30pt。
+- **认出不给结构的应用**:窗口很大但元素不超过 6 个(微信 Mac 只给窗口和三个标题栏按钮),按"不给结构"处理,自动附截图并提示看图。
+- **窗口在另一块屏上**:提示模型这块屏看不到,请用户把窗口挪到主屏,不要去瞄。
+- **缩放比例**改为取主显示器自己的比例,不再用"有键盘焦点的那块屏"。
+
+- **点击前先把应用切到前台**(2026-10-28 补):Mac 上点击不在前台的应用时,第一下只会激活它,不会点进页面。在 Chrome 里实测:第一下点输入框,焦点落在整个网页上;第二下才点进输入框。真实任务里,这表现为"创建新应用第一次点了没反应",以及打字"报成功但框是空的",模型最后断定"这个框我按不动"。现在每次点击前,如果目标应用不在前台,先切过去并等它就位;打字、回车、系统按键前,如果前台是 Andee 自己,也先把目标应用切回来。修复后**还没有端到端验证**(当时用来测试的窗口是用户正在用的 Chrome)。
+
+### 3.3 工具说明和画面对齐
+
+"红色十字"改为"品红色十字";放大图的标签改为"在上边和左边,像地图的标尺"。
+
+## 4. 没做的,以及为什么
+
+- **自托管专门的定位模型**(UI-Venus-2、MAI-UI、UI-TARS):需要 GPU 服务器。豆包这条线已经在用户现有的 key 下可用、实测足够准,先上这个;如果真机上还不够,再考虑。
+- **OCR / 图标检测造"伪编号"**(OmniParser 路线):对无文字的图标效果最差,而微信的难点正是图标。
+- **点前用第二个模型核对**(MHVF、GUI-Actor 的核验器):每次点击要多一次调用,先看 `tap_target` 在真机上的表现再定。
+
+## 5. 待验证
+
+- **手机端 `tap_target` 没上真机**:需要一台语音和大脑 key 都正常的手机,在微信里试一次评论或回复。
+- **Mac 上 `tap_target` 的端到端效果**:10-28 在码上飞的试用任务里用了两次(「创建新应用」「立即开发」),都点中了。样本还太少。
+- **CodeFlying 网关**:新地址 `baas.kuafuai.net`(https)已能转发豆包视觉模型。