Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion ucu/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ The first use of each app by a chat, and every refusal, goes to `~/Library/Logs/
- `look {app, window?, find?, full?, screenshot?}`: an app's window as numbered text, then only what changed, up to 300
lines. `find` shows only the lines with a text, under what they are inside of, and `full` the whole tree.
- `act {app, window?, steps}`: steps in order, then what changed. It stops at the first step that fails.
- `list_windows {app?}`: the windows of an app, or of every app, and which is the main window.
- `list_windows {app?}`: the windows of an app, or of every app, and which is the main window. It begins with a line
about you (see "What an agent is told about you"), and says of each window whether it is on your screen
(`user-screen`), on an agent's desktop (`private-desktop`) or on no screen (`off-screen`). Windows on a Space you
aren't looking at, such as an app in full screen, follow the list as `other-space`: the app's own list leaves those
out.
- `focus_window {app, title, unfullscreen?, activate?}`: makes a window the main window. With `activate: true`, the
window comes to your screen and the front, only when you ask to see it.
- `move_to_desktop {app}`: moves an app's windows to the agent's private desktop.
Expand Down Expand Up @@ -206,6 +210,22 @@ window, which you both use from then on. That is the only way UCU brings anythin
Every time an app comes forward during agent work, `~/Library/Logs/ucu/focus.log` says what UCU did, naming the apps but
no window titles, and `ucu doctor` sums up the last day.

### What an agent is told about you

So that an agent can choose when and where to work, UCU tells it where you are:

- `list_windows` begins with a line such as `User: in Mail, window "Inbox", typing. Spaces: 2 desktops, full screen:
Safari; showing a desktop.` It names the app and the window you are in, says whether you are typing, active, or how
long you have been idle, and describes your Spaces: how many desktops, which apps are in full screen, and which you
are looking at.
- When you move to another app, or into or out of full screen, the agent's next result ends with a note such as
`[ucu: The user is in Safari in full screen, idle 12 s.]` That note names the app only.

It is a picture of this moment: UCU keeps no history of what you did. A window's title is left out for an app on the
deny list, and what is in your windows is never read for this. These lines are part of the tool results, so they go to
whichever model drives UCU. Spaces come from the window server through calls macOS doesn't document. Where those are
missing, nothing is said of Spaces. The title of a window on another Space needs Screen Recording permission.

### The private desktop

Each chat that needs one gets a virtual display, called UCU Agent Desktop, 1920 by 1200. macOS treats its windows as on
Expand Down
172 changes: 172 additions & 0 deletions ucu/native/ucu-window.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,155 @@ func printWindows(of app: NSRunningApplication, element: AXUIElement, list: [AXU
}
}

// MARK: where the user is

// What the window server knows of Spaces. These calls aren't public, so each is looked up, and where one is missing
// nothing is said of Spaces.
enum Spaces {
private static func found<T>(_ name: String, as type: T.Type) -> T? {
dlsym(UnsafeMutableRawPointer(bitPattern: -2), name).map { unsafeBitCast($0, to: type) }
}
private static let connection = found("CGSMainConnectionID", as: (@convention(c) () -> Int32).self)
private static let managed = found("CGSCopyManagedDisplaySpaces",
as: (@convention(c) (Int32) -> Unmanaged<CFArray>?).self)
private static let forWindows = found("CGSCopySpacesForWindows",
as: (@convention(c) (Int32, Int32, CFArray) -> Unmanaged<CFArray>?).self)

struct Layout {
var desktops = 0
var fullScreen = [Int]() // the user's full-screen Spaces, in their order
var showing = Set<Int>() // the Space each of the user's displays shows
var all = Set<Int>()
}

// The Spaces of the user's displays. An agent's desktop has Spaces of its own, which aren't theirs.
static func layout() -> Layout? {
guard let connection, let managed,
let displays = managed(connection())?.takeRetainedValue() as? [[String: Any]] else { return nil }
let agents = agentDisplays()
var layout = Layout()
for display in displays where !agents.contains(display["Display Identifier"] as? String ?? "") {
if let now = (display["Current Space"] as? [String: Any])?["ManagedSpaceID"] as? Int {
layout.showing.insert(now)
}
for space in display["Spaces"] as? [[String: Any]] ?? [] {
guard let id = space["ManagedSpaceID"] as? Int else { continue }
layout.all.insert(id)
if space["type"] as? Int == 4 { layout.fullScreen.append(id) } else { layout.desktops += 1 }
}
}
return layout
}

static func agentDisplays() -> Set<String> {
var count: UInt32 = 0
var displays = [CGDirectDisplayID](repeating: 0, count: 32)
guard CGGetActiveDisplayList(32, &displays, &count) == .success else { return [] }
let agents = displays.prefix(Int(count)).filter { CGDisplayVendorNumber($0) == AgentDesktop.vendor }
return Set(agents.compactMap { display in
CGDisplayCreateUUIDFromDisplayID(display).map { CFUUIDCreateString(nil, $0.takeRetainedValue()) as String }
})
}

static func of(window number: Int) -> [Int] {
guard let connection, let forWindows else { return [] }
return forWindows(connection(), 7, [number] as CFArray)?.takeRetainedValue() as? [Int] ?? []
}
}

// Every window the window server has. It takes 15 ms, so it is read only where there is more than one Space.
func allWindows() -> [[String: Any]] {
CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
}

// An app goes by several names, and the deny list may give any of them. One that can't be read denies every app, as
// it does everywhere else.
func isDenied(_ app: NSRunningApplication, by deny: Set<String>?) -> Bool {
guard let deny else { return true }
let info = app.bundleURL.flatMap { Bundle(url: $0) }?.infoDictionary
let names = [app.localizedName, app.bundleIdentifier, app.bundleURL?.deletingPathExtension().lastPathComponent,
info?["CFBundleName"] as? String, info?["CFBundleDisplayName"] as? String]
return !Set(names.compactMap { $0 }.map(key)).isDisjoint(with: deny)
}

// Whether the user is typing, doing something else, or how long they have done nothing.
func userActivity() -> String {
let key = CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: .keyDown)
let any = CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: CGEventType(rawValue: ~0)!)
if key < 2 { return "typing" }
if any < 2 { return "active" }
return any < 90 ? "idle \(Int(any)) s" : "idle \(Int(any / 60)) min"
}

// The user's Spaces in a few words: how many desktops, which apps are in full screen, and what they are looking at.
func spacesLine(_ layout: Spaces.Layout, windows: [[String: Any]]) -> String {
var apps = [Int: [String]]()
if !layout.fullScreen.isEmpty {
for window in windows where (window[kCGWindowLayer as String] as? Int) == 0 {
guard let number = window[kCGWindowNumber as String] as? Int,
let owner = window[kCGWindowOwnerName as String] as? String,
let bounds = window[kCGWindowBounds as String] as? [String: CGFloat],
(bounds["Height"] ?? 0) > 100 else { continue } // not the strip a full-screen app keeps for its toolbar
for space in Spaces.of(window: number) where layout.fullScreen.contains(space) {
if !(apps[space] ?? []).contains(owner) { apps[space, default: []].append(owner) }
}
}
}
func name(_ space: Int) -> String { apps[space].map { $0.joined(separator: " + ") } ?? "an app" }
var said = "Spaces: \(layout.desktops) desktop\(layout.desktops == 1 ? "" : "s")"
if !layout.fullScreen.isEmpty { said += ", full screen: " + layout.fullScreen.map(name).joined(separator: ", ") }
let shown = layout.fullScreen.filter(layout.showing.contains)
return said + (shown.isEmpty ? "; showing a desktop" : "; showing full screen (\(shown.map(name).joined(separator: ", ")))")
}

// What the user is doing, in a line: the app and window they are in, whether they type, and their Spaces. The title
// of a window is left out for an app on the deny list.
func userLine(deny: Set<String>?, layout: Spaces.Layout?, windows: [[String: Any]]) -> String? {
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
var said = "User: in \(app.localizedName ?? "an app")"
if !isDenied(app, by: deny) {
let element = AXUIElementCreateApplication(app.processIdentifier)
AXUIElementSetMessagingTimeout(element, 0.3) // a busy app must not hold up the list
let window: AXUIElement? = attribute(element, kAXFocusedWindowAttribute)
?? attribute(element, kAXMainWindowAttribute)
if let name = window.map(title), !name.isEmpty { said += ", window \"\(name.prefix(80))\"" }
}
return said + ", " + userActivity() + (layout.map { ". " + spacesLine($0, windows: windows) } ?? "") + "."
}

// The displays, as x, y, width, height and whether each is an agent's desktop: the server tells from them where a
// listed window is. `list` itself would have to connect to the display system for it, which took 27 ms.
func screens() -> [[Any]] {
var count: UInt32 = 0
var displays = [CGDirectDisplayID](repeating: 0, count: 32)
guard CGGetActiveDisplayList(32, &displays, &count) == .success else { return [] }
return displays.prefix(Int(count)).map { display in
let bounds = CGDisplayBounds(display)
return [Int(bounds.minX), Int(bounds.minY), Int(bounds.width), Int(bounds.height),
CGDisplayVendorNumber(display) == AgentDesktop.vendor]
}
}

// The windows of an app on a Space the user isn't looking at, such as one in full screen: the app's own list leaves
// them out. They are told by their titles, which the window server gives only with Screen Recording permission.
func windowsElsewhere(of app: NSRunningApplication, layout: Spaces.Layout, windows: [[String: Any]]) -> [String] {
let listed: [AXUIElement] = attribute(appElement(app.processIdentifier), kAXWindowsAttribute) ?? []
let known = Set(listed.map(title))
var lines = [String]()
for window in windows where (window[kCGWindowOwnerPID as String] as? pid_t) == app.processIdentifier {
guard (window[kCGWindowLayer as String] as? Int) == 0,
!((window[kCGWindowIsOnscreen as String] as? Bool) ?? false),
let number = window[kCGWindowNumber as String] as? Int,
let name = window[kCGWindowName as String] as? String, !name.isEmpty, !known.contains(name) else { continue }
let spaces = Spaces.of(window: number)
guard !spaces.isEmpty, layout.showing.isDisjoint(with: spaces), !layout.all.isDisjoint(with: spaces) else { continue }
let full = layout.fullScreen.contains(where: spaces.contains) ? "fullscreen " : ""
let line = "\(app.localizedName ?? "?"): \"\(name)\" \(full)other-space"
if !lines.contains(line) { lines.append(line) }
}
return lines
}

func find(_ query: String, in list: [AXUIElement]) -> AXUIElement {
let matches = list.filter { title($0).localizedCaseInsensitiveContains(query) }
if matches.count == 1 { return matches[0] }
Expand Down Expand Up @@ -814,6 +963,29 @@ final class Watcher {
open(name, deny: command["deny"] as? [String] ?? [], id: command["id"] ?? NSNull())
}
if let names = command["show"] as? [String] { show(names, id: command["id"]) }
if command["situation"] != nil, let id = command["id"] {
// Where the user is. After every call the server asks only for what tells it of a change, which no
// app has to answer. For `list_windows` it asks for the line that goes with the list, `detail` being
// the app listed or "*", and for that app's windows on Spaces the user isn't looking at. This helper
// answers in half a millisecond, where the `list` command, started anew each time, took 55 ms more.
let layout = Spaces.layout()
var reply: [String: Any] = ["id": id, "doing": userActivity()]
if let app = NSWorkspace.shared.frontmostApplication { reply["app"] = app.localizedName ?? "an app" }
if let layout { reply["fullscreen"] = !layout.showing.isDisjoint(with: layout.fullScreen) }
if let detail = command["detail"] as? String {
let deny = (command["deny"] as? [String]).map { Set($0.map(key)) }
let windows = (layout?.all.count ?? 0) > 1 ? allWindows() : []
reply["line"] = userLine(deny: deny, layout: layout, windows: windows)
reply["screens"] = screens()
if let layout, !windows.isEmpty {
let apps = detail == "*" ? NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular }
: [running(detail)].compactMap { $0 }
reply["elsewhere"] = apps.filter { !isDenied($0, by: deny) }
.flatMap { windowsElsewhere(of: $0, layout: layout, windows: windows) }
}
}
emit(reply)
}
if let names = command["park"] as? [String] {
park(names, onlyHidden: command["onlyHidden"] as? Bool ?? false, id: command["id"])
}
Expand Down
54 changes: 54 additions & 0 deletions ucu/scripts/ucu-proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
ALERT_LATE = 1 # seconds after a call in which a sound still belongs to it
OPEN_TIMEOUT, SHOW_TIMEOUT = 50, 3 # seconds; the helper gives up on an app before OPEN_TIMEOUT
PARK_TIMEOUT, SHOT_TIMEOUT = 6, 15
SITUATION_TIMEOUT = 1 # the helper answers from what it already knows
SESSIONS = Path.home() / "Library/Application Support/ucu/sessions"
SHARED_APP_AGE = 180 # seconds since another chat last got an app
CURSOR_COLORS = ("#E5484D", "#2B9A66", "#3358D4", "#E8590C", "#8E4EC6", "#0D9488", "#D6409F", "#C99700")
Expand All @@ -124,6 +125,7 @@
OWN_BROWSER = "Your own {} window works out of the user's sight already: use the `{}` tool."
SHARED_NOTE = ("[ucu: Another agent ({}) is using {}. Two agents on one app undo each other's work: wait for it, or "
"ask the user.]")
USER_NOTE = "[ucu: The user is in {}{}, {}.]"
FOCUS_NOTE = ("[ucu: {} came to the front during your actions, so ucu put {} back: the user keeps their focus. Check "
"that the app did what you meant.]")
WINDOW_FOCUS_NOTE = ("[ucu: {} gave one of your windows the user's keyboard, so ucu gave it back to their window. "
Expand Down Expand Up @@ -297,6 +299,23 @@ def run_window_tool(name, arguments):
return (result.stdout + result.stderr).strip(), result.returncode != 0


LISTED_WINDOW = re.compile(r'\[\d+\] ".*" (?:[a-z]+ )*(-?\d+),(-?\d+) (\d+)x(\d+)')


def placed(line, screens):
"""A line of `ucu-window list` for a window, with where that window is for the user: on a screen of theirs, on an
agent's desktop, or on none. Its title bar says which, as in ucu-window. A minimized window is in the Dock."""
found = LISTED_WINDOW.fullmatch(line)
if not found or " minimized " in line[line.rindex('"'):]:
return line
x, y, width, height = map(int, found.groups())
across, down = x + width / 2, y + min(height / 2, 20)
for left, top, wide, high, agents in screens:
if left <= across < left + wide and top <= down < top + high:
return line + (" private-desktop" if agents else " user-screen")
return line + " off-screen"


def working_folder():
try:
return "-".join(Path.cwd().name.split()) or "?"
Expand Down Expand Up @@ -1473,6 +1492,8 @@ def __init__(self, turn_idle, stop_grace, stop_idle):
self.browsers = {tool: (SafariWorkspace if tool == "safari" else BrowserWorkspace)(self, tool)
for tool in BROWSERS}
self.used_apps = set() # apps this chat has driven, as app_key names
self.user_seen = None # the app the agent was last told the user is in, and whether in full screen
self.silent_helper = None # a helper that didn't say where the user is, and isn't asked again
self.logged_apps = set() # apps already in the approval log for this chat
self.hidden_apps = {} # apps ucu opened and still keeps out of sight, app_key -> name
self.parked_apps = set() # those of them on the agent's desktop, as app_key names
Expand Down Expand Up @@ -1560,6 +1581,11 @@ def finish(self, started, with_sounds):
if finished:
self.windows.send({"busy": False})
notes = self.windows.take_notes()
where = self.situation()
if where.get("app") and (where["app"], where.get("fullscreen")) != self.user_seen:
self.user_seen = (where["app"], where.get("fullscreen"))
notes.append(USER_NOTE.format(where["app"], " in full screen" if where.get("fullscreen") else "",
where.get("doing") or "doing something"))
if names:
apps = [name if times == 1 else f"{name} ({times} times)"
for name, times in collections.Counter(names).items()]
Expand All @@ -1586,10 +1612,38 @@ def run_tool(self, name, arguments):
text, failed = self.move_to_desktop(str(arguments.get("app") or ""))
else:
text, failed = run_window_tool(name, arguments)
if name == "list_windows" and not failed:
text = self.with_the_user(text, str(arguments.get("app") or "*"))
if failed:
raise ToolError(text)
return [{"type": "text", "text": text}]

def situation(self, **more):
"""Ask the helper where the user is. One built before it knew the question never answers, such as the one a
chat gets that starts while an update is still building the new one. It is asked once, not after every call:
each time would cost the wait."""
helper = self.windows.process
if helper is None or helper is self.silent_helper:
return {}
where = self.windows.ask({"situation": True, **more}, SITUATION_TIMEOUT)
if where is None:
self.silent_helper = helper
return where or {}

def with_the_user(self, listed, app):
"""A list of windows, with where the user is before it and, after it, the windows on Spaces they aren't
looking at, which an app's own list leaves out. The window they are in is named unless its app is denied,
and a deny list that can't be read names none."""
request = {"detail": app}
denied = self.denied_apps()
if denied is not None:
request["deny"] = denied
where = self.situation(**request)
elsewhere, screens = where.get("elsewhere") or [], where.get("screens") or []
lines = [placed(line, screens) for line in listed.splitlines()] if screens else [listed]
return "\n".join([*([where["line"]] if where.get("line") else []), *lines,
*(["On Spaces the user isn't looking at:", *elsewhere] if elsewhere else [])])

# --- apps -------------------------------------------------------------
@staticmethod
def denied_apps():
Expand Down
Loading
Loading