From cf54582d47da076aecdc55748535c14e7abb9b93 Mon Sep 17 00:00:00 2001 From: Illia Kostiikevych Date: Mon, 16 Nov 2026 17:45:27 +0100 Subject: [PATCH 1/8] Add a Claude voice button that presses Claude's voice mode through Accessibility Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 + client/voice-button-section.tsx | 50 ++- client/voice-button.tsx | 423 ++++++++++++++----------- docs/claude-voice-button.md | 66 ++++ index.client.tsx | 4 +- index.server.ts | 30 ++ server/voice-button/claude-ax.test.ts | 160 ++++++++++ server/voice-button/claude-ax.ts | 400 +++++++++++++++++++++++ server/voice-button/claude-mac.test.ts | 144 +++++++++ server/voice-button/claude-mac.ts | 163 ++++++++++ server/voice-button/claude-settings.ts | 18 ++ shared/claude-voice.test.ts | 18 ++ shared/claude-voice.ts | 83 +++++ 13 files changed, 1387 insertions(+), 182 deletions(-) create mode 100644 docs/claude-voice-button.md create mode 100644 server/voice-button/claude-ax.test.ts create mode 100644 server/voice-button/claude-ax.ts create mode 100644 server/voice-button/claude-mac.test.ts create mode 100644 server/voice-button/claude-mac.ts create mode 100644 server/voice-button/claude-settings.ts create mode 100644 shared/claude-voice.test.ts create mode 100644 shared/claude-voice.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7abcb7e..0f9c5af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ the MCP core behind it (up to 0.20 also the ChatGPT Site it published). It follo [Keep a Changelog](https://keepachangelog.com). Each `## [X.Y.Z]` section becomes the notes of the GitHub release vX.Y.Z. +## [Unreleased] + +### Added + +- **Claude voice button.** A second voice button, off until **Claude voice in Paseo** is turned on: one + tap brings the Claude desktop app forward and presses its voice mode button through Accessibility, + opening a new chat first when Claude is elsewhere. It finds the button by several signals, not only + its label, in English, Russian and Ukrainian. On a phone it opens a new Claude chat. See + docs/claude-voice-button.md. + ## [1.1.1] - 2026-11-17 ### Fixed diff --git a/client/voice-button-section.tsx b/client/voice-button-section.tsx index 090f8a9..64b278b 100644 --- a/client/voice-button-section.tsx +++ b/client/voice-button-section.tsx @@ -1,12 +1,14 @@ -// The voice button, reduced to one switch: on, Paseo shows a button that opens ChatGPT's own voice -// chat. Everything else keeps its default: ChatGPT's own shortcut on a Mac, and on an iPhone the -// Apple Shortcut named after the button. +// The voice buttons, reduced to one switch each: on, Paseo shows a button that opens ChatGPT's own +// voice chat, or starts Claude's voice mode. Everything else keeps its default: ChatGPT's own shortcut +// on a Mac and on an iPhone the Apple Shortcut named after the button; Claude's voice mode button +// pressed through Accessibility on a Mac and a new Claude chat on a phone. import type { PluginTheme } from "@getpaseo/plugin"; import { useRpc } from "@getpaseo/plugin/client"; import { SettingsCard, SettingsRow, SettingsSection, SettingsSwitch } from "@getpaseo/plugin/client/ui"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { claudeVoiceStatusRpc, defaultClaudeVoiceSettings, getClaudeVoiceRpc, setClaudeVoiceRpc } from "../shared/claude-voice.ts"; import { defaultVoiceButtonSettings, getVoiceButtonRpc, setVoiceButtonRpc } from "../shared/voice-button.ts"; -import { publishVoiceButton } from "./voice-button.tsx"; +import { publishClaudeVoice, publishVoiceButton } from "./voice-button.tsx"; const SETTINGS_KEY = ["god-mode", "voice-button"]; const errorText = (error: unknown) => String((error as Error)?.message ?? error); @@ -36,6 +38,46 @@ export function VoiceButtonStep(_props: { theme: PluginTheme }) { /> {loaded.isPending ? : null} + ); } + +const CLAUDE_KEY = ["god-mode", "claude-voice"]; +const CLAUDE_STATUS_KEY = ["god-mode", "claude-voice", "status"]; + +/** One switch: on, Paseo shows a button that starts Claude's voice mode in the Claude app. */ +export function ClaudeVoiceStep(_props: { theme: PluginTheme }) { + const get = useRpc(getClaudeVoiceRpc); + const set = useRpc(setClaudeVoiceRpc); + const status = useRpc(claudeVoiceStatusRpc); + const queryClient = useQueryClient(); + const loaded = useQuery({ queryKey: CLAUDE_KEY, queryFn: () => get({}) }); + const mac = useQuery({ queryKey: CLAUDE_STATUS_KEY, queryFn: () => status({}), enabled: loaded.data?.settings.enabled === true }); + const save = useMutation({ + mutationFn: (enabled: boolean) => set({ settings: { ...(loaded.data?.settings ?? defaultClaudeVoiceSettings()), enabled } }), + onSuccess: ({ settings }) => { + publishClaudeVoice(settings); + void queryClient.invalidateQueries({ queryKey: CLAUDE_KEY }); + }, + }); + const warning = + mac.data?.platform === "darwin" && !mac.data.claude + ? "The Claude app is not in Applications." + : mac.data?.accessibilityTrusted === false + ? "Allow Paseo in System Settings → Privacy & Security → Accessibility, or you tap Claude's voice button yourself." + : null; + return ( + + save.mutate(value)} + error={loaded.isError ? errorText(loaded.error) : save.isError ? errorText(save.error) : null} + /> + {warning ? : null} + + ); +} diff --git a/client/voice-button.tsx b/client/voice-button.tsx index 016a53c..d2828cd 100644 --- a/client/voice-button.tsx +++ b/client/voice-button.tsx @@ -1,36 +1,51 @@ -// The voice button wherever the user put it: a pill in every chat, a button in every workspace -// header, a sidebar row, a Command Center item and a slash command. Settings live on the daemon; -// this module keeps the latest copy so the settings section can apply a change at once. +// The voice buttons wherever the user put them: a pill in every chat, a button in every workspace +// header, a sidebar row, a Command Center item and a slash command. There are two, one each for +// ChatGPT's and Claude's own voice; they differ only in their settings and the RPC that launches them. +// Settings live on the daemon; each button keeps the latest copy so its settings section can apply a +// change at once. import type { PluginButton, PluginButtonRegistration, PluginClientContext, PluginCommandCapabilities, PluginSidebarItemProps } from "@getpaseo/plugin/client"; import { useRpc } from "@getpaseo/plugin/client"; import { useToast } from "@getpaseo/plugin/client/react-native"; import { SidebarRow } from "@getpaseo/plugin/client/ui"; import { useSyncExternalStore } from "react"; import { Linking, Platform } from "react-native"; -import { type VoiceButtonLaunch, type VoiceButtonSettings, getVoiceButtonRpc, voiceButtonLaunchRpc, voiceSlashName } from "../shared/voice-button.ts"; +import { type ClaudeVoiceSettings, claudeVoiceLaunchRpc, getClaudeVoiceRpc } from "../shared/claude-voice.ts"; +import { type VoiceButtonSettings, getVoiceButtonRpc, voiceButtonLaunchRpc, voiceSlashName } from "../shared/voice-button.ts"; -const ICON = "AudioLines"; - -let current: VoiceButtonSettings | null = null; -const listeners = new Set<() => void>(); - -/** Publishes saved settings to every surface of this client. */ -export function publishVoiceButton(settings: VoiceButtonSettings) { - current = settings; - for (const listener of listeners) listener(); +type Client = "ios" | "android" | "web"; +interface LaunchResult { + outcome: string; + needsOneTap: boolean; + url: string | null; + message: string; } +type Launch = (input: { client: Client }) => Promise; +type Rpc = PluginCommandCapabilities["rpc"]; -const subscribe = (listener: () => void) => { - listeners.add(listener); - return () => void listeners.delete(listener); -}; - -export const useVoiceButton = () => useSyncExternalStore(subscribe, () => current); +/** What every button's settings share. */ +interface ButtonSettings { + enabled: boolean; + name: string; + placements: VoiceButtonSettings["placements"]; +} -type Launch = (input: { client: "ios" | "android" | "web" }) => Promise; +interface VoiceButtonSpec { + /** The id of its pills, header buttons and Command Center item, unique per button. */ + id: string; + icon: string; + /** "ChatGPT" or "Claude": shown after the name. */ + assistant: string; + keywords: string[]; + /** A slash command name when the button's own name is not one plain word. */ + fallbackSlash: string; + load: (rpc: Rpc) => Promise; + launch: (rpc: Rpc, input: { client: Client }) => Promise; + /** The same launch bound by a hook, for the sidebar row. */ + useLaunch: () => Launch; +} -/** iOS runs the Shortcut on the phone; Mac, browser and Electron ask the daemon's Mac. */ -export async function launchVoice(launch: Launch): Promise { +/** iOS opens what the daemon returns on the phone; Mac, browser and Electron ask the daemon's Mac. */ +export async function launchVoice(launch: Launch): Promise { const client = Platform.OS === "ios" ? "ios" : Platform.OS === "android" ? "android" : "web"; const result = await launch({ client }); if (result.outcome === "unsupported") throw new Error(result.message); @@ -38,166 +53,220 @@ export async function launchVoice(launch: Launch): Promise { return result; } -const rpcLaunch = (rpc: PluginCommandCapabilities["rpc"]): Launch => (input) => rpc(voiceButtonLaunchRpc, input); - -export function VoiceButtonSidebarItem(_props: PluginSidebarItemProps) { - const settings = useVoiceButton(); - const launch = useRpc(voiceButtonLaunchRpc); - const toast = useToast(); - if (!settings?.enabled || !settings.placements.sidebar) return null; - return ( - { - launchVoice(launch) - .then((r) => toast.show(r.message, { variant: r.needsOneTap ? "info" : "success" })) - .catch((error: unknown) => toast.error(error instanceof Error ? error.message : String(error))); - }} - /> - ); -} +function createVoiceButton(spec: VoiceButtonSpec) { + let current: S | null = null; + const listeners = new Set<() => void>(); -export function contributeVoiceButton(client: PluginClientContext): () => void { - const lifetime = new AbortController(); - const agents = new Map(); - const workspaces = new Set(); - const pills = new Map(); - const headers = new Map(); - let commands: (() => void)[] = []; - - const shown = (place: keyof VoiceButtonSettings["placements"]) => !lifetime.signal.aborted && !!current?.enabled && current.placements[place]; - const button = (): PluginButton => ({ - title: `${current?.name}: ChatGPT voice`, - icon: ICON, - label: current?.name, - behavior: { - kind: "action", - async onPress() { - await launchVoice(rpcLaunch(client.rpc)); - }, - }, - }); - - const syncPill = (agentId: string) => { - pills.get(agentId)?.remove(); - pills.delete(agentId); - const workspaceId = agents.get(agentId); - if (workspaceId && shown("chats")) pills.set(agentId, client.addComposerPill({ id: "voice", workspaceId, agentId, button: button() })); + /** Publishes saved settings to every surface of this client. */ + const publish = (settings: S) => { + current = settings; + for (const listener of listeners) listener(); }; - const syncHeader = (workspaceId: string) => { - headers.get(workspaceId)?.remove(); - headers.delete(workspaceId); - if (workspaces.has(workspaceId) && shown("header")) headers.set(workspaceId, client.addHeaderButton({ id: "voice", workspaceId, button: button() })); - }; - const syncCommands = () => { - for (const remove of commands) remove(); - commands = []; - if (shown("commandCenter")) { - commands.push( - client.addCommandCenterItem({ - id: "voice", - title: `${current?.name}: ChatGPT voice`, - icon: ICON, - keywords: ["voice", "chatgpt", "talk"], - context: "global", - async onSelect({ rpc }) { - await launchVoice(rpcLaunch(rpc)); - }, - }), - ); - } - if (shown("slashCommand") && current) { - commands.push( - client.addSlashCommand({ - name: voiceSlashName(current.name), - description: `${current.name}: talk to ChatGPT`, - argumentHint: "", - context: "workspace", - async onSubmit({ rpc }) { - await launchVoice(rpcLaunch(rpc)); - }, - }), - ); - } - }; - const syncAll = () => { - for (const id of new Set([...agents.keys(), ...pills.keys()])) syncPill(id); - for (const id of new Set([...workspaces, ...headers.keys()])) syncHeader(id); - syncCommands(); + + const subscribe = (listener: () => void) => { + listeners.add(listener); + return () => void listeners.delete(listener); }; - const stopListening = subscribe(syncAll); - const failed = (what: string) => (error: unknown) => { - if (!lifetime.signal.aborted) console.error(`[god-mode] voice button: ${what} failed`, error); + const useSettings = () => useSyncExternalStore(subscribe, () => current); + const slashName = (name: string) => { + const word = voiceSlashName(name); + return word === "voice-chat" ? spec.fallbackSlash : word; }; - void client - .rpc(getVoiceButtonRpc, {}) - .then(({ settings }) => publishVoiceButton(settings)) - .catch(failed("loading settings")); - - void client.paseo.agents - .list({ subscribe: {}, signal: lifetime.signal }) - .then(({ subscription }) => { - subscription.subscribe({ - snapshot: ({ entries }) => { - const before = [...agents.keys()]; - agents.clear(); - for (const { agent } of entries) if (agent.workspaceId) agents.set(agent.id, agent.workspaceId); - for (const id of new Set([...before, ...agents.keys()])) syncPill(id); - }, - update: (message) => { - if (message.type !== "agent_update") return; - const update = message.payload; - if (update.kind === "remove") { - agents.delete(update.agentId); - syncPill(update.agentId); - } else if (update.agent.workspaceId && agents.get(update.agent.id) !== update.agent.workspaceId) { - agents.set(update.agent.id, update.agent.workspaceId); - syncPill(update.agent.id); - } - }, - }); - return undefined; - }) - .catch(failed("following chats")); - - void client.paseo.workspaces - .list({ subscribe: {} }) - .then(({ subscription }) => { - if (lifetime.signal.aborted) return void subscription.release(); - lifetime.signal.addEventListener("abort", () => void subscription.release()); - subscription.subscribe({ - snapshot: ({ entries }) => { - const before = [...workspaces]; - workspaces.clear(); - for (const workspace of entries) workspaces.add(workspace.id); - for (const id of new Set([...before, ...workspaces])) syncHeader(id); - }, - update: (message) => { - if (message.type !== "workspace_update") return; - const update = message.payload; - if (update.kind === "remove") { - workspaces.delete(update.id); - syncHeader(update.id); - } else if (!workspaces.has(update.workspace.id)) { - workspaces.add(update.workspace.id); - syncHeader(update.workspace.id); - } + function SidebarItem(_props: PluginSidebarItemProps) { + const settings = useSettings(); + const launch = spec.useLaunch(); + const toast = useToast(); + if (!settings?.enabled || !settings.placements.sidebar) return null; + return ( + { + launchVoice(launch) + .then((r) => toast.show(r.message, { variant: r.needsOneTap ? "info" : "success" })) + .catch((error: unknown) => toast.error(error instanceof Error ? error.message : String(error))); + }} + /> + ); + } + + function contribute(client: PluginClientContext): () => void { + const lifetime = new AbortController(); + const agents = new Map(); + const workspaces = new Set(); + const pills = new Map(); + const headers = new Map(); + let commands: (() => void)[] = []; + + const shown = (place: keyof ButtonSettings["placements"]) => !lifetime.signal.aborted && !!current?.enabled && current.placements[place]; + const rpcLaunch = (rpc: Rpc): Launch => (input) => spec.launch(rpc, input); + const button = (): PluginButton => ({ + title: `${current?.name}: ${spec.assistant} voice`, + icon: spec.icon, + label: current?.name, + behavior: { + kind: "action", + async onPress() { + await launchVoice(rpcLaunch(client.rpc)); }, - }); - return undefined; - }) - .catch(failed("following workspaces")); - - return () => { - lifetime.abort(); - stopListening(); - for (const registration of [...pills.values(), ...headers.values()]) registration.remove(); - pills.clear(); - headers.clear(); - for (const remove of commands) remove(); - commands = []; - }; + }, + }); + + const syncPill = (agentId: string) => { + pills.get(agentId)?.remove(); + pills.delete(agentId); + const workspaceId = agents.get(agentId); + if (workspaceId && shown("chats")) pills.set(agentId, client.addComposerPill({ id: spec.id, workspaceId, agentId, button: button() })); + }; + const syncHeader = (workspaceId: string) => { + headers.get(workspaceId)?.remove(); + headers.delete(workspaceId); + if (workspaces.has(workspaceId) && shown("header")) headers.set(workspaceId, client.addHeaderButton({ id: spec.id, workspaceId, button: button() })); + }; + const syncCommands = () => { + for (const remove of commands) remove(); + commands = []; + if (shown("commandCenter")) { + commands.push( + client.addCommandCenterItem({ + id: spec.id, + title: `${current?.name}: ${spec.assistant} voice`, + icon: spec.icon, + keywords: spec.keywords, + context: "global", + async onSelect({ rpc }) { + await launchVoice(rpcLaunch(rpc)); + }, + }), + ); + } + if (shown("slashCommand") && current) { + commands.push( + client.addSlashCommand({ + name: slashName(current.name), + description: `${current.name}: talk to ${spec.assistant}`, + argumentHint: "", + context: "workspace", + async onSubmit({ rpc }) { + await launchVoice(rpcLaunch(rpc)); + }, + }), + ); + } + }; + const syncAll = () => { + for (const id of new Set([...agents.keys(), ...pills.keys()])) syncPill(id); + for (const id of new Set([...workspaces, ...headers.keys()])) syncHeader(id); + syncCommands(); + }; + const stopListening = subscribe(syncAll); + + const failed = (what: string) => (error: unknown) => { + if (!lifetime.signal.aborted) console.error(`[god-mode] ${spec.id} button: ${what} failed`, error); + }; + + void spec + .load(client.rpc) + .then((settings) => publish(settings)) + .catch(failed("loading settings")); + + void client.paseo.agents + .list({ subscribe: {}, signal: lifetime.signal }) + .then(({ subscription }) => { + subscription.subscribe({ + snapshot: ({ entries }) => { + const before = [...agents.keys()]; + agents.clear(); + for (const { agent } of entries) if (agent.workspaceId) agents.set(agent.id, agent.workspaceId); + for (const id of new Set([...before, ...agents.keys()])) syncPill(id); + }, + update: (message) => { + if (message.type !== "agent_update") return; + const update = message.payload; + if (update.kind === "remove") { + agents.delete(update.agentId); + syncPill(update.agentId); + } else if (update.agent.workspaceId && agents.get(update.agent.id) !== update.agent.workspaceId) { + agents.set(update.agent.id, update.agent.workspaceId); + syncPill(update.agent.id); + } + }, + }); + return undefined; + }) + .catch(failed("following chats")); + + void client.paseo.workspaces + .list({ subscribe: {} }) + .then(({ subscription }) => { + if (lifetime.signal.aborted) return void subscription.release(); + lifetime.signal.addEventListener("abort", () => void subscription.release()); + subscription.subscribe({ + snapshot: ({ entries }) => { + const before = [...workspaces]; + workspaces.clear(); + for (const workspace of entries) workspaces.add(workspace.id); + for (const id of new Set([...before, ...workspaces])) syncHeader(id); + }, + update: (message) => { + if (message.type !== "workspace_update") return; + const update = message.payload; + if (update.kind === "remove") { + workspaces.delete(update.id); + syncHeader(update.id); + } else if (!workspaces.has(update.workspace.id)) { + workspaces.add(update.workspace.id); + syncHeader(update.workspace.id); + } + }, + }); + return undefined; + }) + .catch(failed("following workspaces")); + + return () => { + lifetime.abort(); + stopListening(); + for (const registration of [...pills.values(), ...headers.values()]) registration.remove(); + pills.clear(); + headers.clear(); + for (const remove of commands) remove(); + commands = []; + }; + } + + return { publish, useSettings, SidebarItem, contribute }; } + +const chatgpt = createVoiceButton({ + id: "voice", + icon: "AudioLines", + assistant: "ChatGPT", + keywords: ["voice", "chatgpt", "talk"], + fallbackSlash: "voice-chat", + load: async (rpc) => (await rpc(getVoiceButtonRpc, {})).settings, + launch: (rpc, input) => rpc(voiceButtonLaunchRpc, input), + useLaunch: () => useRpc(voiceButtonLaunchRpc), +}); + +const claude = createVoiceButton({ + id: "claude-voice", + icon: "AudioWaveform", + assistant: "Claude", + keywords: ["voice", "claude", "talk"], + fallbackSlash: "claude-voice", + load: async (rpc) => (await rpc(getClaudeVoiceRpc, {})).settings, + launch: (rpc, input) => rpc(claudeVoiceLaunchRpc, input), + useLaunch: () => useRpc(claudeVoiceLaunchRpc), +}); + +export const publishVoiceButton = chatgpt.publish; +export const useVoiceButton = chatgpt.useSettings; +export const VoiceButtonSidebarItem = chatgpt.SidebarItem; +export const contributeVoiceButton = chatgpt.contribute; + +export const publishClaudeVoice = claude.publish; +export const ClaudeVoiceSidebarItem = claude.SidebarItem; +export const contributeClaudeVoice = claude.contribute; diff --git a/docs/claude-voice-button.md b/docs/claude-voice-button.md new file mode 100644 index 0000000..228fb4f --- /dev/null +++ b/docs/claude-voice-button.md @@ -0,0 +1,66 @@ +# Claude voice button + +An optional button in Paseo that starts Claude's own voice mode in the Claude desktop app, so you talk +to Claude with your claude.ai account, its memory and the God Mode connector. It is the Claude twin of +the [ChatGPT voice button](voice-button.md). It is off until you turn on **Claude voice in Paseo** in +the God Mode screen, under **Voice button**, and it never calls an Anthropic API or sees the +conversation. + +## Settings + +| Setting | Default | What it does | +| --- | --- | --- | +| Name | Claude | The button's label and Command Center title; a plain one-word name is also its slash command (`/claude`), any other name uses `/claude-voice`. | +| Placements | header, Command Center, slash command | Also possible: a pill in every chat and a sidebar row. | +| On a Mac | Press Claude's voice mode button | `open` only brings Claude forward. | +| Profile | the default instance | A name such as `evo` targets the Claude instance whose data lives in `~/.claude-evo-data`. | +| iPhone shortcut | empty | Runs that Apple Shortcut instead of opening a new Claude chat. | + +Settings are kept in `~/.paseo/god-mode/claude-voice.json` on the daemon's Mac. + +## On a Mac + +Anthropic publishes no link, keyboard shortcut, menu item or Shortcuts action that starts voice mode +in the Claude desktop app (its "Voice shortcut" and "Dictation shortcut" only dictate). What the app +has is the voice mode button in the chat composer, the icon with the aria-label "Use voice mode". The +button presses it through Accessibility: + +1. It finds the Claude instance: the one started without `--user-data-dir`, or the chosen profile's + (started with `open -n` and that profile's data when it is not running), and brings that process + forward by its pid. +2. It reads Claude's window (`AXManualAccessibility` makes Electron publish it) and picks the voice + button by several signals, not only the label: a button of the composer that holds the message box, + icon-only, at the send spot while the box is empty, labelled "Use voice mode" or a known translation + (Russian and Ukrainian included), and never one of the known others (send, stop, dictation, + attachments, model, tools). An unknown interface language falls back to the send spot of an empty + composer. +3. When the window is not on a chat (Claude Code, Cowork, settings) or the box holds a draft, it opens + a new chat: the sidebar's link to `/new` (found by its address, so in any language), or, when only + one Claude instance runs, the link `claude://claude.ai/new`. Then it looks again. +4. After the press it checks that voice mode came up (the microphone controls appear). When voice is + already on it says so and does not toggle it off. + +Pressing needs Paseo in System Settings → Privacy & Security → Accessibility, the same permission as +the ChatGPT button. Without it, or when the button is not found, Claude is left in front and you tap +its voice button once. The first voice conversation also asks macOS for Claude's microphone access. + +The script can be run by hand without pressing anything: + +```sh +node -e 'import("./server/voice-button/claude-ax.ts").then(m => process.stdout.write(m.claudeAxScript()))' > /tmp/claude-ax.js +osascript -l JavaScript /tmp/claude-ax.js no 15000 dry +``` + +## On an iPhone + +There is nothing to press from outside: the Claude app has no Shortcuts action, link or intent that +starts voice mode. The button opens `https://claude.ai/new`, a link the app claims, and you tap the +voice button. In a car, Claude's own CarPlay icon starts a voice chat by itself. + +## Known limits + +- Claude's voice mode currently sees only one tool of each custom connector and asks for every write + (anthropics/claude-ai-mcp#1316, #1144), which limits what God Mode can do by voice until Anthropic + fixes it. +- A new release of claude.ai can move or rename the button; the label, position and send-spot signals + each cover for the others, and the toast says when nothing matched. diff --git a/index.client.tsx b/index.client.tsx index d099970..069371a 100644 --- a/index.client.tsx +++ b/index.client.tsx @@ -1,7 +1,7 @@ import type { PluginClientContext, PluginSidebarItemProps } from "@getpaseo/plugin/client"; import { SidebarRow } from "@getpaseo/plugin/client/ui"; import { HomeScreen } from "./client/home.tsx"; -import { VoiceButtonSidebarItem, contributeVoiceButton } from "./client/voice-button.tsx"; +import { ClaudeVoiceSidebarItem, VoiceButtonSidebarItem, contributeClaudeVoice, contributeVoiceButton } from "./client/voice-button.tsx"; function GodModeSidebarItem({ currentScreen, openScreen }: PluginSidebarItemProps) { return openScreen({ screenId: "home" })} />; @@ -13,6 +13,8 @@ export default function contribute(client: PluginClientContext) { client.addSidebarHeaderItem({ id: "home", title: "God Mode", Component: GodModeSidebarItem }), client.addSidebarFooterItem({ id: "voice", title: "Voice button", Component: VoiceButtonSidebarItem }), contributeVoiceButton(client), + client.addSidebarFooterItem({ id: "claude-voice", title: "Claude voice", Component: ClaudeVoiceSidebarItem }), + contributeClaudeVoice(client), ]; return () => { for (const remove of removers) remove(); diff --git a/index.server.ts b/index.server.ts index 2183d91..cc0c669 100644 --- a/index.server.ts +++ b/index.server.ts @@ -1,4 +1,5 @@ import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { CLAUDE_NEW_CHAT_URL, claudeVoiceLaunchRpc, claudeVoiceStatusRpc, getClaudeVoiceRpc, setClaudeVoiceRpc } from "./shared/claude-voice.ts"; import { connectRpc, disconnectRpc, statusRpc, tunnelSetupRpc } from "./shared/contracts.ts"; import { VERSION } from "./shared/version.ts"; import { @@ -10,6 +11,8 @@ import { } from "./shared/voice-button.ts"; import { Gateway } from "./server/gateway/service.ts"; import { Tunnel } from "./server/tunnel/cloudflared.ts"; +import { findClaude, launchClaudeOnMac, listInstances, listProfiles } from "./server/voice-button/claude-mac.ts"; +import { readClaudeVoice, writeClaudeVoice } from "./server/voice-button/claude-settings.ts"; import { detectVoiceHotkey, findChatGpt, isAccessibilityTrusted, launchOnMac, listShortcuts } from "./server/voice-button/mac.ts"; import { readVoiceButton, writeVoiceButton } from "./server/voice-button/settings.ts"; @@ -86,6 +89,33 @@ export default function contribute(server: PluginServerContext) { return launchOnMac(settings); }); + server.handle(getClaudeVoiceRpc, async () => ({ settings: await readClaudeVoice() })); + server.handle(setClaudeVoiceRpc, async ({ settings }) => ({ settings: await writeClaudeVoice(settings) })); + server.handle(claudeVoiceStatusRpc, async () => { + const mac = process.platform === "darwin"; + const claude = mac ? await findClaude() : null; + return { + platform: process.platform, + claude, + accessibilityTrusted: mac ? await isAccessibilityTrusted() : null, + profiles: mac ? listProfiles() : [], + running: claude ? (await listInstances(claude)).map((i) => i.profile) : [], + }; + }); + server.handle(claudeVoiceLaunchRpc, async ({ client }) => { + const settings = await readClaudeVoice(); + if (client === "ios") { + const name = settings.iosShortcutName; + return name + ? { outcome: "open-url" as const, via: "shortcut" as const, needsOneTap: false, url: shortcutRunUrl(name), message: `Running the shortcut "${name}".` } + : { outcome: "open-url" as const, via: "url" as const, needsOneTap: true, url: CLAUDE_NEW_CHAT_URL, message: "Claude is open: tap its voice button." }; + } + if (client === "android") { + return { outcome: "open-url" as const, via: "url" as const, needsOneTap: true, url: CLAUDE_NEW_CHAT_URL, message: "Claude is open: tap its voice button." }; + } + return launchClaudeOnMac(settings); + }); + return () => { void tunnel.stop(); diff --git a/server/voice-button/claude-ax.test.ts b/server/voice-button/claude-ax.test.ts new file mode 100644 index 0000000..319f150 --- /dev/null +++ b/server/voice-button/claude-ax.test.ts @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DECIDE_SOURCE, claudeAxScript } from "./claude-ax.ts"; + +interface Node { + i: number; + parent: number; + role: string; + subrole?: string; + label?: string; + title?: string; + value?: string; + url?: string; + enabled?: boolean; + focused?: boolean; + hasText?: boolean; + x?: number; + y?: number; + w?: number; + h?: number; +} +interface Decision { + action: "press" | "active" | "none"; + index?: number; + label?: string; + why?: string; + reason?: string; + screen?: string; + newChat?: number; +} + +const { decide } = new Function(`${DECIDE_SOURCE}; return { decide };`)() as { decide: (s: { nodes: Node[]; url: string }) => Decision }; + +/** + * A claude.ai window as the Accessibility tree shows it: a sidebar with a "New chat" link, a message + * list, and the composer (a text box with its buttons below it). `buttons` are the composer's, left to right. + */ +function window(options: { buttons: Partial[]; draft?: string; url?: string; focused?: boolean; extra?: Partial[] }) { + const nodes: Node[] = []; + const add = (n: Partial & { role: string; parent: number }) => { + const node = { w: 0, h: 0, x: 0, y: 0, ...n, i: nodes.length } as Node; + nodes.push(node); + return node.i; + }; + const area = add({ role: "AXWebArea", parent: -1 }); + const sidebar = add({ role: "AXGroup", parent: area }); + add({ role: "AXLink", parent: sidebar, label: "", url: "https://claude.ai/new", x: 10, y: 60, w: 200, h: 30 }); + add({ role: "AXButton", parent: sidebar, label: "Close sidebar", x: 10, y: 10, w: 30, h: 30 }); + const list = add({ role: "AXGroup", parent: area }); + add({ role: "AXButton", parent: list, label: "Copy", x: 400, y: 300, w: 30, h: 30 }); + add({ role: "AXButton", parent: list, label: "Retry", x: 440, y: 300, w: 30, h: 30 }); + const composer = add({ role: "AXGroup", parent: area }); + const box = add({ role: "AXGroup", parent: composer }); + add({ role: "AXTextArea", parent: box, value: options.draft ?? "", focused: options.focused ?? true, x: 300, y: 800, w: 700, h: 60 }); + const row = add({ role: "AXGroup", parent: composer }); + let x = 300; + for (const b of options.buttons) { + add({ role: "AXButton", parent: row, x, y: 870, w: 32, h: 32, ...b }); + x += b.x === undefined ? 40 : 0; + } + for (const e of options.extra ?? []) add({ parent: area, ...e } as Node); + return { nodes, url: options.url ?? "https://claude.ai/new" }; +} + +const attach = { label: "Add files and more" }; +const tools = { label: "Tools" }; +const model = { label: "Opus 5.5", hasText: true, x: 800 }; +const dictate = { label: "Dictate", x: 900 }; +const voice = (label: string) => ({ label, x: 960 }); +const pressedLabel = (s: ReturnType, d: Decision) => (d.action === "press" ? s.nodes[d.index as number].label : null); + +test("the English voice mode button is pressed by its label", () => { + const s = window({ buttons: [attach, tools, model, dictate, voice("Use voice mode")] }); + const d = decide(s); + assert.equal(d.action, "press"); + assert.equal(pressedLabel(s, d), "Use voice mode"); + assert.equal(d.why, "label"); +}); + +test("a Russian or Ukrainian interface is recognised too", () => { + for (const label of ["Использовать голосовой режим", "Голосовой режим", "Голосовий режим"]) { + const s = window({ buttons: [{ label: "Добавить файлы" }, { label: "Диктовка", x: 900 }, voice(label)] }); + assert.equal(pressedLabel(s, decide(s)), label, label); + } +}); + +test("an unknown interface language falls back to the send spot of an empty composer", () => { + const s = window({ buttons: [{ label: "Fichiers" }, { label: "Outils" }, voice("Utiliser le mode X")] }); + const d = decide(s); + assert.equal(pressedLabel(s, d), "Utiliser le mode X"); + assert.equal(d.why, "send spot of an empty composer"); +}); + +test("dictation is never mistaken for voice mode", () => { + const s = window({ buttons: [attach, { label: "Dictate", x: 960 }] }); + assert.equal(decide(s).action, "none"); + const ru = window({ buttons: [attach, { label: "Голосовой ввод", x: 960 }] }); + assert.equal(decide(ru).action, "none"); +}); + +test("with a draft the send button holds the spot and nothing is pressed", () => { + const s = window({ draft: "привет", buttons: [attach, dictate, { label: "Send message", x: 960 }] }); + const d = decide(s); + assert.equal(d.action, "none"); + assert.equal(d.reason, "draft"); + assert.equal(s.nodes[d.newChat as number].url, "https://claude.ai/new"); +}); + +test("a send or stop button in the spot is never pressed, even unlabelled in a known way", () => { + for (const label of ["Send message", "Stop response", "Отправить сообщение", "Остановить"]) { + const s = window({ buttons: [attach, { label, x: 960 }] }); + assert.equal(decide(s).action, "none", label); + } +}); + +test("voice already on is reported, not toggled off", () => { + const s = window({ buttons: [{ label: "Turn off microphone" }, { label: "End voice mode", x: 960 }] }); + assert.equal(decide(s).action, "active"); + const ru = window({ buttons: [{ label: "Выключить микрофон" }] }); + assert.equal(decide(ru).action, "active"); +}); + +test("the button is found when the message box is not focused", () => { + const s = window({ focused: false, buttons: [attach, dictate, voice("Use voice mode")] }); + assert.equal(pressedLabel(s, decide(s)), "Use voice mode"); +}); + +test("a labelled voice button elsewhere still wins over position", () => { + const s = window({ + buttons: [attach, { label: "Fichiers", x: 960 }], + extra: [{ role: "AXButton", label: "Use voice mode", x: 50, y: 400, w: 30, h: 30 }], + }); + assert.equal(pressedLabel(s, decide(s)), "Use voice mode"); +}); + +test("Claude Code or Cowork has no composer button for voice: open a new chat", () => { + const s = window({ url: "https://claude.ai/code/abc", buttons: [attach, { label: "Send", x: 960 }] }); + const d = decide(s); + assert.equal(d.action, "none"); + assert.equal(d.screen, "elsewhere"); + assert.ok((d.newChat as number) >= 0); +}); + +test("no window content at all says there is no composer", () => { + const d = decide({ nodes: [{ i: 0, parent: -1, role: "AXWebArea" }], url: "https://claude.ai/settings" }); + assert.equal(d.action, "none"); + assert.equal(d.reason, "no-composer"); + assert.equal(d.newChat, -1); +}); + +test("disabled buttons are skipped", () => { + const s = window({ buttons: [attach, { ...voice("Use voice mode"), enabled: false }] }); + assert.equal(decide(s).action, "none"); +}); + +test("the whole JXA program parses and defines run()", () => { + const script = claudeAxScript(); + assert.doesNotThrow(() => new Function(script)); + assert.match(script, /function run\(argv\)/); +}); diff --git a/server/voice-button/claude-ax.ts b/server/voice-button/claude-ax.ts new file mode 100644 index 0000000..50c915a --- /dev/null +++ b/server/voice-button/claude-ax.ts @@ -0,0 +1,400 @@ +// Finds and presses Claude's voice mode button through macOS Accessibility. Claude's desktop app shows +// claude.ai in an Electron window; its voice button is an icon with an aria-label ("Use voice mode"), +// no test id, sitting in the composer's send spot while the message box is empty. Anthropic publishes no +// link, shortcut or Shortcuts action that starts voice mode, so pressing the button is the only way. +// +// The script runs under `osascript -l JavaScript` (JXA). It is kept as plain JavaScript text in two +// parts: DECIDE_SOURCE is pure (a flat snapshot of the window in, a decision out) and is tested under +// Node; COLLECT_SOURCE reads the Accessibility tree, presses, navigates and verifies. + +/** + * Pure decision logic over a snapshot: `{ nodes, url }`, where each node is + * `{ i, parent, role, subrole, label, title, value, placeholder, url, enabled, focused, x, y, w, h, hasText }`. + */ +export const DECIDE_SOURCE = String.raw` +var VOICE_STRONG = /\bvoice mode\b|\bvoice chat\b|голосов\S* режим|режим\S* голос|голосов\S* (чат|розмов|разговор)|mode vocal|modo (de )?voz|sprachmodus|modalit[aà] vocale|tryb g[łl]osowy|spraakmodus|音声モード|음성 모드|语音模式|語音模式/i; +var VOICE_WEAK = /\bvoice\b|голос|vocal|\bvoz\b|stimm|g[łl]os/i; +var DICTATION = /dictat|диктов|диктуй|voice input|голосов\S* ввод|transcri/i; +var ACTIVE = /turn (on|off) (the )?microphone|(end|exit|leave|stop) voice|(включить|выключить|отключить|вимкнути|увімкнути) микрофон|(включить|выключить|отключить|вимкнути|увімкнути) мікрофон|заверш\S* голос|выйти из голос/i; +var DENY = /send|stop|cancel|attach|upload|\badd\b|plus|model|menu|tool|setting|close|copy|retry|edit|share|search|research|style|project|отправ|стоп|останов|отмен|прикреп|загруз|добав|модел|меню|инструмент|настро|закры|копир|повтор|измен|поделит|поиск|стил|проект/i; + +function textOf(n) { + return [n.label, n.title, n.help].filter(function (s) { return s; }).join(" ").trim(); +} + +function ancestors(nodes, i, limit) { + var out = []; + var at = nodes[i] ? nodes[i].parent : -1; + while (at !== undefined && at >= 0 && out.length < limit) { + out.push(at); + at = nodes[at] ? nodes[at].parent : -1; + } + return out; +} + +/** How many levels up from node i until an ancestor of node j (within limit); -1 when none. */ +function distance(nodes, i, j, limit) { + var up = ancestors(nodes, j, limit); + var at = i; + for (var level = 0; level <= limit; level++) { + if (at === j || up.indexOf(at) >= 0) return level; + at = nodes[at] ? nodes[at].parent : -1; + if (at === undefined || at < 0) return -1; + } + return -1; +} + +function isTextBox(n) { + return n.role === "AXTextArea" || (n.role === "AXTextField" && n.subrole !== "AXSearchField"); +} + +/** The message box: the focused text box, else the lowest wide one. */ +function pickComposer(nodes) { + var boxes = nodes.filter(function (n) { return n && isTextBox(n) && n.w > 120; }); + var focused = boxes.filter(function (n) { return n.focused; }); + if (focused.length) return focused[0]; + boxes.sort(function (a, b) { return (b.y + b.h) - (a.y + a.h); }); + return boxes[0] || null; +} + +function urlPath(url) { + var m = /^[a-z]+:\/\/[^\/]+(\/[^?#]*)?/i.exec(url || ""); + return m ? (m[1] || "/") : ""; +} + +/** Where the window is: "chat" (a new or existing chat), "elsewhere" (Code, Cowork, settings…) or "unknown". */ +function screenOf(url) { + var path = urlPath(url); + if (!path) return "unknown"; + if (path === "/new" || path === "/" || /^\/chat\//.test(path) || /^\/project\/[^\/]+$/.test(path)) return "chat"; + return "elsewhere"; +} + +function decide(snapshot) { + var nodes = snapshot.nodes; + var buttons = nodes.filter(function (n) { return n && n.role === "AXButton" && n.enabled !== false && n.w > 0 && n.h > 0; }); + for (var a = 0; a < buttons.length; a++) { + if (ACTIVE.test(textOf(buttons[a]))) return { action: "active", label: textOf(buttons[a]) }; + } + var composer = pickComposer(nodes); + var empty = composer ? !(composer.value && String(composer.value).trim()) : false; + var near = []; + var candidates = []; + for (var b = 0; b < buttons.length; b++) { + var n = buttons[b]; + var text = textOf(n); + var c = { node: n, text: text, score: 0, inComposer: false, strong: false, weak: false }; + if (composer) { + var d = distance(nodes, n.i, composer.i, 7); + if (d >= 0 && d <= 7 && n.y + n.h / 2 >= composer.y - 8) { + c.inComposer = true; + near.push(c); + } + } + if (DICTATION.test(text) || ACTIVE.test(text)) continue; + if (VOICE_STRONG.test(text)) { c.strong = true; c.score += 100; } + else if (VOICE_WEAK.test(text) && !DENY.test(text)) { c.weak = true; c.score += 40; } + if (!n.hasText) c.score += 10; + if (c.inComposer) c.score += 30; + candidates.push(c); + } + var rightmost = null; + for (var r = 0; r < near.length; r++) { + if (!rightmost || near[r].node.x + near[r].node.w > rightmost.node.x + rightmost.node.w) rightmost = near[r]; + } + for (var k = 0; k < candidates.length; k++) { + if (rightmost && candidates[k].node === rightmost.node) candidates[k].score += 15; + } + candidates.sort(function (x, y) { return y.score - x.score; }); + var best = candidates[0]; + if (best && best.strong) return { action: "press", index: best.node.i, label: best.text, why: "label" }; + // No label we know (another interface language): the voice button takes the send spot while the + // message box is empty, so it is the rightmost icon of the composer and never one of the known others. + if (best && best.weak && best.inComposer) { + return { action: "press", index: best.node.i, label: best.text, why: "voice word in the composer" }; + } + if (rightmost && empty && !rightmost.node.hasText && rightmost.text && !DENY.test(rightmost.text) && !DICTATION.test(rightmost.text) && !ACTIVE.test(rightmost.text)) { + return { action: "press", index: rightmost.node.i, label: rightmost.text, why: "send spot of an empty composer" }; + } + var links = nodes.filter(function (n) { return n && n.role === "AXLink" && urlPath(n.url) === "/new" && n.w > 0; }); + var reason = !composer ? "no-composer" : !empty ? "draft" : "no-button"; + return { + action: "none", + reason: reason, + screen: screenOf(snapshot.url), + newChat: links.length ? links[0].i : -1, + seen: buttons.length, + labels: near.map(function (x) { return x.text; }).slice(0, 12), + }; +} +`; + +/** Reads the tree, presses, navigates to a new chat when needed and checks that voice started. */ +export const COLLECT_SOURCE = String.raw` +ObjC.import("ApplicationServices"); +ObjC.import("AppKit"); + +var ATTRS = ["AXRole", "AXSubrole", "AXDescription", "AXTitle", "AXHelp", "AXChildren", "AXEnabled", "AXFocused", "AXPosition", "AXSize", "AXURL", "AXValue", "AXPlaceholderValue"]; + +function attr(el, name) { + var ref = Ref(); + return $.AXUIElementCopyAttributeValue(el, $(name), ref) === 0 ? ObjC.castRefToObject(ref[0]) : undefined; +} + +function many(el) { + var ref = Ref(); + if ($.AXUIElementCopyMultipleAttributeValues(el, $(ATTRS), 0, ref) !== 0) return null; + var arr = ObjC.castRefToObject(ref[0]); + var out = {}; + for (var i = 0; i < ATTRS.length; i++) { + var v = arr.objectAtIndex(i); + out[ATTRS[i]] = v; + } + return out; +} + +function isAxError(v) { + try { + var d = v.description.js; + return /kAXValueAXErrorType/.test(d); + } catch (e) { + return false; + } +} + +function val(raw, name) { + var v = raw[name]; + if (v === undefined || v === null || isAxError(v)) return undefined; + return v; +} + +function text(v) { + if (v === undefined) return ""; + try { + var u = ObjC.unwrap(v); + if (typeof u === "string") return u; + if (v.absoluteString) return v.absoluteString.js || ""; + } catch (e) {} + return ""; +} + +function geometry(v) { + if (v === undefined) return null; + try { + var d = v.description.js; + var m = /x:(-?[\d.]+) y:(-?[\d.]+)/.exec(d) || /w:(-?[\d.]+) h:(-?[\d.]+)/.exec(d); + if (m) return [parseFloat(m[1]), parseFloat(m[2])]; + } catch (e) {} + return null; +} + +var KEEP = { AXButton: 1, AXLink: 1, AXTextArea: 1, AXTextField: 1, AXStaticText: 0 }; + +/** One pass over a subtree; every visited element gets an index and a parent so the decision can relate them. */ +function collect(root, budget) { + var nodes = []; + var elements = []; + var stack = [[root, -1]]; + var visited = 0; + while (stack.length && visited < budget) { + var item = stack.pop(); + var el = item[0]; + var raw = many(el); + if (!raw) continue; + var i = visited++; + var role = text(val(raw, "AXRole")); + var n = { i: i, parent: item[1], role: role }; + if (KEEP[role] === 1) { + var pos = geometry(val(raw, "AXPosition")) || [0, 0]; + var size = geometry(val(raw, "AXSize")) || [0, 0]; + var enabled = val(raw, "AXEnabled"); + var focused = val(raw, "AXFocused"); + n.subrole = text(val(raw, "AXSubrole")); + n.label = text(val(raw, "AXDescription")); + n.title = text(val(raw, "AXTitle")); + n.help = text(val(raw, "AXHelp")); + n.url = text(val(raw, "AXURL")); + n.value = role === "AXButton" ? "" : text(val(raw, "AXValue")); + n.placeholder = text(val(raw, "AXPlaceholderValue")); + n.enabled = enabled === undefined ? true : ObjC.unwrap(enabled) !== false; + n.focused = focused === undefined ? false : ObjC.unwrap(focused) === true; + n.x = pos[0]; n.y = pos[1]; n.w = size[0]; n.h = size[1]; + n.hasText = false; + elements[i] = el; + } + nodes[i] = n; + var kids = val(raw, "AXChildren"); + if (kids !== undefined) { + var count = kids.count; + for (var k = count - 1; k >= 0; k--) stack.push([kids.objectAtIndex(k), i]); + } + if (role === "AXStaticText" && n.parent >= 0 && nodes[n.parent] && nodes[n.parent].role === "AXButton") nodes[n.parent].hasText = true; + } + return { nodes: nodes, elements: elements, visited: visited, truncated: stack.length > 0 }; +} + +function findRole(root, role, depth) { + var queue = [[root, 0]]; + while (queue.length) { + var item = queue.shift(); + if (roleOf(item[0]) === role) return item[0]; + if (item[1] >= depth) continue; + var kids = attr(item[0], "AXChildren"); + if (kids === undefined) continue; + for (var k = 0; k < kids.count; k++) queue.push([kids.objectAtIndex(k), item[1] + 1]); + } + return null; +} + +function roleOf(el) { + return text(attr(el, "AXRole")); +} + +function sleepMs(ms) { delay(ms / 1000); } + +function now() { return Date.now(); } + +function waitFor(fn, ms, step) { + var end = now() + ms; + var got = fn(); + while (!got && now() < end) { + sleepMs(step || 150); + got = fn(); + } + return got; +} + +function webAreaOf(app) { + var win = attr(app, "AXFocusedWindow") || attr(app, "AXMainWindow"); + if (win === undefined) { + var ws = attr(app, "AXWindows"); + if (ws !== undefined && ws.count > 0) win = ws.objectAtIndex(0); + } + if (win === undefined || roleOf(win) !== "AXWindow") return null; + var area = findRole(win, "AXWebArea", 14); + if (!area) return null; + var kids = attr(area, "AXChildren"); + if (kids === undefined || kids.count === 0) return null; + return { win: win, area: area }; +} + +function areaUrl(area) { + return text(attr(area, "AXURL")); +} + +/** The focused element's surroundings first: a long chat has thousands of elements, the composer a few dozen. */ +function snapshotNear(app, area) { + var f = attr(app, "AXFocusedUIElement"); + if (f === undefined) return null; + var role = roleOf(f); + if (role !== "AXTextArea" && role !== "AXTextField") return null; + var at = f; + for (var level = 0; level < 7; level++) { + var p = attr(at, "AXParent"); + if (p === undefined) break; + at = p; + } + var snap = collect(at, 1500); + snap.url = areaUrl(area); + return snap; +} + +function snapshotAll(area, budget) { + var snap = collect(area, budget); + snap.url = areaUrl(area); + return snap; +} + +function look(app, area) { + var near = snapshotNear(app, area); + if (near) { + var d = decide(near); + if (d.action !== "none") return { snap: near, d: d, scope: "composer" }; + } + var all = snapshotAll(area, 40000); + return { snap: all, d: decide(all), scope: "window" }; +} + +function press(el) { + return $.AXUIElementPerformAction(el, $("AXPress")) === 0; +} + +function front(app) { + $.AXUIElementSetAttributeValue(app, $("AXFrontmost"), $.kCFBooleanTrue); +} + +function run(argv) { + var pid = parseInt(argv[0], 10); + var mayDeepLink = argv[1] === "deeplink"; + var waitMs = parseInt(argv[2] || "15000", 10); + // "dry": find and report, press and navigate nothing (for checking a Mac by hand). + var dry = argv[3] === "dry"; + var steps = []; + var app = $.AXUIElementCreateApplication(pid); + $.AXUIElementSetAttributeValue(app, $("AXManualAccessibility"), $.kCFBooleanTrue); + if (!dry) front(app); + var web = waitFor(function () { return webAreaOf(app); }, waitMs, 250); + if (!web) return JSON.stringify({ result: "no-window", steps: steps }); + + for (var attempt = 0; attempt < 2; attempt++) { + var seen = waitFor(function () { + var w = webAreaOf(app); + if (!w) return null; + web = w; + var l = look(app, w.area); + return l.d.action === "none" && attempt === 1 && l.d.reason === "no-composer" ? null : l; + }, attempt === 0 ? 1500 : 8000, 300); + if (!seen) seen = look(app, web.area); + var d = seen.d; + steps.push({ attempt: attempt, scope: seen.scope, visited: seen.snap.visited, url: seen.snap.url, decision: d }); + if (d.action === "active") return JSON.stringify({ result: "already-on", steps: steps }); + if (dry) return JSON.stringify({ result: "dry-run", steps: steps }); + if (d.action === "press") { + var el = seen.snap.elements[d.index]; + front(app); + if (!el || !press(el)) return JSON.stringify({ result: "press-failed", steps: steps }); + var on = waitFor(function () { + var w = webAreaOf(app); + if (!w) return null; + var after = look(app, w.area).d; + return after.action === "active" ? after : null; + }, 4000, 300); + return JSON.stringify({ result: on ? "started" : "pressed", label: d.label, why: d.why, steps: steps }); + } + if (attempt === 1) break; + // Not a chat, a draft in the box or no button: open a new chat and look again. + if (d.newChat >= 0 && seen.snap.elements[d.newChat] && press(seen.snap.elements[d.newChat])) { + steps.push({ navigate: "new-chat-link" }); + } else if (mayDeepLink) { + $.NSWorkspace.sharedWorkspace.openURL($.NSURL.URLWithString("claude://claude.ai/new")); + steps.push({ navigate: "deep-link" }); + } else { + break; + } + sleepMs(600); + front(app); + } + return JSON.stringify({ result: "not-found", steps: steps }); +} +`; + +/** The whole JXA program; `osascript -l JavaScript -e