diff --git a/ucu/README.md b/ucu/README.md index bf938bb..4c253fb 100644 --- a/ucu/README.md +++ b/ucu/README.md @@ -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. @@ -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 diff --git a/ucu/native/ucu-window.swift b/ucu/native/ucu-window.swift index 2ff99da..d71a8d0 100644 --- a/ucu/native/ucu-window.swift +++ b/ucu/native/ucu-window.swift @@ -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(_ 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?).self) + private static let forWindows = found("CGSCopySpacesForWindows", + as: (@convention(c) (Int32, Int32, CFArray) -> Unmanaged?).self) + + struct Layout { + var desktops = 0 + var fullScreen = [Int]() // the user's full-screen Spaces, in their order + var showing = Set() // the Space each of the user's displays shows + var all = Set() + } + + // 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 { + 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?) -> 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?, 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] } @@ -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"]) } diff --git a/ucu/scripts/ucu-proxy.py b/ucu/scripts/ucu-proxy.py index ba053cb..56af321 100755 --- a/ucu/scripts/ucu-proxy.py +++ b/ucu/scripts/ucu-proxy.py @@ -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") @@ -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. " @@ -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 "?" @@ -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 @@ -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()] @@ -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(): diff --git a/ucu/tests/fake_ucu_window.py b/ucu/tests/fake_ucu_window.py index 5cfe4bc..e3510d7 100644 --- a/ucu/tests/fake_ucu_window.py +++ b/ucu/tests/fake_ucu_window.py @@ -60,6 +60,14 @@ def answer(command): fresh = not set(command["park"]) <= parked parked.update(command["park"]) send({"id": command["id"], "state": "no desktop" if stuck else "parked", "moved": fresh}) + elif "situation" in command: # where the user is: what a test wrote in ~/user.json, or nothing known + if os.path.exists(os.path.join(os.environ["HOME"], "old-helper")): + return # one built before this question existed says nothing + said = os.path.join(os.environ["HOME"], "user.json") + known = json.load(open(said)) if os.path.exists(said) else {} + if "detail" not in command: # the line and the windows elsewhere go with a list only + known = {key: value for key, value in known.items() if key not in ("line", "elsewhere")} + send({"id": command["id"], **known}) elif "desktop" in command: moved = os.path.exists(os.path.join(os.environ["HOME"], "desktop-moved")) # another chat's desktop left send({"id": command["id"], "bounds": [-3840 if moved else -1920, -2400 if moved else -1200, 1920, 1200]}) @@ -73,6 +81,11 @@ def log(entry): def main(): if sys.argv[1:] != ["watch"]: log({"args": sys.argv[1:]}) + if sys.argv[1:] == ["list", "Listed"]: # as the real one lists an app's windows + print('Listed (com.example.listed, pid 1)\n[0] "One \\"quoted\\" 1,2 3x4" main 10,40 300x200\n' + '[1] "Two" minimized 20,50 300x200\n[2] "Three" dialog fullscreen -1900,-1100 400x300\n' + '[3] "Four" 9000,9000 200x100') + sys.exit(0) print(f"args: {' '.join(sys.argv[1:])}") sys.exit(2 if "Missing" in sys.argv else 0) threading.Thread(target=relay_reports, daemon=True).start() diff --git a/ucu/tests/test_windows.py b/ucu/tests/test_windows.py index 3e7154e..669698e 100644 --- a/ucu/tests/test_windows.py +++ b/ucu/tests/test_windows.py @@ -168,6 +168,64 @@ def test_moves_an_app_to_the_desktop_when_asked(self): self.assertIn("private desktop", proxy.text(proxy.call("move_to_desktop", app="Calculator"))) self.assertEqual(proxy.commands("park")[0]["park"], ["Calculator"]) + def test_tells_the_agent_where_the_user_is_when_that_is_news(self): + proxy = WatchingProxy(self) + user = Path(proxy.home.name) / "user.json" + + def told(): + return [note for note in proxy.notes(proxy.look("Calculator")) if "The user is in" in note] + + self.assertEqual(told(), []) # a helper that knows nothing says nothing + user.write_text(json.dumps({"app": "Mail", "doing": "typing", "fullscreen": False})) + self.assertEqual(told(), ["[ucu: The user is in Mail, typing.]"]) + user.write_text(json.dumps({"app": "Mail", "doing": "idle 40 s", "fullscreen": False})) + self.assertEqual(told(), []) # the same app: nothing new + user.write_text(json.dumps({"app": "Safari", "doing": "idle 12 s", "fullscreen": True})) + self.assertEqual(told(), ["[ucu: The user is in Safari in full screen, idle 12 s.]"]) + self.assertEqual(proxy.commands("situation")[0].keys() - {"at"}, {"situation", "id"}) + + def test_asks_a_helper_that_cannot_say_where_the_user_is_only_once(self): + proxy = WatchingProxy(self) + (Path(proxy.home.name) / "old-helper").write_text("") + proxy.look("Calculator") + started = time.monotonic() + proxy.look("Calculator") + proxy.call("list_windows", app="Calculator") + self.assertLess(time.monotonic() - started, 0.9) # each question would have waited a second + self.assertEqual(len(proxy.commands("situation")), 1) + + def test_lists_windows_with_where_the_user_is_and_what_is_on_other_spaces(self): + proxy = WatchingProxy(self) + proxy.policy(deny=["Notes", "Mail"]) + (Path(proxy.home.name) / "user.json").write_text(json.dumps({ + "app": "Mail", "doing": "typing", "line": "User: in Mail, typing. Spaces: 1 desktop, full screen: Maps.", + "elsewhere": ['Maps: "Route" fullscreen other-space']})) + listed = proxy.text(proxy.call("list_windows", app="Maps")).splitlines() + self.assertEqual(listed[0], "User: in Mail, typing. Spaces: 1 desktop, full screen: Maps.") + self.assertEqual(listed[1], "args: list Maps") # what the helper's own list gave + self.assertEqual(listed[2:4], ["On Spaces the user isn't looking at:", 'Maps: "Route" fullscreen other-space']) + asked = [command for command in proxy.commands("situation") if "detail" in command][0] + self.assertEqual((asked["detail"], asked["deny"]), ("Maps", ["Notes", "Mail"])) + self.assertEqual(asked.keys() - {"at"}, {"situation", "detail", "deny", "id"}) + self.assertNotIn("user-screen", "".join(listed)) # the helper said nothing of the screens + # A deny list that can't be read names no window: the helper then takes every app for denied. + (Path(proxy.home.name) / "Library/Application Support/ucu/policy.json").write_text("not a policy") + proxy.call("list_windows") + asked = [command for command in proxy.commands("situation") if "detail" in command][-1] + self.assertEqual((asked["detail"], "deny" in asked), ("*", False)) + + def test_says_where_each_listed_window_is_for_the_user(self): + proxy = WatchingProxy(self) + proxy.policy(deny=[]) + (Path(proxy.home.name) / "user.json").write_text(json.dumps({ + "app": "Mail", "doing": "typing", "screens": [[0, 0, 1512, 982, False], [-1920, -1200, 1920, 1200, True]]})) + listed = proxy.texts(proxy.call("list_windows", app="Listed"))[0].splitlines() # a note on the user follows + self.assertEqual(listed, ['Listed (com.example.listed, pid 1)', + '[0] "One \\"quoted\\" 1,2 3x4" main 10,40 300x200 user-screen', + '[1] "Two" minimized 20,50 300x200', + '[2] "Three" dialog fullscreen -1900,-1100 400x300 private-desktop', + '[3] "Four" 9000,9000 200x100 off-screen']) + def test_tells_the_agent_when_a_running_app_got_a_window(self): proxy = WatchingProxy(self) self.assertIn("had no open window", proxy.notes(proxy.look("Empty App"))[0])