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
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion com.todd.streamdeckcodex.sdPlugin/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
{
Expand Down
148 changes: 148 additions & 0 deletions native/Antigravity.swift
Original file line number Diff line number Diff line change
@@ -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<String>
) -> [(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<T>(_ 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")
}
}
1 change: 1 addition & 0 deletions native/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
19 changes: 10 additions & 9 deletions src/actions/antigravity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<void> {
if ([...this.actions].length === 0) return;
await antigravityStore.refreshPreset();
await super.refreshAll();
}

async onKeyDown(event: KeyDownEvent): Promise<void> {
try {
await antigravityStore.cyclePreset();
Expand All @@ -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",
);
Expand Down
101 changes: 45 additions & 56 deletions src/lib/antigravity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<AntigravityPreset, string> = {
REQUEST_REVIEW: "Review",
DEFAULT: "Default",
TURBO: "Turbo",
};

export interface AntigravityQuotaBucket {
/** First word of the quota group, e.g. "GEMINI" or "CLAUDE". */
Expand Down Expand Up @@ -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<void> | undefined;
reason: AntigravityReason | undefined = "NOT OPEN";
#quotaAt = 0;
#liveAt = 0;
#refreshing: Promise<void> | undefined;
readonly #daemon: () => Daemon | undefined;
readonly #native: (request: "read" | "cycle") => Promise<NativeControlResult>;

constructor(daemon: () => Daemon | undefined = findAntigravityDaemon) {
constructor(
daemon: () => Daemon | undefined = findAntigravityDaemon,
native: (request: "read" | "cycle") => Promise<NativeControlResult> = (
request,
) => invoke("antigravity-permission", request, 8_000),
) {
this.#daemon = daemon;
this.#native = native;
}

async #call(method: string, body: unknown = {}): Promise<unknown> {
Expand Down Expand Up @@ -234,17 +212,13 @@ export class AntigravityStore {
if (!this.#daemon()) {
this.quota = [];
this.context = undefined;
this.preset = undefined;
this.reason = "NOT OPEN";
this.#quotaAt = this.#liveAt = 0;
return;
}
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"),
);
Expand Down Expand Up @@ -274,23 +248,38 @@ export class AntigravityStore {
}
}

/** Apply the next preset and return what the server then reports. */
async cyclePreset(): Promise<AntigravityPreset> {
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<void> {
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<string> {
this.preset = await this.#permission("cycle");
this.#presetAt = Date.now();
return this.preset;
}

async #permission(request: "read" | "cycle"): Promise<string> {
const result = await this.#native(request);
if (!result.model) throw new Error(result.message);
return result.model;
}
}

Expand Down
Loading
Loading