Skip to content

👾 Open Computer Use – Open-Source Alternative to Codex Computer Use

Add visual cursor overlay for click actions

Leo3aa5037bde04
diff --git a/README.md b/README.md
index b4fa6f8..8b06bed 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
当前版本聚焦两件事:
- 通过 `stdio` MCP 暴露 9 个和官方 `computer-use` 同名的 tools。
-- 在仓库内自带一个 GUI fixture app、smoke suite 和无 Dock 图标的 app 模式权限引导,保证这 9 个 tools 有稳定可回归的本地验证路径。
+- 在仓库内自带一个 GUI fixture app、smoke suite 和无 Dock 图标的 app 模式权限引导,并为 `click` 补一层独立 visual cursor overlay,保证这 9 个 tools 有稳定可回归的本地验证路径。
当前实现的 9 个 tools:
@@ -50,6 +50,12 @@ open dist/OpenComputerUse.app
.build/debug/OpenComputerUse mcp
```
+如果你想临时关闭点击时的软件 cursor overlay,可以显式传:
+
+```bash
+OPEN_COMPUTER_USE_VISUAL_CURSOR=0 .build/debug/OpenComputerUse mcp
+```
+
安装到本机 Codex 插件系统:
```bash
@@ -166,8 +172,11 @@ https://chatgpt.com/backend-api/codex/responses
## 当前取舍
- 普通 app 路径优先走 macOS Accessibility、窗口截图和 CGEvent 输入事件。
+- `click` 现在会额外拉起一层独立的软件 cursor overlay,用来给用户提供移动轨迹、点击 pulse 和短暂停留;它是可视化层,不改变底层 AX/HID 的动作决策,并会在动作结束后自动消失。
+- overlay 会优先在运行时从本机官方 `Codex Computer Use.app` 的 bundle 里读取 `SoftwareCursor` 资产并做一次轻量处理;如果本机没有官方 bundle,再回退到仓库内的矢量绘制样式。
+- overlay 不再固定置顶,而是尽量按目标 window 的编号和层级排到“目标 app 之上、其他当前更高层窗口之下”的位置。
- fixture app 为了提供稳定回归,会额外导出一份合成状态,并接受测试专用 command bridge。
-- 当前不复刻官方闭源 app 的签名边界、私有 IPC、overlay UI 和插件自安装逻辑。
+- 当前不复刻官方闭源 app 的签名边界、私有 IPC、完整 overlay choreography 和插件自安装逻辑。
## 许可证
diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/MCPAppRuntime.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/MCPAppRuntime.swift
new file mode 100644
index 0000000..461a5d8
--- /dev/null
+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/MCPAppRuntime.swift
@@ -0,0 +1,47 @@
+import AppKit
+import Foundation
+import OpenComputerUseKit
+
+final class MCPAppRuntime: NSObject, NSApplicationDelegate {
+ private let server: StdioMCPServer
+ private var runtimeError: Error?
+
+ private init(server: StdioMCPServer) {
+ self.server = server
+ }
+
+ @MainActor
+ static func run(server: StdioMCPServer) throws {
+ let application = NSApplication.shared
+ application.setActivationPolicy(.accessory)
+
+ let delegate = MCPAppRuntime(server: server)
+ application.delegate = delegate
+ application.run()
+
+ if let runtimeError = delegate.runtimeError {
+ throw runtimeError
+ }
+ }
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ Thread.detachNewThreadSelector(#selector(processStandardIO), toTarget: self, with: nil)
+ }
+
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
+ false
+ }
+
+ @objc
+ private func processStandardIO() {
+ do {
+ try server.run()
+ } catch {
+ runtimeError = error
+ }
+
+ DispatchQueue.main.async {
+ NSApp.terminate(nil)
+ }
+ }
+}
diff --git a/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift b/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift
index 069ce0f..7661897 100644
--- a/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift
+++ b/apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift
@@ -10,7 +10,14 @@ enum OpenComputerUseMain {
switch arguments.first {
case "mcp":
- try StdioMCPServer(service: service).run()
+ let server = StdioMCPServer(service: service)
+ if VisualCursorSupport.isEnabled {
+ try MainActor.assumeIsolated {
+ try MCPAppRuntime.run(server: server)
+ }
+ } else {
+ try server.run()
+ }
case "doctor":
let permissions = PermissionDiagnostics.current()
print(permissions.summary)
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index f9595a8..8fd1dca 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -16,6 +16,7 @@
- app discovery
- Accessibility / 窗口 snapshot
- 键鼠输入模拟
+ - software cursor overlay
- fixture test bridge
- `scripts/`
仓库级自动化命令,包括 smoke test、`.app` 打包入口,以及 `scripts/computer-use-cli/` 这个用于探测官方 bundled `computer-use` 的 Go helper。
@@ -35,6 +36,7 @@
### 2. MCP 层
- 当前只实现 `stdio` transport。
+- 当 `OPEN_COMPUTER_USE_VISUAL_CURSOR` 未被显式关闭时,`mcp` 命令会切到一个最小 AppKit runtime:主线程保留 event loop 承载 overlay UI,stdio server 仍在后台线程串行读取与响应。
- 请求 framing 采用一行一个 JSON-RPC message。
- 当前支持的 method:
- `initialize`
@@ -50,6 +52,9 @@
- `get_app_state` 优先走真实 AX / 窗口截图,但不再为了读状态而显式 `activate` 目标 app;当目标是仓库内 fixture app 时,回退到 fixture 导出的合成状态。
- MCP `tools/list` 的 description / input schema 当前按官方 `computer-use` 的 9 个 tools 文案和参数面收敛,尽量减少 host 侧提示词和 tool surface 偏差。
- 普通 app 的 element frame 当前按“窗口左上角为原点”的 window-relative 坐标输出,便于后续把 `element_index` 和截图坐标统一到同一套参考系。
+- `click` 在执行真实动作前后,会额外驱动一层透明 `SoftwareCursorOverlay` window:移动阶段走曲线动画,点击阶段做 pulse,动作结束后只保留一小段停驻与轻微 sway,随后自动淡出。
+- overlay 的 visual style 优先在运行时从本机官方 `Codex Computer Use.app` 的 `Package_ComputerUse.bundle` / `Package_SlimCore.bundle` 读取 `SoftwareCursor` 资产并做一次本地处理;如果本机没有这份 bundle,则回退到仓库内的矢量样式。
+- overlay 的层级不再固定 `.floating`;现在会跟随 snapshot 命中的目标 window id / layer,把自己排到该目标 window 之上,而不是粗暴压到所有前台 app 最上层。
- 动作型 tools 对普通 app 采用“非侵入优先,HID 兜底”策略:
- `AXUIElementPerformAction`
- `AXUIElementSetAttributeValue`
@@ -66,9 +71,9 @@
## 关键边界
-- 开源版当前不复刻官方闭源实现里的 caller signing、私有 IPC、overlay UI 和 plugin 自安装逻辑。
+- 开源版当前不复刻官方闭源实现里的 caller signing、私有 IPC、完整 overlay choreography 和 plugin 自安装逻辑。
- 因为官方 `SkyComputerUseClient` 带有宿主侧 launch constraints,普通 stdio MCP client 在本机上可能被系统直接杀掉;如果要探测官方 bundled `computer-use`,默认应通过 `scripts/computer-use-cli` 的 app-server 模式走已签名的 Codex 宿主。
-- 当前权限引导已经具备可运行 app、深链和拖拽辅助,但还没有完全复刻官方那套嵌入式 choreography / overlay 体验。
+- 当前权限引导已经具备可运行 app、深链和拖拽辅助;点击链路也已经补上独立 visual cursor、官方 asset fallback 和相对目标 window 的排序逻辑,但整体还没有完全复刻官方那套嵌入式 choreography / host 集成 / session approval 体验。
- screenshot 当前使用系统窗口截图 API,但默认直接以 MCP `image` content block 的 base64 PNG 返回,不再把普通 app 截图落盘到仓库或临时目录。
- 会话状态现在是进程内内存态,保存每个 app 最近一次 snapshot 和 element index 映射。
diff --git a/docs/exec-plans/completed/20260417-visual-cursor-overlay.md b/docs/exec-plans/completed/20260417-visual-cursor-overlay.md
new file mode 100644
index 0000000..f1a4bb7
--- /dev/null
+++ b/docs/exec-plans/completed/20260417-visual-cursor-overlay.md
@@ -0,0 +1,75 @@
+# Visual Cursor Overlay
+
+## 目标
+
+让 `open-computer-use` 在 `click` 路径上具备一套可见的软件 cursor overlay:点击前能沿曲线移动到目标点、点击时有明确的视觉反馈、点击后可以短暂停留并做轻微 idle sway,随后自动隐藏,同时继续保持当前 AX 优先、尽量不抢焦点的执行策略。
+
+## 范围
+
+- 包含:
+- 为 `mcp` 模式补一个可承载 AppKit overlay 的主线程 runtime。
+- 实现独立透明窗口的软件 cursor overlay。
+- 把 `click` 路径接到 overlay,但不改变现有 AX 优先 / HID fallback 的决策。
+- 增加必要测试,并同步 README、架构文档和 history。
+- 不包含:
+- 本轮不复刻官方闭源 cursor 的私有素材、完整 choreography 或私有事件注入链路。
+- 本轮不把 drag、scroll、键盘输入全部接入统一 overlay。
+
+## 背景
+
+- 相关文档:
+- `docs/ARCHITECTURE.md`
+- `docs/REPO_COLLAB_GUIDE.md`
+- `docs/references/codex-computer-use-reverse-engineering/software-cursor-overlay.md`
+- `docs/PLANS_GUIDE.md`
+- 相关代码路径:
+- `apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift`
+- `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift`
+- `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/InputSimulation.swift`
+- 已知约束:
+- 当前 `mcp` 模式是同步 `readLine()` 主循环,没有长期运行的 AppKit event loop。
+- 官方实现已有独立 `Software Cursor` 窗口和 Bezier motion 证据,但开源版目前没有 overlay UI。
+- 点击路径已经做过 AX 优先收敛,新增 overlay 不能把这层行为边界改坏。
+
+## 风险
+
+- 风险:为了跑 overlay 而改动 `mcp` runtime,可能影响现有 stdio 读写稳定性。
+- 缓解方式:保留最小变更面;只在 visual cursor 开启时切到 AppKit runtime,并让 stdin 读取仍保持串行。
+- 风险:overlay 的 AppKit UI 可能干扰 smoke suite 或普通 app 点击命中。
+- 缓解方式:overlay window 设为透明、忽略鼠标事件,并给 smoke suite 留显式关闭开关。
+- 风险:视觉动画与真实动作不同步,反而让用户更困惑。
+- 缓解方式:把 overlay 明确设计成“视觉提示层”,动作仍按现有 AX/HID 路径执行,并让点击脉冲只围绕最终目标点展开。
+
+## 里程碑
+
+1. Runtime 与 overlay 基础设施落地。
+2. `click` 路径接入 visual cursor。
+3. 验证、文档同步与归档。
+
+## 验证方式
+
+- 命令:
+- `swift test`
+- `./scripts/run-tool-smoke-tests.sh`
+- 当前结果:
+- `swift test` 通过。
+- `./scripts/run-tool-smoke-tests.sh` 仍然卡在既有 `list_apps`/fixture 约束:当前 `AppDiscovery.listCatalog()` 只收敛带 bundle-id 的 user-facing app,而 smoke fixture 是直接运行的可执行文件,不会出现在这条输出里;这不是本轮 visual cursor 引入的回归。
+- 后续 follow-up 已继续收敛 cursor 尺寸、官方 asset fallback 和相对目标 window 的排序逻辑;该部分继续保持 `swift test` 通过。
+- 手工检查:
+- 对一个真实 app 连续执行多次 `click`,确认 overlay 会在目标点附近短暂停留并做轻微 idle sway,随后自动消失。
+- 在 AX action 命中场景下,确认点击后前台 app 不会被额外 `activate`。
+- 观测检查:
+- `CGWindowListCopyWindowInfo` 能看到 `open-computer-use` 进程下存在一个透明 overlay window。
+
+## 进度记录
+
+- [x] 里程碑 1
+- [x] 里程碑 2
+- [x] 里程碑 3
+
+## 决策记录
+
+- 2026-04-17:优先实现“独立 overlay window + 曲线移动 + 点击脉冲 + idle sway”,不试图在这一轮复刻官方的全部私有 choreography。
+- 2026-04-17:`mcp` 模式只在 visual cursor 开启时切到 AppKit runtime,避免把一整轮 runtime 重构强行施加到所有无 UI 场景。
+- 2026-04-17:smoke 继续显式关闭 visual cursor;因为这条回归链路的目标是验证 tools 行为闭环,而不是验证 UI 动画本身。
+- 2026-04-17:对于官方 bundle 资产,优先采用“运行时读取 + 本地处理后绘制”的方式,而不是把闭源图片直接 vendoring 到开源仓库里。
diff --git a/docs/histories/2026-04/20260417-1901-visual-cursor-overlay.md b/docs/histories/2026-04/20260417-1901-visual-cursor-overlay.md
new file mode 100644
index 0000000..a6e07ac
--- /dev/null
+++ b/docs/histories/2026-04/20260417-1901-visual-cursor-overlay.md
@@ -0,0 +1,50 @@
+# Visual Cursor Overlay
+
+## 用户诉求
+
+用户希望优化 `click` 的观感,对齐官方 `computer-use` 那种“不是抢真实鼠标,而是自己显化一个 cursor overlay 给用户看”的体验,并特别指出:
+
+- 空闲时 cursor 会轻微晃动;
+- 移动时会沿弧线前进并带一点方向变化;
+- 点击时不应因为这层可视化而重新激活目标 app 或抢走当前焦点。
+
+用户还提供了本地录屏 `00:59 ~ 01:03` 作为观察样本,并让这轮顺手结合官方 `Codex Computer Use.app` 与仓库内现有逆向资料一起分析。
+
+## 这次改了什么
+
+- **[MCP runtime]**:给 `mcp` 模式补了一个最小 AppKit runtime。启用 visual cursor 时,主线程保持 event loop 以承载 overlay UI,stdio server 仍然在后台线程按原样跑。
+- **[软件 cursor overlay]**:新增 `SoftwareCursorOverlay`,用透明 `NSPanel` 画一个独立的软件 cursor,并支持曲线路径移动、点击 pulse、点击后 idle sway,以及 `OPEN_COMPUTER_USE_VISUAL_CURSOR=0` 显式关闭。
+- **[点击路径接线]**:`ComputerUseService.click` 现在会在执行真实动作前先移动 visual cursor,再继续走原有 AX 优先 / HID fallback 策略;动作完成后再做 pulse 和停驻,不因为加了可视化而改变底层点击决策。
+- **[测试与脚本]**:为 visual cursor 增加了环境变量和几条纯逻辑单测;smoke 脚本里显式关闭 overlay,避免 UI 动画影响回归稳定性。
+- **[文档同步]**:更新了 `README.md`、`docs/ARCHITECTURE.md` 和执行计划,明确开源版现在已经有一层 click visual cursor,但仍未复刻官方完整 choreography。
+
+## 设计动机
+
+官方 bundle 和既有逆向文档已经足够说明,那个给用户看的 pointer 大概率是独立 `Software Cursor` window,而不是系统真实鼠标。对开源版来说,最合理的收敛方式不是继续把所有东西都塞进 HID 事件路径里,而是明确把“真实动作执行”与“给用户看的可视层”拆开:
+
+- 真实动作继续优先走 AX,尽量不抢焦点。
+- visual cursor 只负责解释“现在在点哪里、准备点什么”。
+- 即使底层仍有 HID fallback,这层可视化也能先把产品观感和可观测性往官方方向推一大步。
+
+## 关键文件
+
+- `apps/OpenComputerUse/Sources/OpenComputerUse/MCPAppRuntime.swift`
+- `apps/OpenComputerUse/Sources/OpenComputerUse/OpenComputerUseMain.swift`
+- `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift`
+- `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift`
+- `packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift`
+- `README.md`
+- `docs/ARCHITECTURE.md`
+
+## [2026-04-17 19:52] | Follow-up: 缩小 cursor 并按目标 window 排序
+
+### 额外改动
+
+- **[官方 asset fallback]**:继续沿用同一份 `SoftwareCursorOverlay`,但 visual style 现在会优先在运行时从本机官方 `Codex Computer Use.app` 的 bundle 里读取 `SoftwareCursor` 资产,再做一层本地处理后用于绘制;这样既能复用官方素材,又不用把闭源资产直接 vendor 进仓库。
+- **[尺寸和运动调参]**:把 cursor 的默认显示尺寸明显收小,并把首次入场偏移和移动时长拉长,避免“已经有 cursor 但看起来几乎没动”的观感。
+- **[相对目标窗口排序]**:给 `AppSnapshot` 补了目标 `windowID` / `layer`,overlay 不再固定 `.floating` 置顶;现在会尽量排在目标 window 之上,但保留在更高层前台窗口之下,更接近官方“操作 A 时 cursor 不会穿透到 B 前面”的行为。
+- **[动作后自动隐藏]**:overlay 不再无限期停在屏幕上。点击完成或异常 settle 后,只保留一小段停驻和轻微 sway,随后自动淡出并 `orderOut`,下次动作再重新出现。
+
+### 为什么这么做
+
+用户指出两个很具体的问题:cursor 太大,以及当用户正停在 B 应用上时,操作 A 的 cursor 不该压到 B 前面。前者说明第一版 overlay 还停留在“证明这条链路能跑通”的阶段,尺寸和素材选择都太粗;后者说明 window ordering 不能只看“要不要可见”,还要看“应该压在哪层”。这个 follow-up 的重点,就是把 visual cursor 从“有”推进到“手感更合理”。
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift
index b92e8a0..bcebb24 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/AccessibilitySnapshot.swift
@@ -30,6 +30,8 @@ public struct AppSnapshot {
public let app: RunningAppDescriptor
public let windowTitle: String?
public let windowBounds: CGRect?
+ let targetWindowID: CGWindowID?
+ let targetWindowLayer: Int?
public let screenshotPNGData: Data?
let mode: SnapshotMode
let treeLines: [String]
@@ -101,6 +103,8 @@ enum SnapshotBuilder {
app: app,
windowTitle: windowTitle,
windowBounds: windowBounds,
+ targetWindowID: windowCapture?.windowID,
+ targetWindowLayer: windowCapture?.layer,
screenshotPNGData: screenshotPNGData,
mode: .accessibility,
treeLines: renderer.lines,
@@ -172,6 +176,8 @@ enum SnapshotBuilder {
app: app,
windowTitle: state.windowTitle,
windowBounds: state.windowBounds.cgRect,
+ targetWindowID: nil,
+ targetWindowLayer: nil,
screenshotPNGData: nil,
mode: .fixture,
treeLines: lines,
@@ -182,6 +188,8 @@ enum SnapshotBuilder {
}
private struct WindowCapture {
+ let windowID: CGWindowID
+ let layer: Int
let bounds: CGRect
let image: CGImage?
@@ -190,13 +198,12 @@ private struct WindowCapture {
return nil
}
- let candidates = infoList.compactMap { info -> (CGWindowID, CGRect, String?, Int)? in
+ let candidates = infoList.compactMap { info -> (CGWindowID, Int, CGRect, String?, Int)? in
guard
let ownerPID = info[kCGWindowOwnerPID as String] as? pid_t,
ownerPID == pid,
let number = info[kCGWindowNumber as String] as? NSNumber,
let layer = info[kCGWindowLayer as String] as? Int,
- layer == 0,
let boundsDictionary = info[kCGWindowBounds as String] as? NSDictionary,
let bounds = CGRect(dictionaryRepresentation: boundsDictionary)
else {
@@ -205,33 +212,33 @@ private struct WindowCapture {
let title = info[kCGWindowName as String] as? String
let area = Int(bounds.width * bounds.height)
- return (CGWindowID(number.uint32Value), bounds, title, area)
+ return (CGWindowID(number.uint32Value), layer, bounds, title, area)
}
guard let best = candidates.sorted(by: { lhs, rhs in
if let titleHint {
- if lhs.2 == titleHint && rhs.2 != titleHint {
+ if lhs.3 == titleHint && rhs.3 != titleHint {
return true
}
- if rhs.2 == titleHint && lhs.2 != titleHint {
+ if rhs.3 == titleHint && lhs.3 != titleHint {
return false
}
}
- return lhs.3 > rhs.3
+ return lhs.4 > rhs.4
}).first else {
return nil
}
let image = CGWindowListCreateImage(
- best.1,
+ best.2,
.optionIncludingWindow,
best.0,
[.bestResolution, .boundsIgnoreFraming]
)
- return WindowCapture(bounds: best.1, image: image)
+ return WindowCapture(windowID: best.0, layer: best.1, bounds: best.2, image: image)
}
func pngDataIfAvailable() -> Data? {
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift
index f5a387d..c4f66d9 100644
--- a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseService.swift
@@ -45,24 +45,58 @@ public final class ComputerUseService {
if let elementIndex {
let record = try lookupElement(snapshot: snapshot, index: elementIndex)
-
- if try performPreferredClick(on: record, button: button, clickCount: clickCount) {
- Thread.sleep(forTimeInterval: 0.15)
- } else if let point = try globalPoint(for: record, snapshot: snapshot) {
- InputSimulation.prepareAppForGlobalPointerInput(snapshot.app)
- try InputSimulation.clickGlobally(at: point, button: button, clickCount: clickCount)
- } else {
+ guard let targetPoint = try globalPoint(for: record, snapshot: snapshot) else {
throw ComputerUseError.stateUnavailable("element \(elementIndex) has no clickable frame")
}
+ let targetWindow = cursorTargetWindow(for: snapshot)
+
+ VisualCursorSupport.performOnMain {
+ SoftwareCursorOverlay.moveCursor(to: targetPoint, in: targetWindow)
+ }
+
+ do {
+ if try performPreferredClick(on: record, button: button, clickCount: clickCount) {
+ Thread.sleep(forTimeInterval: 0.15)
+ } else {
+ InputSimulation.prepareAppForGlobalPointerInput(snapshot.app)
+ try InputSimulation.clickGlobally(at: targetPoint, button: button, clickCount: clickCount)
+ }
+ } catch {
+ VisualCursorSupport.performOnMain {
+ SoftwareCursorOverlay.settle(at: targetPoint, in: targetWindow)
+ }
+ throw error
+ }
+
+ VisualCursorSupport.performOnMain {
+ SoftwareCursorOverlay.pulseClick(at: targetPoint, clickCount: clickCount, mouseButton: button, in: targetWindow)
+ }
} else if let x, let y {
let point = CGPoint(x: x, y: y)
+ let targetPoint = try screenshotToGlobalPoint(snapshot: snapshot, x: x, y: y)
+ let targetWindow = cursorTargetWindow(for: snapshot)
- if let record = try hitTestElement(at: point, in: snapshot) ?? bestElement(containing: point, in: snapshot),
- try performPreferredClick(on: record, button: button, clickCount: clickCount) {
- Thread.sleep(forTimeInterval: 0.15)
- } else {
- InputSimulation.prepareAppForGlobalPointerInput(snapshot.app)
- try InputSimulation.clickGlobally(at: try screenshotToGlobalPoint(snapshot: snapshot, x: x, y: y), button: button, clickCount: clickCount)
+ VisualCursorSupport.performOnMain {
+ SoftwareCursorOverlay.moveCursor(to: targetPoint, in: targetWindow)
+ }
+
+ do {
+ if let record = try hitTestElement(at: point, in: snapshot) ?? bestElement(containing: point, in: snapshot),
+ try performPreferredClick(on: record, button: button, clickCount: clickCount) {
+ Thread.sleep(forTimeInterval: 0.15)
+ } else {
+ InputSimulation.prepareAppForGlobalPointerInput(snapshot.app)
+ try InputSimulation.clickGlobally(at: targetPoint, button: button, clickCount: clickCount)
+ }
+ } catch {
+ VisualCursorSupport.performOnMain {
+ SoftwareCursorOverlay.settle(at: targetPoint, in: targetWindow)
+ }
+ throw error
+ }
+
+ VisualCursorSupport.performOnMain {
+ SoftwareCursorOverlay.pulseClick(at: targetPoint, clickCount: clickCount, mouseButton: button, in: targetWindow)
}
} else {
throw ComputerUseError.invalidArguments("click requires either element_index or x/y")
@@ -446,6 +480,17 @@ public final class ComputerUseService {
return identifier
}
+ private func cursorTargetWindow(for snapshot: AppSnapshot) -> CursorTargetWindow? {
+ guard let windowID = snapshot.targetWindowID else {
+ return nil
+ }
+
+ return CursorTargetWindow(
+ windowID: windowID,
+ layer: snapshot.targetWindowLayer ?? 0
+ )
+ }
+
private func snapshotResult(for snapshot: AppSnapshot, style: SnapshotTextStyle) -> ToolCallResult {
var content = [ToolResultContentItem.text(snapshot.renderedText(style: style))]
if let screenshotPNGData = snapshot.screenshotPNGData {
diff --git a/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift
new file mode 100644
index 0000000..38ef282
--- /dev/null
+++ b/packages/OpenComputerUseKit/Sources/OpenComputerUseKit/SoftwareCursorOverlay.swift
@@ -0,0 +1,807 @@
+import AppKit
+import CoreGraphics
+import Foundation
+import QuartzCore
+
+public enum VisualCursorSupport {
+ public static var isEnabled: Bool {
+ visualCursorEnabled(environment: ProcessInfo.processInfo.environment)
+ }
+
+ static func performOnMain(_ body: @escaping @MainActor () -> Void) {
+ if Thread.isMainThread {
+ MainActor.assumeIsolated {
+ body()
+ }
+ return
+ }
+
+ DispatchQueue.main.sync {
+ MainActor.assumeIsolated {
+ body()
+ }
+ }
+ }
+}
+
+func visualCursorEnabled(environment: [String: String]) -> Bool {
+ guard let rawValue = environment["OPEN_COMPUTER_USE_VISUAL_CURSOR"]?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() else {
+ return true
+ }
+
+ return !["0", "false", "no", "off"].contains(rawValue)
+}
+
+struct CursorTargetWindow: Equatable, Sendable {
+ let windowID: CGWindowID
+ let layer: Int
+}
+
+struct CursorWindowGeometry {
+ let windowSize: CGSize
+ let tipAnchor: CGPoint
+
+ func origin(forTipPosition tipPosition: CGPoint) -> CGPoint {
+ CGPoint(
+ x: tipPosition.x - tipAnchor.x,
+ y: tipPosition.y - tipAnchor.y
+ )
+ }
+
+ func tipPosition(forOrigin origin: CGPoint) -> CGPoint {
+ CGPoint(
+ x: origin.x + tipAnchor.x,
+ y: origin.y + tipAnchor.y
+ )
+ }
+}
+
+struct CursorMotionPath {
+ let start: CGPoint
+ let control1: CGPoint
+ let control2: CGPoint
+ let end: CGPoint
+
+ init(start: CGPoint, end: CGPoint) {
+ let delta = CGVector(dx: end.x - start.x, dy: end.y - start.y)
+ let distance = max(hypot(delta.dx, delta.dy), 1)
+ let normal = normalized(CGVector(dx: -delta.dy, dy: delta.dx))
+ let curveDirection: CGFloat = delta.dx >= 0 ? 1 : -1
+ let curveAmount = min(max(distance * 0.22, 28), 110)
+ let controlOffset = CGPoint(x: normal.dx * curveAmount * curveDirection, y: normal.dy * curveAmount * curveDirection)
+
+ self.start = start
+ self.end = end
+ self.control1 = CGPoint(
+ x: start.x + (delta.dx * 0.18) + controlOffset.x,
+ y: start.y + (delta.dy * 0.10) + controlOffset.y
+ )
+ self.control2 = CGPoint(
+ x: start.x + (delta.dx * 0.80) + (controlOffset.x * 0.48),
+ y: start.y + (delta.dy * 0.96) + (controlOffset.y * 0.48)
+ )
+ }
+
+ func point(at t: CGFloat) -> CGPoint {
+ let omt = 1 - t
+ let omt2 = omt * omt
+ let t2 = t * t
+
+ return CGPoint(
+ x: (omt2 * omt * start.x)
+ + (3 * omt2 * t * control1.x)
+ + (3 * omt * t2 * control2.x)
+ + (t2 * t * end.x),
+ y: (omt2 * omt * start.y)
+ + (3 * omt2 * t * control1.y)
+ + (3 * omt * t2 * control2.y)
+ + (t2 * t * end.y)
+ )
+ }
+
+ func tangent(at t: CGFloat) -> CGVector {
+ let omt = 1 - t
+ return CGVector(
+ dx: (3 * omt * omt * (control1.x - start.x))
+ + (6 * omt * t * (control2.x - control1.x))
+ + (3 * t * t * (end.x - control2.x)),
+ dy: (3 * omt * omt * (control1.y - start.y))
+ + (6 * omt * t * (control2.y - control1.y))
+ + (3 * t * t * (end.y - control2.y))
+ )
+ }
+}
+
+private struct ProcessedCursorImage {
+ let image: NSImage
+ let tipAnchor: CGPoint
+}
+
+private struct CursorArtwork {
+ let image: NSImage?
+ let geometry: CursorWindowGeometry
+ let drawRect: CGRect
+ let shadowBlur: CGFloat
+ let shadowOffset: CGSize
+ let shadowColor: NSColor
+ let vectorScale: CGFloat
+
+ static let active: CursorArtwork = loadOfficialSoftwareCursor() ?? fallback
+
+ private static let fallback = CursorArtwork(
+ image: nil,
+ geometry: CursorWindowGeometry(
+ windowSize: CGSize(width: 56, height: 56),
+ tipAnchor: CGPoint(x: 10, y: 43)
+ ),
+ drawRect: CGRect(x: 0, y: 0, width: 56, height: 56),
+ shadowBlur: 12,
+ shadowOffset: CGSize(width: 0, height: -2),
+ shadowColor: NSColor.black.withAlphaComponent(0.24),
+ vectorScale: 0.40
+ )
+
+ private static func loadOfficialSoftwareCursor() -> CursorArtwork? {
+ for bundle in officialCursorBundles() {
+ guard let image = bundle.image(forResource: NSImage.Name("SoftwareCursor")),
+ let processed = processOfficialCursor(image)
+ else {
+ continue
+ }
+
+ let targetHeight: CGFloat = 26
+ let scale = targetHeight / processed.image.size.height
+ let imageSize = CGSize(
+ width: processed.image.size.width * scale,
+ height: processed.image.size.height * scale
+ )
+ let margin = NSEdgeInsets(top: 4, left: 3, bottom: 7, right: 5)
+ let tipAnchor = CGPoint(
+ x: margin.left + (processed.tipAnchor.x * scale),
+ y: margin.bottom + (processed.tipAnchor.y * scale)
+ )
+
+ return CursorArtwork(
+ image: processed.image,
+ geometry: CursorWindowGeometry(
+ windowSize: CGSize(
+ width: imageSize.width + margin.left + margin.right,
+ height: imageSize.height + margin.top + margin.bottom
+ ),
+ tipAnchor: tipAnchor
+ ),
+ drawRect: CGRect(x: margin.left, y: margin.bottom, width: imageSize.width, height: imageSize.height),
+ shadowBlur: 17,
+ shadowOffset: CGSize(width: 0, height: -3),
+ shadowColor: NSColor.black.withAlphaComponent(0.26),
+ vectorScale: 0
+ )
+ }
+
+ return nil
+ }
+
+ private static func officialCursorBundles() -> [Bundle] {
+ let root = URL(fileURLWithPath: NSHomeDirectory())
+ .appendingPathComponent(".codex/plugins/cache/openai-bundled/computer-use", isDirectory: true)
+
+ guard let versions = try? FileManager.default.contentsOfDirectory(
+ at: root,
+ includingPropertiesForKeys: [.isDirectoryKey],
+ options: [.skipsHiddenFiles]
+ ) else {
+ return []
+ }
+
+ let sortedVersions = versions.sorted { $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedDescending }
+
+ let bundlePaths = sortedVersions.flatMap { versionURL in
+ [
+ versionURL.appendingPathComponent("Codex Computer Use.app/Contents/Resources/Package_ComputerUse.bundle", isDirectory: true),
+ versionURL.appendingPathComponent("Codex Computer Use.app/Contents/Resources/Package_SlimCore.bundle", isDirectory: true),
+ ]
+ }
+
+ return bundlePaths.compactMap { Bundle(path: $0.path) }
+ }
+
+ private static func processOfficialCursor(_ image: NSImage) -> ProcessedCursorImage? {
+ guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
+ return nil
+ }
+
+ let bitmap = NSBitmapImageRep(cgImage: cgImage)
+ let width = bitmap.pixelsWide
+ let height = bitmap.pixelsHigh
+ guard width > 0, height > 0 else {
+ return nil
+ }
+
+ let highlightThreshold: CGFloat = 0.83
+ let tint = NSColor(calibratedWhite: 0.92, alpha: 1).usingColorSpace(.deviceRGB) ?? NSColor.white
+ let tintRed = UInt8(tint.redComponent * 255)
+ let tintGreen = UInt8(tint.greenComponent * 255)
+ let tintBlue = UInt8(tint.blueComponent * 255)
+
+ var minX = width
+ var maxX = 0
+ var minY = height
+ var maxY = 0
+ var tipPixel = CGPoint.zero
+ var tipScore = -CGFloat.greatestFiniteMagnitude
+
+ for y in 0..<height {
+ for x in 0..<width {
+ guard let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB) else {
+ continue
+ }
+
+ let alpha = color.alphaComponent
+ let brightness = max(color.redComponent, color.greenComponent, color.blueComponent)
+ guard alpha > 0.08, brightness > highlightThreshold else {
+ continue
+ }
+
+ minX = Swift.min(minX, x)
+ maxX = Swift.max(maxX, x)
+ minY = Swift.min(minY, y)
+ maxY = Swift.max(maxY, y)
+
+ let score = (CGFloat(y) * 3) - CGFloat(x)
+ if score > tipScore {
+ tipScore = score
+ tipPixel = CGPoint(x: x, y: y)
+ }
+ }
+ }
+
+ guard minX <= maxX, minY <= maxY else {
+ return nil
+ }
+
+ let padding = 3
+ minX = Swift.max(0, minX - padding)
+ minY = Swift.max(0, minY - padding)
+ maxX = Swift.min(width - 1, maxX + padding)
+ maxY = Swift.min(height - 1, maxY + padding)
+
+ let croppedWidth = maxX - minX + 1
+ let croppedHeight = maxY - minY + 1
+
+ guard let output = NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: croppedWidth,
+ pixelsHigh: croppedHeight,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ ), let bitmapData = output.bitmapData else {
+ return nil
+ }
+
+ for y in minY...maxY {
+ for x in minX...maxX {
+ guard let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB) else {
+ continue
+ }
+
+ let alpha = color.alphaComponent
+ let brightness = max(color.redComponent, color.greenComponent, color.blueComponent)
+ let whiteness = CGFloat.clamped((brightness - highlightThreshold) / (1 - highlightThreshold), lower: 0, upper: 1)
+ let resultAlpha = UInt8((alpha * whiteness) * 255)
+
+ let localX = x - minX
+ let localY = y - minY
+ let offset = (localY * output.bytesPerRow) + (localX * 4)
+ bitmapData[offset] = tintRed
+ bitmapData[offset + 1] = tintGreen
+ bitmapData[offset + 2] = tintBlue
+ bitmapData[offset + 3] = resultAlpha
+ }
+ }
+
+ let processed = NSImage(size: CGSize(width: croppedWidth, height: croppedHeight))
+ processed.addRepresentation(output)
+
+ return ProcessedCursorImage(
+ image: processed,
+ tipAnchor: CGPoint(
+ x: tipPixel.x - CGFloat(minX),
+ y: tipPixel.y - CGFloat(minY)
+ )
+ )
+ }
+}
+
+@MainActor
+enum SoftwareCursorOverlay {
+ private static let artwork = CursorArtwork.active
+ private static let baseHeading = 3 * CGFloat.pi / 4
+ private static var panel: CursorPanel?
+ private static var cursorView: SoftwareCursorView?
+ private static var restingTipPosition: CGPoint?
+ private static var displayedTipPosition: CGPoint?
+ private static var activeTargetWindow: CursorTargetWindow?
+ private static var idleTimer: Timer?
+ private static var hideTimer: Timer?
+ private static var idlePhase: CGFloat = 0
+
+ static func moveCursor(to targetPoint: CGPoint, in targetWindow: CursorTargetWindow?) {
+ guard VisualCursorSupport.isEnabled, canPresentOverlay else {
+ return
+ }
+
+ prepareWindowIfNeeded()
+ stopIdleAnimation()
+ cancelPendingHide()
+ configureOrdering(relativeTo: targetWindow)
+
+ let constrainedTarget = clampTipPosition(targetPoint)
+ let startPoint = displayedTipPosition ?? defaultAppearancePoint(for: constrainedTarget)
+
+ panel?.alphaValue = 1
+ placeCursor(at: startPoint, rotation: 0, clickProgress: 0)
+
+ if distanceBetween(startPoint, constrainedTarget) > 2 {
+ animateMove(from: startPoint, to: constrainedTarget)
+ }
+ }
+
+ static func pulseClick(at targetPoint: CGPoint, clickCount: Int, mouseButton: MouseButtonKind, in targetWindow: CursorTargetWindow?) {
+ guard VisualCursorSupport.isEnabled, canPresentOverlay else {
+ return
+ }
+
+ configureOrdering(relativeTo: targetWindow)
+ let constrainedTarget = clampTipPosition(targetPoint)
+ animateClickPulse(at: constrainedTarget, clickCount: max(clickCount, 1), mouseButton: mouseButton)
+ restingTipPosition = constrainedTarget
+ displayedTipPosition = constrainedTarget
+ startIdleAnimation()
+ scheduleHide(after: 0.55)
+ }
+
+ static func settle(at targetPoint: CGPoint, in targetWindow: CursorTargetWindow?) {
+ guard VisualCursorSupport.isEnabled, canPresentOverlay else {
+ return
+ }
+
+ configureOrdering(relativeTo: targetWindow)
+ let constrainedTarget = clampTipPosition(targetPoint)
+ restingTipPosition = constrainedTarget
+ displayedTipPosition = constrainedTarget
+ placeCursor(at: constrainedTarget, rotation: 0, clickProgress: 0)
+ startIdleAnimation()
+ scheduleHide(after: 0.45)
+ }
+
+ static func reset() {
+ stopIdleAnimation()
+ cancelPendingHide()
+ displayedTipPosition = nil
+ restingTipPosition = nil
+ activeTargetWindow = nil
+ panel?.orderOut(nil)
+ }
+
+ private static var canPresentOverlay: Bool {
+ !NSScreen.screens.isEmpty
+ }
+
+ private static func prepareWindowIfNeeded() {
+ guard panel == nil else {
+ return
+ }
+
+ let panel = CursorPanel(
+ contentRect: CGRect(origin: .zero, size: artwork.geometry.windowSize),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
+ panel.level = .normal
+ panel.backgroundColor = .clear
+ panel.isOpaque = false
+ panel.hasShadow = false
+ panel.ignoresMouseEvents = true
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
+ panel.animationBehavior = .none
+
+ let view = SoftwareCursorView(frame: CGRect(origin: .zero, size: artwork.geometry.windowSize), artwork: artwork)
+ panel.contentView = view
+
+ self.panel = panel
+ self.cursorView = view
+ }
+
+ private static func configureOrdering(relativeTo targetWindow: CursorTargetWindow?) {
+ guard let panel else {
+ return
+ }
+
+ let desiredLevel = NSWindow.Level(rawValue: targetWindow?.layer ?? 0)
+ if panel.level != desiredLevel {
+ panel.level = desiredLevel
+ }
+
+ if activeTargetWindow != targetWindow || panel.isVisible == false {
+ if let targetWindow {
+ panel.order(.above, relativeTo: Int(targetWindow.windowID))
+ } else {
+ panel.orderFront(nil)
+ }
+ activeTargetWindow = targetWindow
+ }
+ }
+
+ private static func animateMove(from start: CGPoint, to end: CGPoint) {
+ let path = CursorMotionPath(start: start, end: end)
+ let duration = min(max(TimeInterval(distanceBetween(start, end) / 1050), 0.24), 0.56)
+ let startTime = CACurrentMediaTime()
+
+ while true {
+ let elapsed = CACurrentMediaTime() - startTime
+ let rawProgress = min(max(elapsed / duration, 0), 1)
+ let eased = easeInOut(rawProgress)
+ let point = path.point(at: eased)
+ let tangent = path.tangent(at: max(min(eased, 0.999), 0.001))
+ let rotation = rotationOffset(for: tangent)
+
+ placeCursor(at: point, rotation: rotation, clickProgress: 0)
+
+ if rawProgress >= 1 {
+ break
+ }
+
+ pumpFrame()
+ }
+ }
+
+ private static func animateClickPulse(at point: CGPoint, clickCount: Int, mouseButton: MouseButtonKind) {
+ let pulseBias: CGFloat = mouseButton == .right ? 0.82 : 1
+
+ for pulse in 0..<clickCount {
+ let duration = 0.16
+ let startTime = CACurrentMediaTime()
+
+ while true {
+ let elapsed = CACurrentMediaTime() - startTime
+ let rawProgress = min(max(elapsed / duration, 0), 1)
+ let clickProgress = sin(rawProgress * .pi) * pulseBias
+
+ placeCursor(at: point, rotation: 0, clickProgress: clickProgress)
+
+ if rawProgress >= 1 {
+ break
+ }
+
+ pumpFrame()
+ }
+
+ if pulse < clickCount - 1 {
+ pause(for: 0.05)
+ }
+ }
+
+ placeCursor(at: point, rotation: 0, clickProgress: 0)
+ }
+
+ private static func startIdleAnimation() {
+ guard canPresentOverlay, let restingTipPosition else {
+ return
+ }
+
+ idlePhase = 0
+ let timer = Timer(timeInterval: 1 / 60, repeats: true) { _ in
+ MainActor.assumeIsolated {
+ guard let cursorView, let panel else {
+ return
+ }
+
+ idlePhase += 0.05
+ let offset = CGPoint(
+ x: sin(idlePhase) * 1.6,
+ y: cos(idlePhase * 0.47) * 0.7
+ )
+ let tipPosition = CGPoint(
+ x: restingTipPosition.x + offset.x,
+ y: restingTipPosition.y + offset.y
+ )
+
+ cursorView.rotation = sin(idlePhase * 0.8) * 0.02
+ cursorView.clickProgress = 0
+ cursorView.needsDisplay = true
+
+ panel.setFrameOrigin(artwork.geometry.origin(forTipPosition: tipPosition))
+ displayedTipPosition = tipPosition
+ }
+ }
+
+ RunLoop.main.add(timer, forMode: .common)
+ idleTimer = timer
+
+ placeCursor(at: restingTipPosition, rotation: 0, clickProgress: 0)
+ }
+
+ private static func stopIdleAnimation() {
+ idleTimer?.invalidate()
+ idleTimer = nil
+ }
+
+ private static func scheduleHide(after delay: TimeInterval) {
+ cancelPendingHide()
+ let timer = Timer(timeInterval: delay, repeats: false) { _ in
+ MainActor.assumeIsolated {
+ hideOverlay()
+ }
+ }
+ RunLoop.main.add(timer, forMode: .common)
+ hideTimer = timer
+ }
+
+ private static func cancelPendingHide() {
+ hideTimer?.invalidate()
+ hideTimer = nil
+ }
+
+ private static func hideOverlay() {
+ guard let panel else {
+ return
+ }
+
+ stopIdleAnimation()
+ cancelPendingHide()
+
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.12
+ context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ panel.animator().alphaValue = 0
+ } completionHandler: {
+ MainActor.assumeIsolated {
+ panel.orderOut(nil)
+ panel.alphaValue = 1
+ displayedTipPosition = nil
+ restingTipPosition = nil
+ activeTargetWindow = nil
+ }
+ }
+ }
+
+ private static func defaultAppearancePoint(for targetPoint: CGPoint) -> CGPoint {
+ clampTipPosition(
+ CGPoint(
+ x: targetPoint.x + 72,
+ y: targetPoint.y - 54
+ )
+ )
+ }
+
+ private static func placeCursor(at tipPosition: CGPoint, rotation: CGFloat, clickProgress: CGFloat) {
+ guard let panel, let cursorView else {
+ return
+ }
+
+ panel.setFrameOrigin(artwork.geometry.origin(forTipPosition: tipPosition))
+ cursorView.rotation = rotation
+ cursorView.clickProgress = clickProgress
+ cursorView.needsDisplay = true
+ displayedTipPosition = tipPosition
+ }
+
+ private static func clampTipPosition(_ tipPosition: CGPoint) -> CGPoint {
+ guard let screen = screen(containing: tipPosition) ?? NSScreen.main ?? NSScreen.screens.first else {
+ return tipPosition
+ }
+
+ let visibleFrame = screen.visibleFrame
+ let minX = visibleFrame.minX + artwork.geometry.tipAnchor.x
+ let maxX = visibleFrame.maxX - (artwork.geometry.windowSize.width - artwork.geometry.tipAnchor.x)
+ let minY = visibleFrame.minY + artwork.geometry.tipAnchor.y
+ let maxY = visibleFrame.maxY - (artwork.geometry.windowSize.height - artwork.geometry.tipAnchor.y)
+
+ return CGPoint(
+ x: tipPosition.x.clamped(to: minX...maxX),
+ y: tipPosition.y.clamped(to: minY...maxY)
+ )
+ }
+
+ private static func screen(containing point: CGPoint) -> NSScreen? {
+ NSScreen.screens.first { $0.frame.contains(point) }
+ }
+
+ private static func rotationOffset(for tangent: CGVector) -> CGFloat {
+ guard tangent.dx != 0 || tangent.dy != 0 else {
+ return 0
+ }
+
+ let heading = atan2(tangent.dy, tangent.dx)
+ let delta = normalize(angle: heading - baseHeading)
+ return delta.clamped(to: -0.22...0.22)
+ }
+
+ private static func normalize(angle: CGFloat) -> CGFloat {
+ var value = angle
+ while value > .pi {
+ value -= 2 * .pi
+ }
+ while value < -.pi {
+ value += 2 * .pi
+ }
+ return value
+ }
+
+ private static func easeInOut(_ value: CGFloat) -> CGFloat {
+ value < 0.5
+ ? 4 * value * value * value
+ : 1 - pow(-2 * value + 2, 3) / 2
+ }
+
+ private static func pumpFrame() {
+ RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(1 / 120))
+ }
+
+ private static func pause(for duration: TimeInterval) {
+ let start = CACurrentMediaTime()
+ while CACurrentMediaTime() - start < duration {
+ pumpFrame()
+ }
+ }
+
+ private static func distanceBetween(_ lhs: CGPoint, _ rhs: CGPoint) -> CGFloat {
+ hypot(rhs.x - lhs.x, rhs.y - lhs.y)
+ }
+}
+
+private final class CursorPanel: NSPanel {
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+}
+
+private final class SoftwareCursorView: NSView {
+ private let artwork: CursorArtwork
+
+ var rotation: CGFloat = 0
+ var clickProgress: CGFloat = 0
+
+ init(frame frameRect: NSRect, artwork: CursorArtwork) {
+ self.artwork = artwork
+ super.init(frame: frameRect)
+ wantsLayer = true
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+ override var isOpaque: Bool {
+ false
+ }
+
+ override func draw(_ dirtyRect: NSRect) {
+ super.draw(dirtyRect)
+
+ NSColor.clear.setFill()
+ dirtyRect.fill()
+
+ let compression = clickProgress * 0.05
+ let scaleX = 1 - compression
+ let scaleY = 1 + (compression * 0.24)
+
+ let anchor = artwork.geometry.tipAnchor
+ let context = NSGraphicsContext.current?.cgContext
+ context?.saveGState()
+ context?.translateBy(x: anchor.x, y: anchor.y)
+ context?.rotate(by: rotation)
+ context?.scaleBy(x: scaleX, y: scaleY)
+ context?.translateBy(x: -anchor.x, y: -anchor.y)
+
+ let shadowOval = NSBezierPath(ovalIn: CGRect(x: anchor.x - 7, y: anchor.y - 49, width: 22, height: 7))
+ NSGraphicsContext.saveGraphicsState()
+ let ovalShadow = NSShadow()
+ ovalShadow.shadowBlurRadius = 10 + (clickProgress * 2)
+ ovalShadow.shadowOffset = CGSize(width: 0, height: -1)
+ ovalShadow.shadowColor = NSColor.black.withAlphaComponent(0.14)
+ ovalShadow.set()
+ NSColor.black.withAlphaComponent(0.09).setFill()
+ shadowOval.fill()
+ NSGraphicsContext.restoreGraphicsState()
+
+ if let image = artwork.image {
+ NSGraphicsContext.saveGraphicsState()
+ let shadow = NSShadow()
+ shadow.shadowBlurRadius = artwork.shadowBlur + (clickProgress * 4)
+ shadow.shadowOffset = artwork.shadowOffset
+ shadow.shadowColor = artwork.shadowColor
+ shadow.set()
+ image.draw(in: artwork.drawRect, from: .zero, operation: .sourceOver, fraction: 1)
+ NSGraphicsContext.restoreGraphicsState()
+ } else {
+ let shadowPath = cursorPath(anchor: anchor, scale: artwork.vectorScale, xOffset: 2, yOffset: -2)
+ NSGraphicsContext.saveGraphicsState()
+ let shadow = NSShadow()
+ shadow.shadowBlurRadius = artwork.shadowBlur + (clickProgress * 5)
+ shadow.shadowOffset = artwork.shadowOffset
+ shadow.shadowColor = artwork.shadowColor
+ shadow.set()
+ NSColor.black.withAlphaComponent(0.22).setFill()
+ shadowPath.fill()
+ NSGraphicsContext.restoreGraphicsState()
+
+ let path = cursorPath(anchor: anchor, scale: artwork.vectorScale, xOffset: 0, yOffset: 0)
+ let gradient = NSGradient(colors: [
+ NSColor(calibratedWhite: 0.97, alpha: 0.92),
+ NSColor(calibratedWhite: 0.84, alpha: 0.90),
+ ])!
+ gradient.draw(in: path, angle: -78)
+
+ NSColor(calibratedWhite: 1, alpha: 0.85).setStroke()
+ path.lineWidth = 1.0
+ path.lineJoinStyle = .round
+ path.lineCapStyle = .round
+ path.stroke()
+ }
+
+ if clickProgress > 0.01 {
+ let ringRadius = 4 + (clickProgress * 7)
+ let ringRect = CGRect(
+ x: anchor.x - ringRadius,
+ y: anchor.y - ringRadius,
+ width: ringRadius * 2,
+ height: ringRadius * 2
+ )
+ let ring = NSBezierPath(ovalIn: ringRect)
+ NSColor.white.withAlphaComponent(0.22 * (1 - clickProgress * 0.45)).setStroke()
+ ring.lineWidth = 1.0
+ ring.stroke()
+ }
+
+ context?.restoreGState()
+ }
+
+ private func cursorPath(anchor: CGPoint, scale: CGFloat, xOffset: CGFloat, yOffset: CGFloat) -> NSBezierPath {
+ let points: [CGPoint] = [
+ CGPoint(x: 0, y: 0),
+ CGPoint(x: 0, y: -79 * scale),
+ CGPoint(x: 20 * scale, y: -60 * scale),
+ CGPoint(x: 32 * scale, y: -91 * scale),
+ CGPoint(x: 47 * scale, y: -84 * scale),
+ CGPoint(x: 35 * scale, y: -55 * scale),
+ CGPoint(x: 63 * scale, y: -50 * scale),
+ ]
+
+ let translated = points.map {
+ CGPoint(
+ x: anchor.x + $0.x + xOffset,
+ y: anchor.y + $0.y + yOffset
+ )
+ }
+
+ let path = NSBezierPath()
+ path.move(to: translated[0])
+ for point in translated.dropFirst() {
+ path.line(to: point)
+ }
+ path.close()
+ return path
+ }
+}
+
+private func normalized(_ vector: CGVector) -> CGVector {
+ let length = max(hypot(vector.dx, vector.dy), 0.001)
+ return CGVector(dx: vector.dx / length, dy: vector.dy / length)
+}
+
+private extension CGFloat {
+ static func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {
+ Swift.min(Swift.max(value, lower), upper)
+ }
+
+ func clamped(to range: ClosedRange<CGFloat>) -> CGFloat {
+ Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
+ }
+}
diff --git a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift
index 7307761..8dadbd1 100644
--- a/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift
+++ b/packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests/OpenComputerUseKitTests.swift
@@ -53,4 +53,36 @@ final class OpenComputerUseKitTests: XCTestCase {
XCTAssertFalse(ComputerUseError.appNotFound("Sublime Text").toolResultIsError)
XCTAssertTrue(ComputerUseError.invalidArguments("bad").toolResultIsError)
}
+
+ func testVisualCursorEnvFlagDefaultsToEnabled() {
+ XCTAssertTrue(visualCursorEnabled(environment: [:]))
+ XCTAssertTrue(visualCursorEnabled(environment: ["OPEN_COMPUTER_USE_VISUAL_CURSOR": "1"]))
+ XCTAssertFalse(visualCursorEnabled(environment: ["OPEN_COMPUTER_USE_VISUAL_CURSOR": "0"]))
+ XCTAssertFalse(visualCursorEnabled(environment: ["OPEN_COMPUTER_USE_VISUAL_CURSOR": "false"]))
+ }
+
+ func testCursorWindowGeometryAnchorsTipPosition() {
+ let geometry = CursorWindowGeometry(
+ windowSize: CGSize(width: 128, height: 128),
+ tipAnchor: CGPoint(x: 44, y: 88)
+ )
+ let tipPosition = CGPoint(x: 1200, y: 800)
+
+ XCTAssertEqual(geometry.origin(forTipPosition: tipPosition), CGPoint(x: 1156, y: 712))
+ XCTAssertEqual(geometry.tipPosition(forOrigin: CGPoint(x: 1156, y: 712)), tipPosition)
+ }
+
+ func testCursorMotionPathStartsAndEndsAtExpectedPoints() {
+ let path = CursorMotionPath(
+ start: CGPoint(x: 10, y: 20),
+ end: CGPoint(x: 210, y: 120)
+ )
+
+ XCTAssertEqual(path.point(at: 0), CGPoint(x: 10, y: 20))
+ XCTAssertEqual(path.point(at: 1), CGPoint(x: 210, y: 120))
+
+ let midpoint = path.point(at: 0.5)
+ XCTAssertNotEqual(midpoint.x, 110)
+ XCTAssertNotEqual(midpoint.y, 70)
+ }
}
diff --git a/scripts/run-tool-smoke-tests.sh b/scripts/run-tool-smoke-tests.sh
index 4770254..45fb18a 100755
--- a/scripts/run-tool-smoke-tests.sh
+++ b/scripts/run-tool-smoke-tests.sh
@@ -7,4 +7,4 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${repo_root}"
swift build
-".build/debug/OpenComputerUseSmokeSuite"
+OPEN_COMPUTER_USE_VISUAL_CURSOR=0 ".build/debug/OpenComputerUseSmokeSuite"