diff --git a/CHANGELOG.md b/CHANGELOG.md index cd18259..4c710fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,9 @@ All notable changes to this project are documented here. - Add three Google Antigravity keys that read its local language server (no screen reading): Antigravity Left (each model group's weekly and five-hour - quota), Antigravity Context, and Antigravity Permissions (cycles the global - preset Review, Default, Turbo). + quota), Antigravity Context, and Antigravity Permissions (steps the open + conversation through the presets its composer offers: Request Review, + Default, Auto, Turbo). - Give Approval Mode the shared settings panel so a hand-placed key can be switched to Claude Code, and draw the Claude permission mode as the key's headline instead of a truncated caption. diff --git a/com.todd.streamdeckcodex.sdPlugin/manifest.json b/com.todd.streamdeckcodex.sdPlugin/manifest.json index e15c24e..fa5c0cc 100644 --- a/com.todd.streamdeckcodex.sdPlugin/manifest.json +++ b/com.todd.streamdeckcodex.sdPlugin/manifest.json @@ -271,7 +271,7 @@ "ShowTitle": false } ], - "Tooltip": "Cycle Antigravity's global permission preset: Review, Default, Turbo.", + "Tooltip": "Step the open Antigravity conversation through the permission presets its composer offers: Request Review, Default, Auto, Turbo.", "UUID": "com.todd.streamdeckcodex.antigravity-permissions" }, { diff --git a/native/Antigravity.swift b/native/Antigravity.swift new file mode 100644 index 0000000..f0b0d74 --- /dev/null +++ b/native/Antigravity.swift @@ -0,0 +1,148 @@ +import AppKit +import ApplicationServices +import Foundation + +// Google Antigravity's permission preset is chosen per conversation from a +// popup in the composer. The local server's global preset only feeds the +// popup's "Default" entry, so the popup is the control a user sees and the +// one this drives. +let antigravityBundleIdentifier = "com.google.antigravity" +let antigravitySelectorPrefix = "Agent permissions preset selector, current: " +let antigravityPresetOrder = ["Request Review", "Default", "Auto", "Turbo"] + +/// The preset named at the start of a menu item such as +/// "Turbo Run all commands without restrictions.". +func antigravityPresetName(menuItem text: String) -> String? { + antigravityPresetOrder.first { text == $0 || text.hasPrefix($0 + " ") } +} + +/// The offered preset after `current`, in the menu's own order, wrapping. +func nextAntigravityPreset(current: String, offered: [String]) -> String? { + guard offered.count > 1, let index = offered.firstIndex(of: current) else { return nil } + return offered[(index + 1) % offered.count] +} + +private func antigravityAttribute(_ element: AXUIElement, _ name: String) -> AnyObject? { + var value: AnyObject? + AXUIElementCopyAttributeValue(element, name as CFString, &value) + return value +} + +private func antigravityText(_ element: AXUIElement) -> String { + [kAXTitleAttribute, kAXDescriptionAttribute, kAXValueAttribute] + .compactMap { antigravityAttribute(element, $0 as String) as? String } + .filter { !$0.isEmpty } + .joined(separator: " ") +} + +private func antigravityElements( + _ root: AXUIElement, + roles: Set +) -> [(element: AXUIElement, text: String)] { + var found: [(AXUIElement, String)] = [] + var visited = 0 + func walk(_ element: AXUIElement, _ depth: Int) { + visited += 1 + guard depth <= 80, visited <= 12_000 else { return } + if roles.contains(antigravityAttribute(element, kAXRoleAttribute as String) as? String ?? "") { + found.append((element, antigravityText(element))) + } + for child in (antigravityAttribute(element, kAXChildrenAttribute as String) as? [AXUIElement]) ?? [] { + walk(child, depth + 1) + } + } + walk(root, 0) + return found +} + +private func antigravitySelector(_ app: AXUIElement) throws -> (element: AXUIElement, current: String) { + let selectors = antigravityElements(app, roles: [kAXPopUpButtonRole as String]) + .filter { $0.text.hasPrefix(antigravitySelectorPrefix) } + guard selectors.count == 1, let selector = selectors.first else { + throw ControlError.failed( + selectors.isEmpty + ? "Antigravity shows no conversation permission selector." + : "Antigravity shows more than one permission selector.", + selectors.isEmpty ? "NO_FOCUS" : "TARGET_MISMATCH" + ) + } + return (selector.element, String(selector.text.dropFirst(antigravitySelectorPrefix.count))) +} + +private func antigravityWait(_ seconds: Double, _ read: () -> T?) -> T? { + let deadline = Date().addingTimeInterval(seconds) + repeat { + if let value = read() { return value } + usleep(120_000) + } while Date() < deadline + return nil +} + +func runAntigravityAction(_ action: String, requested: String?) { + guard action == "antigravity-permission" else { return } + func finish(_ ok: Bool, _ current: String?, _ message: String, _ code: String? = nil) -> Never { + var result = ControlResult( + ok: ok, action: action, requested: requested, model: current, effort: nil, message: message + ) + result.reasonCode = code + emit(result, exitCode: ok ? 0 : 1) + } + guard AXIsProcessTrusted() else { + finish(false, nil, "Accessibility permission is required for the Stream Deck app.", "ACCESSIBILITY") + } + guard let running = NSRunningApplication + .runningApplications(withBundleIdentifier: antigravityBundleIdentifier).first + else { finish(false, nil, "Antigravity is not running.", "NO_FOCUS") } + let app = AXUIElementCreateApplication(running.processIdentifier) + do { + // Chromium exposes only its menus until accessibility is switched on. + if (try? antigravitySelector(app)) == nil { + AXUIElementSetAttributeValue(app, "AXManualAccessibility" as CFString, kCFBooleanTrue) + AXUIElementSetAttributeValue(app, "AXEnhancedUserInterface" as CFString, kCFBooleanTrue) + _ = antigravityWait(4) { try? antigravitySelector(app) } + } + let selector = try antigravitySelector(app) + guard requested == "cycle" else { + finish(true, selector.current, "Antigravity permissions are \(selector.current).") + } + guard AXUIElementPerformAction(selector.element, kAXPressAction as CFString) == .success else { + throw ControlError.failed("Antigravity rejected opening the permission selector.", "UNCHANGED") + } + func items() -> [(element: AXUIElement, preset: String)] { + antigravityElements(app, roles: [kAXMenuItemRole as String]).compactMap { item in + antigravityPresetName(menuItem: item.text).map { (item.element, $0) } + } + } + func close() { _ = AXUIElementPerformAction(selector.element, kAXPressAction as CFString) } + guard let offered = antigravityWait(2.5, { () -> [(element: AXUIElement, preset: String)]? in + let found = items() + return found.count > 1 ? found : nil + }) else { + close() + throw ControlError.failed("Antigravity's permission menu did not open.", "UNCHANGED") + } + guard let wanted = nextAntigravityPreset(current: selector.current, offered: offered.map(\.preset)), + let item = offered.first(where: { $0.preset == wanted }) + else { + close() + throw ControlError.failed( + "Antigravity does not offer a preset after \(selector.current).", "UNAVAILABLE" + ) + } + guard AXUIElementPerformAction(item.element, kAXPressAction as CFString) == .success else { + close() + throw ControlError.failed("Antigravity rejected the \(wanted) preset.", "UNCHANGED") + } + guard antigravityWait(3, { () -> Bool? in + (try? antigravitySelector(app))?.current == wanted ? true : nil + }) != nil else { + let shown = (try? antigravitySelector(app))?.current ?? "nothing" + throw ControlError.failed("Antigravity still shows \(shown) after choosing \(wanted).", "UNCHANGED") + } + finish(true, wanted, "Antigravity permissions are now \(wanted).") + } catch let ControlError.failed(message, code) { + finish(false, nil, message, code) + } catch { + finish(false, nil, error.localizedDescription, "UNKNOWN") + } +} diff --git a/native/main.swift b/native/main.swift index 8987cca..c9043bf 100644 --- a/native/main.swift +++ b/native/main.swift @@ -19,6 +19,7 @@ let threadId = arguments.count > 2 ? arguments[2] : nil runFixtureAction(action, arguments: arguments) runProviderAction(action, requested: requested) +runAntigravityAction(action, requested: requested) var accessibilityInitialization = "not attempted" do { diff --git a/package-lock.json b/package-lock.json index c7a85ff..0753326 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1986,9 +1986,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { diff --git a/package.json b/package.json index 24341b2..6a7f265 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ ], "overrides": { "brace-expansion": "5.0.12", - "fast-uri": "3.1.8", + "fast-uri": "3.1.9", "nanoid": "3.3.18", "zod": "4.6.6" }, diff --git a/src/actions/antigravity.ts b/src/actions/antigravity.ts index e6a285d..2509c0a 100644 --- a/src/actions/antigravity.ts +++ b/src/actions/antigravity.ts @@ -5,10 +5,7 @@ import streamDeck, { SingletonAction, type WillAppearEvent, } from "@elgato/streamdeck"; -import { - ANTIGRAVITY_PRESET_LABEL, - antigravityStore, -} from "../lib/antigravity.js"; +import { antigravityStore } from "../lib/antigravity.js"; import { renderKey } from "../lib/render-cache.js"; import { contextKeySvg, @@ -86,9 +83,15 @@ export class AntigravityContextAction extends AntigravityKey { } } -/** Press to cycle the global permission preset: Review, Default, Turbo. */ +/** Press to step the open conversation through the presets its composer offers. */ @action({ UUID: "com.todd.streamdeckcodex.antigravity-permissions" }) export class AntigravityPermissionsAction extends AntigravityKey { + override async refreshAll(): Promise { + if ([...this.actions].length === 0) return; + await antigravityStore.refreshPreset(); + await super.refreshAll(); + } + async onKeyDown(event: KeyDownEvent): Promise { try { await antigravityStore.cyclePreset(); @@ -104,11 +107,9 @@ export class AntigravityPermissionsAction extends AntigravityKey { } protected svg(): string { - const preset = antigravityStore.preset; return modeKeySvg( - preset - ? ANTIGRAVITY_PRESET_LABEL[preset] - : (antigravityStore.reason ?? "UNAVAILABLE"), + antigravityStore.preset ?? + (antigravityStore.reason === "NOT OPEN" ? "NOT OPEN" : "NO CHAT"), "Antigravity", "shield", ); diff --git a/src/lib/antigravity.ts b/src/lib/antigravity.ts index 5abb079..dd50d4f 100644 --- a/src/lib/antigravity.ts +++ b/src/lib/antigravity.ts @@ -2,6 +2,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { ContextSnapshot, UsageSnapshot } from "../types.js"; +import { invoke, type NativeControlResult } from "./codex-ui-control.js"; /** * Google Antigravity runs a local language server that answers quota, @@ -14,20 +15,6 @@ const SERVICE = "exa.language_server_pb.LanguageServerService"; const REQUEST_TIMEOUT_MS = 2_500; const QUOTA_CACHE_MS = 30_000; const LIVE_CACHE_MS = 3_000; -const PRESET_PREFIX = "AGENT_PERMISSION_PRESET_"; - -/** The presets the server keeps distinct; every other value reads back as Default. */ -export const ANTIGRAVITY_PRESETS = [ - "REQUEST_REVIEW", - "DEFAULT", - "TURBO", -] as const; -export type AntigravityPreset = (typeof ANTIGRAVITY_PRESETS)[number]; -export const ANTIGRAVITY_PRESET_LABEL: Record = { - REQUEST_REVIEW: "Review", - DEFAULT: "Default", - TURBO: "Turbo", -}; export interface AntigravityQuotaBucket { /** First word of the quota group, e.g. "GEMINI" or "CLAUDE". */ @@ -169,37 +156,28 @@ export function parseAntigravityContext( return undefined; } -export function parseAntigravityPreset( - response: unknown, -): AntigravityPreset | undefined { - const value = String((response as any)?.globalPreset ?? "").slice( - PRESET_PREFIX.length, - ); - return (ANTIGRAVITY_PRESETS as readonly string[]).includes(value) - ? (value as AntigravityPreset) - : undefined; -} - -export function nextAntigravityPreset( - current: AntigravityPreset, -): AntigravityPreset { - return ANTIGRAVITY_PRESETS[ - (ANTIGRAVITY_PRESETS.indexOf(current) + 1) % ANTIGRAVITY_PRESETS.length - ]!; -} - export class AntigravityStore { quota: AntigravityQuotaBucket[] = []; context: ContextSnapshot | undefined; - preset: AntigravityPreset | undefined; + /** The open conversation's preset as its composer names it. */ + preset: string | undefined; + #presetAt = 0; + #presetRead: Promise | undefined; reason: AntigravityReason | undefined = "NOT OPEN"; #quotaAt = 0; #liveAt = 0; #refreshing: Promise | undefined; readonly #daemon: () => Daemon | undefined; + readonly #native: (request: "read" | "cycle") => Promise; - constructor(daemon: () => Daemon | undefined = findAntigravityDaemon) { + constructor( + daemon: () => Daemon | undefined = findAntigravityDaemon, + native: (request: "read" | "cycle") => Promise = ( + request, + ) => invoke("antigravity-permission", request, 8_000), + ) { this.#daemon = daemon; + this.#native = native; } async #call(method: string, body: unknown = {}): Promise { @@ -234,7 +212,6 @@ export class AntigravityStore { if (!this.#daemon()) { this.quota = []; this.context = undefined; - this.preset = undefined; this.reason = "NOT OPEN"; this.#quotaAt = this.#liveAt = 0; return; @@ -242,9 +219,6 @@ export class AntigravityStore { try { if (force || now - this.#liveAt >= LIVE_CACHE_MS) { this.#liveAt = now; - this.preset = parseAntigravityPreset( - await this.#call("GetPermissionSettings"), - ); const conversation = latestAntigravityConversation( await this.#call("GetAllCascadeTrajectories"), ); @@ -274,23 +248,38 @@ export class AntigravityStore { } } - /** Apply the next preset and return what the server then reports. */ - async cyclePreset(): Promise { - const current = parseAntigravityPreset( - await this.#call("GetPermissionSettings"), - ); - if (!current) throw new Error("Antigravity reported no known preset."); - const wanted = nextAntigravityPreset(current); - await this.#call("UpdatePermissionSettings", { - preset: PRESET_PREFIX + wanted, - }); - const applied = parseAntigravityPreset( - await this.#call("GetPermissionSettings"), - ); - this.preset = applied; - if (applied !== wanted) - throw new Error(`Antigravity kept ${applied ?? "an unknown preset"}.`); - return applied; + /** + * The preset lives in the conversation's composer popup, not in the server: + * the server's global value only feeds the popup's "Default" entry. Reads + * are throttled and run only while a permissions key is visible. + */ + refreshPreset(now = Date.now()): Promise { + if (now - this.#presetAt < LIVE_CACHE_MS) return Promise.resolve(); + this.#presetAt = now; + this.#presetRead ??= this.#permission("read") + .then((preset) => { + this.preset = preset; + }) + .catch(() => { + this.preset = undefined; + }) + .finally(() => { + this.#presetRead = undefined; + }); + return this.#presetRead; + } + + /** Choose the next preset the popup offers and return what it then shows. */ + async cyclePreset(): Promise { + this.preset = await this.#permission("cycle"); + this.#presetAt = Date.now(); + return this.preset; + } + + async #permission(request: "read" | "cycle"): Promise { + const result = await this.#native(request); + if (!result.model) throw new Error(result.message); + return result.model; } } diff --git a/src/lib/codex-ui-control.ts b/src/lib/codex-ui-control.ts index 45e1c7a..1853a68 100644 --- a/src/lib/codex-ui-control.ts +++ b/src/lib/codex-ui-control.ts @@ -94,6 +94,7 @@ export function invoke( | "target-capture" | "target-check" | "provider-read" + | "antigravity-permission" | "claude", requested?: string, timeoutMs?: number, diff --git a/src/lib/visuals.ts b/src/lib/visuals.ts index c71d028..a85e0d7 100644 --- a/src/lib/visuals.ts +++ b/src/lib/visuals.ts @@ -283,7 +283,7 @@ const MODE_ACCENT: [RegExp, string][] = [ [/accept/i, "#7EE787"], [/^plan/i, "#C8A4FF"], [/^auto/i, "#E7A589"], - [/^(manual|ask|review)/i, "#79C0FF"], + [/^(manual|ask|review|request)/i, "#79C0FF"], [/^turbo/i, "#FFD166"], [/^default/i, "#7EE787"], ]; diff --git a/test/antigravity.test.ts b/test/antigravity.test.ts index a6660a3..e2e517b 100644 --- a/test/antigravity.test.ts +++ b/test/antigravity.test.ts @@ -3,11 +3,10 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { + AntigravityStore, findAntigravityDaemon, latestAntigravityConversation, - nextAntigravityPreset, parseAntigravityContext, - parseAntigravityPreset, parseAntigravityQuota, } from "../src/lib/antigravity.js"; @@ -107,17 +106,37 @@ describe("Antigravity local server readings", () => { ).toBeUndefined(); }); - it("cycles only the presets the server keeps distinct", () => { - expect( - parseAntigravityPreset({ globalPreset: "AGENT_PERMISSION_PRESET_TURBO" }), - ).toBe("TURBO"); - expect( - parseAntigravityPreset({ - globalPreset: "AGENT_PERMISSION_PRESET_VETTED", - }), - ).toBeUndefined(); - expect(nextAntigravityPreset("REQUEST_REVIEW")).toBe("DEFAULT"); - expect(nextAntigravityPreset("DEFAULT")).toBe("TURBO"); - expect(nextAntigravityPreset("TURBO")).toBe("REQUEST_REVIEW"); + it("takes the conversation preset from the composer, never the server", async () => { + const requests: string[] = []; + const store = new AntigravityStore( + () => undefined, + async (request) => { + requests.push(request); + return { + ok: true, + action: "antigravity-permission", + message: "", + model: request === "cycle" ? "Turbo" : "Auto", + } as never; + }, + ); + await store.refreshPreset(10_000); + expect(store.preset).toBe("Auto"); + await store.refreshPreset(10_001); + expect(requests).toEqual(["read"]); + expect(await store.cyclePreset()).toBe("Turbo"); + expect(store.preset).toBe("Turbo"); + }); + + it("shows no preset when the composer cannot be read", async () => { + const store = new AntigravityStore( + () => undefined, + async () => { + throw new Error("Antigravity is not running."); + }, + ); + await store.refreshPreset(10_000); + expect(store.preset).toBeUndefined(); + await expect(store.cyclePreset()).rejects.toThrow("not running"); }); });