diff --git a/CHANGELOG.md b/CHANGELOG.md index 7abcb7e..3cd2609 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ 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. +- **Each voice button's name and places on the screen.** Under **Voice buttons**, once a button is on: + its name (the label, Command Center title and slash command) and where it shows (workspace header, + every chat, sidebar, Command Center, slash command). + ## [1.1.1] - 2026-11-17 ### Fixed diff --git a/client/voice-button-section.tsx b/client/voice-button-section.tsx index 090f8a9..85647ab 100644 --- a/client/voice-button-section.tsx +++ b/client/voice-button-section.tsx @@ -1,41 +1,185 @@ -// 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' settings: for each one a switch, and once it is on a summary row that opens its name +// and where it shows. +// ChatGPT's button opens ChatGPT's own voice chat (its own shortcut on a Mac, on an iPhone the Apple +// Shortcut named after the button); Claude's presses Claude's voice mode button through Accessibility +// on a Mac and opens 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 { SettingsAction, SettingsCard, SettingsInput, SettingsRow, SettingsSection, SettingsSwitch } from "@getpaseo/plugin/client/ui"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { defaultVoiceButtonSettings, getVoiceButtonRpc, setVoiceButtonRpc } from "../shared/voice-button.ts"; -import { publishVoiceButton } from "./voice-button.tsx"; +import { useEffect, useRef, useState } from "react"; +import { type ClaudeVoiceSettings, claudeVoiceStatusRpc, getClaudeVoiceRpc, setClaudeVoiceRpc } from "../shared/claude-voice.ts"; +import { type VoiceButtonSettings, getVoiceButtonRpc, setVoiceButtonRpc } from "../shared/voice-button.ts"; +import { publishClaudeVoice, publishVoiceButton, voiceSlashFor } from "./voice-button.tsx"; -const SETTINGS_KEY = ["god-mode", "voice-button"]; const errorText = (error: unknown) => String((error as Error)?.message ?? error); -export function VoiceButtonStep(_props: { theme: PluginTheme }) { +type Placement = keyof VoiceButtonSettings["placements"]; +type ButtonSettings = VoiceButtonSettings | ClaudeVoiceSettings; + +const PLACEMENTS: { key: Placement; label: string; hint: string }[] = [ + { key: "header", label: "Workspace header", hint: "A button at the top of every workspace." }, + { key: "chats", label: "Every chat", hint: "A pill above the message box of every chat." }, + { key: "sidebar", label: "Sidebar", hint: "A row at the bottom of the sidebar." }, + { key: "commandCenter", label: "Command Center", hint: "An item in Command Center." }, + { key: "slashCommand", label: "Slash command", hint: "A command typed in a chat." }, +]; + +/** A name a button can take: what the schema allows, so the input never saves one the daemon refuses. */ +const nameProblem = (name: string) => (!name.trim() ? "Give the button a name." : name.trim().length > 24 ? "At most 24 characters." : null); + +function VoiceButtonCard(props: { + title: string; + hint: string; + settings: S | undefined; + loadError: unknown; + save: (settings: S) => void; + saving: boolean; + saveError: unknown; + slashFor: (name: string) => string; + placeholder: string; + warning?: string | null; +}) { + const { settings } = props; + const [name, setName] = useState(null); + const [open, setOpen] = useState(false); + const timer = useRef | null>(null); + // The name is saved after a pause; by then a switch may have changed, so it merges into the latest. + const latest = useRef(settings); + latest.current = settings; + useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []); + + const change = (patch: Partial) => { + if (latest.current) props.save({ ...latest.current, ...patch }); + }; + // Saved half a second after the last key, so the buttons are not renamed letter by letter. + const typeName = (text: string) => { + setName(text); + if (timer.current) clearTimeout(timer.current); + if (nameProblem(text)) return; + timer.current = setTimeout(() => change({ name: text.trim() } as Partial), 500); + }; + const shownName = name ?? settings?.name ?? ""; + const slash = props.slashFor(shownName); + + return ( + + change({ enabled } as Partial)} + error={props.loadError ? errorText(props.loadError) : props.saveError ? errorText(props.saveError) : null} + /> + {!settings && !props.loadError ? : null} + {props.warning ? : null} + {settings?.enabled ? ( + settings.placements[p.key]).map((p) => (p.key === "slashCommand" ? `/${slash}` : p.label)).join(", ") || "Shown nowhere"} + actionLabel={open ? "Done" : "Edit"} + onPress={() => setOpen(!open)} + /> + ) : null} + {settings?.enabled && open ? ( + <> + + {PLACEMENTS.map((p) => ( + change({ placements: { ...settings.placements, [p.key]: value } } as Partial)} + /> + ))} + + ) : null} + + ); +} + +const CHATGPT_KEY = ["god-mode", "voice-button"]; +const CLAUDE_KEY = ["god-mode", "claude-voice"]; +const CLAUDE_STATUS_KEY = ["god-mode", "claude-voice", "status"]; + +function ChatGptVoiceCard() { const get = useRpc(getVoiceButtonRpc); const set = useRpc(setVoiceButtonRpc); const queryClient = useQueryClient(); - const loaded = useQuery({ queryKey: SETTINGS_KEY, queryFn: () => get({}) }); + const loaded = useQuery({ queryKey: CHATGPT_KEY, queryFn: () => get({}) }); const save = useMutation({ - mutationFn: (enabled: boolean) => set({ settings: { ...(loaded.data?.settings ?? defaultVoiceButtonSettings()), enabled } }), + mutationFn: (settings: VoiceButtonSettings) => set({ settings }), onSuccess: ({ settings }) => { publishVoiceButton(settings); - void queryClient.invalidateQueries({ queryKey: SETTINGS_KEY }); + queryClient.setQueryData(CHATGPT_KEY, { settings }); }, }); return ( - - - save.mutate(value)} - error={loaded.isError ? errorText(loaded.error) : save.isError ? errorText(save.error) : null} - /> - {loaded.isPending ? : null} - + save.mutate(settings)} + saving={save.isPending} + saveError={save.isError ? save.error : null} + slashFor={voiceSlashFor.chatgpt} + placeholder="Jarvis" + /> + ); +} + +function ClaudeVoiceCard() { + 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: (settings: ClaudeVoiceSettings) => set({ settings }), + onSuccess: ({ settings }) => { + publishClaudeVoice(settings); + queryClient.setQueryData(CLAUDE_KEY, { settings }); + }, + }); + 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(settings)} + saving={save.isPending} + saveError={save.isError ? save.error : null} + slashFor={voiceSlashFor.claude} + placeholder="Claude" + warning={warning} + /> + ); +} + +export function VoiceButtonStep(_props: { theme: PluginTheme }) { + return ( + + + ); } diff --git a/client/voice-button.tsx b/client/voice-button.tsx index 016a53c..e4aad9e 100644 --- a/client/voice-button.tsx +++ b/client/voice-button.tsx @@ -1,36 +1,53 @@ -// 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; + /** A button whose slash command wins when both would take the same one; this one then uses fallbackSlash. */ + yieldsTo?: { slash: () => string | null; subscribe: (listener: () => void) => () => void }; +} -/** 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 +55,228 @@ 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); + if (word === "voice-chat" || word === spec.yieldsTo?.slash()) return spec.fallbackSlash; + return word; }; + /** The slash command this button registers now, or null when it registers none. */ + const slash = () => (current?.enabled && current.placements.slashCommand ? slashName(current.name) : null); - 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 stopFollowing = spec.yieldsTo?.subscribe(syncCommands) ?? (() => {}); + + 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(); + stopFollowing(); + for (const registration of [...pills.values(), ...headers.values()]) registration.remove(); + pills.clear(); + headers.clear(); + for (const remove of commands) remove(); + commands = []; + }; + } + + return { publish, subscribe, useSettings, slash, slashName, 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), + yieldsTo: { slash: chatgpt.slash, subscribe: chatgpt.subscribe }, +}); + +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; +/** The slash command each button takes for a name, after the two have settled a clash. */ +export const voiceSlashFor = { chatgpt: chatgpt.slashName, claude: claude.slashName }; +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..8d08c6f --- /dev/null +++ b/docs/claude-voice-button.md @@ -0,0 +1,80 @@ +# 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 buttons**, where you also give it its name and choose where it shows, 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 windows. `AXManualAccessibility` makes Electron publish the page, about two seconds + after it is set; it is set once and left alone, since every new set starts that over (set every + 300 ms, a freshly started Claude never showed its page). In JXA it has to be an NSNumber bool: + `$.kCFBooleanTrue` is refused. The claude.ai page + sits inside the app's own `file://` page, and Claude Code opens windows of its own, so it takes the + claude.ai page of the window that is on a chat and raises that window. +3. It picks the voice button by several signals, not only the label: a button of the composer that + holds the message box, icon-only, labelled "Use voice mode" or a known translation (the Russian + interface says «Включить голосовой режим»; Ukrainian too), and never one of the known others (send, + stop, dictation, attachments, model, tools, read aloud). With a label it does not know, it takes the + icon right after the dictation button, which is where voice mode sits, and only while the message + box is empty (with a draft, send can take that spot). Right before the press it reads the button's + label again, in case the composer changed under it. +4. When nothing matches it recovers, in order: Escape, sent only while that Claude is frontmost, closes + what covers the chat (settings, a menu, a dialog: Claude hides everything under a modal); then, when + the window is not on a chat, a new chat: the sidebar's New chat («Создать»), only on a chat screen since on Claude Code's screen the + same button starts a Code session, or, when only one Claude instance runs, the link + `claude://claude.ai/new`. Then it looks again. A draft in the message box hides the voice button; + the draft is the user's text, so nothing is done about it and the toast says so. +5. After the press it checks that voice mode came up (the microphone control, «Выключить микрофон» / + "Turn off microphone", appears). 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, place and dictation-neighbour + signals each cover for the others, and the toast says when nothing matched. +- macOS hides every window from Accessibility while the screen is locked: the button then only brings + Claude forward. +- Measured on 2026-11-17 (Claude 5.11492.5, Russian interface), from the Paseo button to voice on: + about 2 s with Claude running, 5 to 9 s with Claude closed, about 3 s with settings open over a chat. diff --git a/docs/voice-button.md b/docs/voice-button.md index d3638ab..5a3454a 100644 --- a/docs/voice-button.md +++ b/docs/voice-button.md @@ -7,19 +7,19 @@ OpenAI API or sees the conversation. ## Settings -The screen has one switch, **ChatGPT voice in Paseo** (off by default): on, Paseo shows the button. -The other settings are no longer on the screen and keep their defaults: +The God Mode screen has, under **Voice buttons**, a switch **ChatGPT voice in Paseo** (off by default). +Once it is on, the card shows a row with the button's name and where it shows; **Edit** opens it: | Setting | Default | What it does | | --- | --- | --- | -| Name | Jarvis | The button's label and Command Center title. A plain one-word name is also its slash command (`/jarvis`); any other name uses `/voice-chat`. | -| Placements | all on | A pill in every chat, a button in every workspace header (a new chat has no pill yet), a sidebar row, a Command Center item, a slash command. | -| On a Mac | Press ChatGPT's voice shortcut | How the Mac starts voice; see below. | -| iPhone shortcut | the name | The Apple Shortcut the iPhone runs. | - -Settings are kept in `~/.paseo/god-mode/voice-button.json` on the daemon's Mac. The switch changes -only whether the button is on, so a value an earlier version stored in that file stays in force. -Other devices pick up a change the next time Paseo loads the plugin. +| Name | Jarvis | The button's label and Command Center title. A plain one-word name is also its slash command (`/jarvis`); any other name uses `/voice-chat`. On an iPhone it is also the Apple Shortcut the button runs. | +| Workspace header, Every chat, Sidebar, Command Center, Slash command | all on | Where the button shows: a button at the top of every workspace, a pill above every chat's message box, a sidebar row, a Command Center item, a slash command. | + +The name is saved half a second after the last key. Two settings are not on the screen and keep their +defaults: how a Mac starts voice (ChatGPT's own shortcut) and the iPhone shortcut's own name. + +Settings are kept in `~/.paseo/god-mode/voice-button.json` on the daemon's Mac. The device you change +them on applies them at once; other devices pick up a change the next time Paseo loads the plugin. ## On a Mac 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..dbdc8df --- /dev/null +++ b/server/voice-button/claude-ax.test.ts @@ -0,0 +1,228 @@ +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 of the desktop app showed it (2026-11-17): a sidebar + * with a "New chat" link, a message list with its own buttons, and the composer: the message box with + * the send button at its right, and below it a row of icons (attachments, dictation, voice mode). + * `buttons` are that row, left to right. + */ +function window(options: { buttons: Partial[]; draft?: string; url?: string; focused?: boolean; send?: string | null; link?: 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 }); + if (options.link !== false) add({ role: "AXLink", parent: sidebar, label: "", url: "https://claude.ai/new", x: 355, y: 90, w: 268, h: 32 }); + add({ role: "AXButton", parent: sidebar, label: "Close sidebar", x: 355, y: 41, w: 28, h: 28 }); + const list = add({ role: "AXGroup", parent: area }); + add({ role: "AXButton", parent: list, label: "Copy", x: 753, y: 561, w: 24, h: 25 }); + add({ role: "AXButton", parent: list, label: "Read aloud", x: 777, y: 561, w: 24, h: 25 }); + add({ role: "AXButton", parent: list, label: "Retry", x: 849, y: 561, w: 24, h: 25 }); + const composer = add({ role: "AXGroup", parent: area }); + const top = add({ role: "AXGroup", parent: composer }); + const box = add({ role: "AXGroup", parent: top }); + add({ role: "AXTextArea", parent: box, label: "Write your prompt to Claude", value: options.draft ?? "", focused: options.focused ?? true, x: 753, y: 951, w: 710, h: 21 }); + const send = options.send === undefined ? "Send message" : options.send; + if (send) add({ role: "AXButton", parent: top, label: send, x: 1471, y: 947, w: 28, h: 28 }); + const row = add({ role: "AXGroup", parent: composer }); + let x = 746; + for (const b of options.buttons) { + add({ role: "AXButton", parent: row, x, y: 991, w: 24, h: 24, ...b }); + x += 28; + } + 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 dictate = { label: "Dictate" }; +const voice = (label: string) => ({ label }); +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, 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({ send: "Отправить сообщение", buttons: [{ label: "Добавить файлы" }, { label: "Диктовать" }, voice(label)] }); + assert.equal(pressedLabel(s, decide(s)), label, label); + } +}); + +test("a voice label we do not know is still found right after the dictation button", () => { + const s = window({ buttons: [attach, dictate, voice("Talk with Claude")] }); + const d = decide(s); + assert.equal(pressedLabel(s, d), "Talk with Claude"); + assert.equal(d.why, "next to dictation"); + const ru = window({ send: "Отправить сообщение", buttons: [{ label: "Добавить файлы" }, { label: "Диктовать" }, voice("Поговорить с Claude")] }); + assert.equal(decide(ru).why, "next to dictation"); +}); + +test("an interface language we do not know at all presses nothing, least of all send", () => { + const s = window({ send: "Envoyer le message", buttons: [{ label: "Fichiers" }, { label: "Dicter" }, voice("Utiliser le mode X")] }); + assert.equal(decide(s).action, "none"); +}); + +test("dictation is never mistaken for voice mode", () => { + const s = window({ buttons: [attach, dictate] }); + assert.equal(decide(s).action, "none"); + const ru = window({ buttons: [attach, { label: "Голосовой ввод" }] }); + 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] }); + 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("send, stop and the message list's own buttons are never pressed", () => { + for (const label of ["Send message", "Stop response", "Отправить сообщение", "Остановить"]) { + const s = window({ send: label, buttons: [attach, dictate, { label }] }); + assert.equal(decide(s).action, "none", label); + } + const reading = window({ buttons: [attach, dictate] }); + assert.equal(decide(reading).action, "none", "Read aloud is not voice mode"); +}); + +test("voice already on is reported, not toggled off", () => { + const s = window({ buttons: [{ label: "Turn off microphone" }, { label: "End voice mode" }] }); + assert.equal(decide(s).action, "active"); + const ru = window({ buttons: [{ label: "Выключить микрофон" }] }); + assert.equal(decide(ru).action, "active"); +}); + +test("a label repeated as the title is read once", () => { + const s = window({ buttons: [attach, dictate, { label: "Use voice mode", title: "Use voice mode" }] }); + assert.equal(decide(s).label, "Use voice mode"); +}); + +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 voice mode label outside the composer is never pressed: a settings row or a help card is not the button", () => { + const s = window({ + buttons: [attach, { label: "Fichiers" }], + extra: [{ role: "AXButton", label: "Use voice mode", x: 50, y: 400, w: 30, h: 30 }], + }); + assert.equal(decide(s).action, "none"); + const modal = { nodes: [{ i: 0, parent: -1, role: "AXWebArea" }, { i: 1, parent: 0, role: "AXButton", label: "Голосовой режим", x: 600, y: 300, w: 200, h: 30 }], url: "https://claude.ai/new#settings" }; + assert.equal(decide(modal).action, "none"); +}); + +test("with a draft, an icon after dictation is never taken for voice: send can sit there under a label we do not know", () => { + const s = window({ draft: "half a thought", send: null, buttons: [attach, dictate, { label: "Submit" }] }); + const d = decide(s); + assert.equal(d.action, "none"); + assert.equal(d.reason, "draft"); +}); + +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] }); + 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, dictate, { ...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\)/); +}); + +test("on a chat without the button, the sidebar's New chat button is the way to a new chat", () => { + const s = window({ url: "https://claude.ai/chat/abc", link: false, buttons: [attach, dictate], extra: [{ role: "AXButton", title: "Создать", x: 355, y: 82, w: 268, h: 32 }] }); + const d = decide(s); + assert.equal(d.reason, "no-button"); + assert.equal(s.nodes[d.newChat as number].title, "Создать"); +}); + +test("on Claude Code's screen its Create button is not taken for a new chat", () => { + const s = window({ url: "https://claude.ai/epitaxy", link: false, buttons: [attach], extra: [{ role: "AXButton", title: "Создать", x: 447, y: 290, w: 268, h: 32 }] }); + const d = decide(s); + assert.equal(d.screen, "elsewhere"); + assert.equal(d.newChat, -1); +}); + +test("AX booleans are NSNumber bools: JXA's kCFBooleanTrue is refused, and Electron never publishes its page", () => { + const script = claudeAxScript(); + assert.doesNotMatch(script, /kCFBooleanTrue/); + assert.match(script, /AXManualAccessibility"\), YES\)/); +}); + +test("the flag is not set again while Electron builds the page: each set starts it over", () => { + assert.match(claudeAxScript(), /flagTakenAt < 0 \|\| now\(\) - flagTakenAt > 4000/); +}); + +test("a draft ends the attempt: the user's text is never left behind for a new chat", () => { + assert.match(claudeAxScript(), /if \(d\.reason === "draft"\) break;/); +}); + +test("the label is read again right before the press, and the whole script runs against one deadline", () => { + const script = claudeAxScript(); + assert.match(script, /labelOf\(el\) !== d\.label/); + assert.match(script, /var end = Math\.min\(now\(\) \+ ms, deadline\)/); + assert.match(script, /result: "timeout"/); +}); + +test("Claude is brought forward once while the page loads, not on every tick", () => { + const script = claudeAxScript(); + const wait = script.slice(script.indexOf("var web = waitFor("), script.indexOf("if (!web)")); + assert.doesNotMatch(wait, /front\(/); +}); diff --git a/server/voice-button/claude-ax.ts b/server/voice-button/claude-ax.ts new file mode 100644 index 0000000..256c406 --- /dev/null +++ b/server/voice-button/claude-ax.ts @@ -0,0 +1,516 @@ +// 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 NEW_CHAT = /^(new chat|start new chat|новый чат|создать|новий чат|створити)$/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; + +/** The label, title and help, each once: Chromium often repeats the aria-label as the title. */ +function textOf(n) { + var out = []; + [n.label, n.title, n.help].forEach(function (s) { + s = (s || "").trim(); + if (s && out.indexOf(s) < 0) out.push(s); + }); + return out.join(" "); +} + +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); + } + candidates.sort(function (x, y) { return y.score - x.score; }); + var best = candidates[0]; + // Only the composer's own buttons: a "voice mode" row in settings or a help card is not the button. + if (best && best.strong && best.inComposer) return { action: "press", index: best.node.i, label: best.text, why: "label" }; + if (best && best.weak && best.inComposer) { + return { action: "press", index: best.node.i, label: best.text, why: "voice word in the composer" }; + } + // No label we know (another interface language): voice mode sits right after the dictation button, + // in the same row of the composer, so take the icon there unless it is one of the known others. Only + // while the box is empty: with a draft, send can take that spot under a label we do not know. + var dictation = composer && empty ? near.filter(function (x) { return DICTATION.test(x.text); })[0] : null; + if (dictation) { + var row = dictation.node.y + dictation.node.h / 2; + var next = null; + for (var r = 0; r < near.length; r++) { + var o = near[r].node; + var gap = o.x - (dictation.node.x + dictation.node.w); + if (o === dictation.node || gap < -2 || gap > 40 || Math.abs(o.y + o.h / 2 - row) > 8) continue; + if (!next || o.x < next.node.x) next = near[r]; + } + if (next && !next.node.hasText && next.text && !DENY.test(next.text) && !DICTATION.test(next.text) && !ACTIVE.test(next.text)) { + return { action: "press", index: next.node.i, label: next.text, why: "next to dictation" }; + } + } + // A new chat: a link to /new, or on a chat screen the sidebar's "New chat" ("Создать" in Russian; + // on Claude Code's screen the same button starts a Code session, so only on a chat). + var links = nodes.filter(function (n) { + if (!n || n.w <= 0) return false; + if (n.role === "AXLink" && urlPath(n.url) === "/new") return true; + return n.role === "AXButton" && screenOf(snapshot.url) === "chat" && NEW_CHAT.test(textOf(n)); + }); + 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"); + +// JXA hands YES over as something AX refuses (kAXErrorFailure, -25200), so the flag that +// makes Electron publish its page was never set; an NSNumber bool is the CFBoolean AX expects. +var YES = $.NSNumber.numberWithBool(true); + +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 = Number(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 }; +} + +/** The claude.ai page: the desktop app's own shell is a file:// web area that holds it. */ +function findClaudeArea(root, depth) { + var queue = [[root, 0]]; + while (queue.length) { + var item = queue.shift(); + if (roleOf(item[0]) === "AXWebArea" && /^https:\/\/([a-z0-9-]+\.)*claude\.ai\//i.test(text(attr(item[0], "AXURL")))) return item[0]; + if (item[1] >= depth) continue; + var kids = attr(item[0], "AXChildren"); + if (kids === undefined) continue; + for (var k = 0; k < Number(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(); } + +/** Set by run(): the whole script answers before Paseo gives up on the button. */ +var deadline = Infinity; + +function left() { + return deadline - now(); +} + +function waitFor(fn, ms, step) { + var end = Math.min(now() + ms, deadline); + var got = fn(); + while (!got && now() < end) { + sleepMs(step || 150); + got = fn(); + } + return got; +} + +/** + * The window to work in. Claude Code opens windows of its own beside the chat window, so the window + * on a chat wins over the focused one, and is raised when it is not in front. + */ +function webAreaOf(app) { + var ws = attr(app, "AXWindows"); + if (ws === undefined || Number(ws.count) === 0) return null; + var focused = attr(app, "AXFocusedWindow"); + var best = null; + for (var w = 0; w < Number(ws.count); w++) { + var win = ws.objectAtIndex(w); + if (roleOf(win) !== "AXWindow") continue; + var area = findClaudeArea(win, 20); + if (!area) continue; + var kids = attr(area, "AXChildren"); + if (kids === undefined || Number(kids.count) === 0) continue; + var isFocused = focused !== undefined && $.CFEqual(focused, win); + var rank = (screenOf(areaUrl(area)) === "chat" ? 2 : 0) + (isFocused ? 1 : 0); + if (!best || rank > best.rank) best = { win: win, area: area, rank: rank, focused: isFocused }; + } + if (best && !best.focused) { + $.AXUIElementPerformAction(best.win, $("AXRaise")); + $.AXUIElementSetAttributeValue(best.win, $("AXMain"), YES); + } + return best; +} + +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" }; +} + +/** What a live element is called now, read the way the snapshot read it. */ +function labelOf(el) { + return textOf({ label: text(attr(el, "AXDescription")), title: text(attr(el, "AXTitle")), help: text(attr(el, "AXHelp")) }); +} + +function press(el) { + return $.AXUIElementPerformAction(el, $("AXPress")) === 0; +} + +var openBundle = ""; + +/** + * Brings this pid forward. AXFrontmost is ignored for a background caller and macOS may refuse an + * activation it did not see the user ask for; LaunchServices (\`open -b\`) is let through, so it is + * used as well whenever it cannot pick another instance (the caller passes the bundle id only then). + */ +function front(pid) { + var running = $.NSRunningApplication.runningApplicationWithProcessIdentifier(pid); + if (running && !running.isNil()) running.activateWithOptions(3); + if (openBundle && frontPid() !== pid) { + var sa = Application.currentApplication(); + sa.includeStandardAdditions = true; + try { sa.doShellScript("/usr/bin/open -b " + openBundle); } catch (e) {} + } +} + +function frontPid() { + var f = $.NSWorkspace.sharedWorkspace.frontmostApplication; + return f && !f.isNil() ? f.processIdentifier : -1; +} + +/** Escape, key code 53, down and up. */ +function pressEscape() { + ObjC.import("CoreGraphics"); + var down = $.CGEventCreateKeyboardEvent(null, 53, true); + $.CGEventPost(0, down); + delay(0.05); + var up = $.CGEventCreateKeyboardEvent(null, 53, false); + $.CGEventPost(0, up); +} + +function run(argv) { + var pid = parseInt(argv[0], 10); + var mayDeepLink = argv[1] === "deeplink"; + // The time this script has, all of it: Paseo stops waiting for a plugin after 30 s. + var budget = parseInt(argv[2] || "20000", 10); + deadline = now() + budget; + // "dry": find and report, press and navigate nothing (for checking a Mac by hand). + var dry = argv[3] === "dry"; + openBundle = /^[A-Za-z0-9.-]+$/.test(argv[4] || "") ? argv[4] : ""; + var steps = []; + var app = $.AXUIElementCreateApplication(pid); + // Electron builds the page's tree a second or two after AXManualAccessibility is set, and every new + // set starts that over: set every 300 ms, a freshly started Claude never showed its page in 25 s; set + // once, it did in about 2 s. So set it until Claude takes it (a Claude still starting answers -25204), + // then leave it alone, and set it again only if the page has not shown 4 s later. + // It does so for a Claude in the background too, so Claude is brought forward once here and again only + // right before a key or a press, never on every tick: the user may be working in another app. + var flagTakenAt = -1; + if (!dry) front(pid); + var web = waitFor(function () { + if (flagTakenAt < 0 || now() - flagTakenAt > 4000) { + if ($.AXUIElementSetAttributeValue(app, $("AXManualAccessibility"), YES) === 0) flagTakenAt = now(); + } + return webAreaOf(app); + }, budget, 300); + if (!web) return JSON.stringify({ result: "no-window", steps: steps }); + + // Ways out when the button is not there, tried in this order: Escape closes what covers the chat + // (settings, a menu, a dialog: Claude hides everything under a modal), then a new chat replaces a + // screen that is not a chat. A draft is the user's text: nothing is done about it, they are told. + var recoveries = ["escape", "new-chat"]; + var attempts = recoveries.length + 1; + for (var attempt = 0; attempt < attempts; attempt++) { + if (left() < 1500) return JSON.stringify({ result: "timeout", steps: steps }); + var seen = waitFor(function () { + var w = webAreaOf(app); + if (!w) return null; + web = w; + var l = look(app, w.area); + // A page that has just loaded shows its controls a moment later: give the button that moment. + return l.d.action === "none" && (attempt === 0 || l.d.reason === "no-composer") ? null : l; + }, attempt === 0 ? 2500 : 6000, 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(pid); + // React reuses elements: if the composer changed since the snapshot (a reply streaming in, + // dictation filling the box), the same element may be send or stop by now. + if (!el || labelOf(el) !== d.label) return JSON.stringify({ result: "press-failed", why: "changed", steps: steps }); + if (!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; + }, 6000, 300); + return JSON.stringify({ result: on ? "started" : "pressed", label: d.label, why: d.why, steps: steps }); + } + if (d.reason === "draft") break; + var recovered = false; + while (!recovered && recoveries.length) { + var next = recoveries.shift(); + if (next === "escape" && d.reason === "no-composer") { + // Keys go to the frontmost app, so only when that is this Claude. + front(pid); + sleepMs(200); + if (frontPid() === pid) { + pressEscape(); + steps.push({ navigate: "escape" }); + recovered = true; + } + } else if (next === "new-chat") { + if (d.newChat >= 0 && seen.snap.elements[d.newChat] && press(seen.snap.elements[d.newChat])) { + steps.push({ navigate: "new-chat-button" }); + recovered = true; + } else if (mayDeepLink) { + $.NSWorkspace.sharedWorkspace.openURL($.NSURL.URLWithString("claude://claude.ai/new")); + steps.push({ navigate: "deep-link" }); + recovered = true; + } + } + } + if (!recovered) break; + sleepMs(600); + front(pid); + } + return JSON.stringify({ result: "not-found", steps: steps }); +} +`; + +/** The whole JXA program; `osascript -l JavaScript -e