Skip to content

The agent that grows with you

feat(desktop): attach the frontmost window to the active draft

brooklyn!1b2da207839b
diff --git a/apps/desktop/README.md b/apps/desktop/README.md
index 997cb72846c..165cb36b1d8 100644
--- a/apps/desktop/README.md
+++ b/apps/desktop/README.md
@@ -48,9 +48,25 @@ hermes update
---
+## Screenshot shortcut (macOS)
+
+Enable **Settings → Keyboard Shortcuts → Screenshot shortcut**, then press the
+left and right Command keys together in any app. Hermes captures that app's
+frontmost window and attaches the image to the last-active Hermes composer,
+including split-pane chats. It does not send the draft or capture the whole
+screen. Release both keys before taking another screenshot.
+
+The shortcut is off by default and saved only on this Mac. macOS requires
+**Input Monitoring** and **Screen & System Audio Recording** permission; the
+settings row links to the relevant system pane and offers Retry. If macOS asks
+to restart the app after granting access, do so before retrying. Review the
+attachment before sending, especially when the captured window is sensitive.
+
## Requirements
The installer handles everything for you (Python 3.11+, a portable Git, ripgrep).
+macOS source builds also require Xcode Command Line Tools to compile the native
+shortcut helper. Prebuilt installers include it; no compiler is needed at runtime.
---
diff --git a/apps/desktop/electron/command-screenshot-capture.test.ts b/apps/desktop/electron/command-screenshot-capture.test.ts
new file mode 100644
index 00000000000..83d9b2750cd
--- /dev/null
+++ b/apps/desktop/electron/command-screenshot-capture.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { createScreenshotCapture } from './command-screenshot-capture'
+
+const window = { windowId: 42, width: 1200, height: 800 }
+const png = new Uint8Array([137, 80, 78, 71])
+
+function setup() {
+ const image = { isEmpty: () => false, toPNG: () => png }
+ const sources = vi.fn(async () => [{ id: 'window:42:0', thumbnail: image }])
+ const permission = vi.fn(() => true)
+ const capture = createScreenshotCapture({ getSources: sources, hasScreenPermission: permission })
+
+ return { capture, sources, permission }
+}
+
+describe('Command screenshot capture', () => {
+ it('binds a single-use gesture to its original renderer and exact window, never another screen', async () => {
+ const { capture, sources } = setup()
+ const request = capture.request(7, window)!
+
+ expect(await capture.take(8, request)).toEqual({ ok: false, reason: 'expired' })
+ expect(sources).not.toHaveBeenCalled()
+ expect(await capture.take(7, request)).toEqual({ ok: true, png })
+ expect(sources).toHaveBeenCalledWith({ types: ['window'], thumbnailSize: { width: 2400, height: 1600 }, fetchWindowIcons: false })
+ expect(await capture.take(7, request)).toEqual({ ok: false, reason: 'expired' })
+
+ sources.mockResolvedValue([{ id: 'window:99:0', thumbnail: { isEmpty: () => false, toPNG: () => png } }])
+ expect(await capture.take(7, capture.request(7, window)!)).toEqual({ ok: false, reason: 'unavailable' })
+ })
+
+ it('drops denied, expired, concurrent and disabled captures without leaking a late image', async () => {
+ const { capture, sources, permission } = setup()
+ permission.mockReturnValue(false)
+ expect(await capture.take(7, capture.request(7, window)!)).toEqual({ ok: false, reason: 'screen-permission' })
+ expect(sources).not.toHaveBeenCalled()
+ permission.mockReturnValue(true)
+
+ vi.useFakeTimers()
+ try {
+ const expired = capture.request(7, window)!
+ vi.advanceTimersByTime(6000)
+ expect(await capture.take(7, expired)).toEqual({ ok: false, reason: 'expired' })
+ } finally {
+ vi.useRealTimers()
+ }
+
+ let finish!: (value: Awaited<ReturnType<typeof sources>>) => void
+ sources.mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const pending = capture.take(7, capture.request(7, window)!)
+ expect(capture.request(7, window)).toBeNull()
+ capture.clear()
+ finish([{ id: 'window:42:0', thumbnail: { isEmpty: () => false, toPNG: () => png } }])
+ expect(await pending).toEqual({ ok: false, reason: 'expired' })
+ })
+})
diff --git a/apps/desktop/electron/command-screenshot-capture.ts b/apps/desktop/electron/command-screenshot-capture.ts
new file mode 100644
index 00000000000..0d108ad48d7
--- /dev/null
+++ b/apps/desktop/electron/command-screenshot-capture.ts
@@ -0,0 +1,89 @@
+import { randomUUID } from 'node:crypto'
+
+import type { ScreenshotResult, ScreenshotWindow } from './command-screenshot-types'
+
+interface ScreenshotSource {
+ id: string
+ thumbnail: { isEmpty(): boolean; toPNG(): Uint8Array }
+}
+
+interface CaptureDependencies {
+ hasScreenPermission(): boolean
+ getSources(options: {
+ types: ['window']
+ thumbnailSize: { width: number; height: number }
+ fetchWindowIcons: false
+ }): Promise<ScreenshotSource[]>
+}
+
+/** A physical gesture grants one renderer one capture, not an arbitrary capture IPC. */
+export function createScreenshotCapture({ getSources, hasScreenPermission }: CaptureDependencies) {
+ let pending: { id: string; owner: number; window: ScreenshotWindow; expires: number } | null = null
+ let generation = 0
+ let busy = false
+
+ return {
+ request(owner: number, window: ScreenshotWindow): string | null {
+ if (busy || (pending && pending.expires > Date.now())) {
+ return null
+ }
+
+ const id = randomUUID()
+ pending = { id, owner, window, expires: Date.now() + 5000 }
+
+ return id
+ },
+ clear() {
+ generation += 1
+ pending = null
+ },
+ async take(owner: number, id: unknown): Promise<ScreenshotResult> {
+ if (!pending || pending.id !== id || pending.owner !== owner) {
+ return { ok: false, reason: 'expired' }
+ }
+
+ if (pending.expires <= Date.now()) {
+ pending = null
+
+ return { ok: false, reason: 'expired' }
+ }
+
+ const { window } = pending
+ pending = null
+
+ if (!hasScreenPermission()) {
+ return { ok: false, reason: 'screen-permission' }
+ }
+
+ const capturedGeneration = generation
+ busy = true
+
+ try {
+ // Retina detail, bounded for very large windows. No display fallback:
+ // sharing the desktop would expose content the gesture did not select.
+ const scale = Math.min(2, 4096 / Math.max(window.width, window.height))
+ const sources = await getSources({
+ types: ['window'],
+ thumbnailSize: { width: Math.ceil(window.width * scale), height: Math.ceil(window.height * scale) },
+ fetchWindowIcons: false
+ })
+
+ if (capturedGeneration !== generation) {
+ return { ok: false, reason: 'expired' }
+ }
+
+ const source = sources.find(item => item.id.split(':')[0] === 'window' && item.id.split(':')[1] === String(window.windowId))
+
+ if (!source || source.thumbnail.isEmpty()) {
+ return { ok: false, reason: 'unavailable' }
+ }
+
+ return { ok: true, png: source.thumbnail.toPNG() }
+ } catch {
+ return { ok: false, reason: hasScreenPermission() ? 'unavailable' : 'screen-permission' }
+ } finally {
+ busy = false
+ }
+ }
+ }
+}
diff --git a/apps/desktop/electron/command-screenshot.test.ts b/apps/desktop/electron/command-screenshot.test.ts
new file mode 100644
index 00000000000..06245a2348d
--- /dev/null
+++ b/apps/desktop/electron/command-screenshot.test.ts
@@ -0,0 +1,109 @@
+import { EventEmitter } from 'node:events'
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const native = vi.hoisted(() => ({ start: vi.fn(), stop: vi.fn() }))
+const electron = vi.hoisted(() => ({ handlers: new Map(), windows: [] as any[], focused: null as any, screenPermission: 'granted', directory: '' }))
+vi.mock('./command-screenshot-monitor', () => ({ CommandScreenshotMonitor: class { start = native.start; stop = native.stop } }))
+vi.mock('electron', async () => {
+ const { EventEmitter } = await import('node:events')
+ const ipcMain = new EventEmitter() as any
+ ipcMain.handle = (channel: string, handler: unknown) => electron.handlers.set(channel, handler)
+ ipcMain.removeHandler = (channel: string) => electron.handlers.delete(channel)
+
+ return {
+ app: Object.assign(new EventEmitter(), { getPath: () => electron.directory, getAppPath: () => '/app' }),
+ ipcMain,
+ BrowserWindow: {
+ fromWebContents: (wc: unknown) => electron.windows.find(win => win.webContents === wc),
+ getFocusedWindow: () => electron.focused,
+ getAllWindows: () => electron.windows
+ },
+ desktopCapturer: { getSources: vi.fn(async () => [{ id: 'window:42:0', thumbnail: { isEmpty: () => false, toPNG: () => new Uint8Array([1]) } }]) },
+ systemPreferences: { getMediaAccessStatus: () => electron.screenPermission },
+ shell: { openExternal: vi.fn() }
+ }
+})
+
+import { app, desktopCapturer, ipcMain } from 'electron'
+
+import { installCommandScreenshot } from './command-screenshot'
+
+const cleanups: (() => void)[] = []
+afterEach(async () => {
+ cleanups.splice(0).forEach(fn => fn())
+ await rm(electron.directory, { recursive: true, force: true })
+ electron.windows = []
+ electron.focused = null
+ electron.screenPermission = 'granted'
+ vi.clearAllMocks()
+})
+
+function window(id: number, url = 'http://127.0.0.1:5174/') {
+ const frame = { url }
+ const wc = Object.assign(new EventEmitter(), { id, mainFrame: frame, getURL: () => url, isDestroyed: () => false, send: vi.fn() })
+ const win = { webContents: wc, isDestroyed: () => false }
+ electron.windows.push(win)
+
+ return { win, event: { sender: wc, senderFrame: frame }, wc }
+}
+
+async function setup() {
+ electron.directory = await mkdtemp(path.join(os.tmpdir(), 'hermes-screenshot-'))
+ cleanups.push(installCommandScreenshot({ rendererUrl: 'http://127.0.0.1:5174/' }))
+}
+
+const call = (channel: string, event: unknown, ...args: unknown[]) => electron.handlers.get(`hermes:screenshot:${channel}`)(event, ...args)
+
+describe.skipIf(process.platform !== 'darwin')('Command screenshot native bridge', () => {
+ it('persists opt-in, routes to the last focused subscribed window while backgrounded, and revokes on disable', async () => {
+ await setup()
+ const first = window(1)
+ const second = window(2)
+ expect(await call('settings:get', first.event)).toEqual({ enabled: false, state: 'disabled' })
+ expect(native.start).not.toHaveBeenCalled()
+ ipcMain.emit('subscribe', first.event) // unrelated IPC grants nothing
+ ipcMain.emit('hermes:screenshot:subscribe', first.event, true)
+ ipcMain.emit('hermes:screenshot:subscribe', second.event, true)
+ app.emit('browser-window-focus', {}, second.win)
+ electron.focused = null
+ await call('settings:set', first.event, true)
+ expect(JSON.parse(await readFile(path.join(electron.directory, 'screenshot.json'), 'utf8'))).toEqual({ enabled: true })
+ const [capture, status] = native.start.mock.calls.at(-1)!
+ status({ type: 'ready' })
+ capture({ type: 'capture', windowId: 42, width: 600, height: 400 })
+ const requests = second.wc.send.mock.calls.filter(([channel]) => channel === 'hermes:screenshot:request')
+ expect(requests).toHaveLength(1)
+ expect(first.wc.send.mock.calls.some(([channel]) => channel === 'hermes:screenshot:request')).toBe(false)
+ expect(await call('capture', first.event, requests[0]![1])).toEqual({ ok: false, reason: 'expired' })
+ await call('settings:set', second.event, false)
+ expect(await call('capture', second.event, requests[0]![1])).toEqual({ ok: false, reason: 'expired' })
+ expect(native.stop).toHaveBeenCalled()
+ for (let i = 0; i < 3; i += 1) {
+ ipcMain.emit('hermes:screenshot:subscribe', second.event, false)
+ ipcMain.emit('hermes:screenshot:subscribe', second.event, true)
+ }
+ expect(second.wc.listenerCount('destroyed')).toBe(1)
+ ipcMain.emit('hermes:screenshot:subscribe', second.event, false)
+ expect(second.wc.listenerCount('destroyed')).toBe(0)
+ })
+
+ it('rejects guest/foreign frames and reports denied screen access rather than ready', async () => {
+ await setup()
+ const trusted = window(3)
+ const foreign = window(4, 'https://example.org/')
+ await expect(call('settings:set', foreign.event, true)).rejects.toThrow()
+ await expect(call('settings:set', { ...trusted.event, senderFrame: { url: 'https://example.org/' } }, true)).rejects.toThrow()
+ expect(native.start).not.toHaveBeenCalled()
+ electron.screenPermission = 'denied'
+ await call('settings:set', trusted.event, true)
+ native.start.mock.calls.at(-1)![1]({ type: 'ready' })
+ expect(desktopCapturer.getSources).toHaveBeenCalledWith({
+ types: ['window'], thumbnailSize: { width: 1, height: 1 }, fetchWindowIcons: false
+ })
+ expect(await call('settings:get', trusted.event)).toEqual({ enabled: true, state: 'screen-permission' })
+ })
+})
diff --git a/apps/desktop/electron/command-screenshot.ts b/apps/desktop/electron/command-screenshot.ts
new file mode 100644
index 00000000000..788a29922e4
--- /dev/null
+++ b/apps/desktop/electron/command-screenshot.ts
@@ -0,0 +1,216 @@
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import path from 'node:path'
+
+import { app, BrowserWindow, desktopCapturer, ipcMain, shell, systemPreferences } from 'electron'
+import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron'
+
+import { createScreenshotCapture } from './command-screenshot-capture'
+import { CommandScreenshotMonitor } from './command-screenshot-monitor'
+import type { ScreenshotStatus } from './command-screenshot-types'
+
+/** Device-local, opt-in native gesture. No renderer can request an arbitrary screenshot. */
+export function installCommandScreenshot({ rendererUrl }: { rendererUrl: string }): () => void {
+ if (process.platform !== 'darwin') {
+ return () => undefined
+ }
+
+ const configPath = path.join(app.getPath('userData'), 'screenshot.json')
+ const expectedUrl = new URL(rendererUrl)
+ const monitor = new CommandScreenshotMonitor({ appPath: app.getAppPath() })
+ const hasScreenPermission = () => systemPreferences.getMediaAccessStatus('screen') === 'granted'
+ const capture = createScreenshotCapture({ hasScreenPermission, getSources: options => desktopCapturer.getSources(options) })
+ const recipients = new Map<number, () => void>()
+ let lastRecipient: BrowserWindow | null = null
+ let enabled = false
+ let monitorState: ScreenshotStatus['state'] = 'disabled'
+ let disposed = false
+ let generation = 0
+
+ try {
+ enabled = JSON.parse(readFileSync(configPath, 'utf8')).enabled === true
+ } catch {
+ // Missing or malformed device preference must never opt the user in.
+ }
+
+ const status = (): ScreenshotStatus => ({
+ enabled,
+ state: !enabled ? 'disabled' : monitorState === 'ready' && !hasScreenPermission() ? 'screen-permission' : monitorState
+ })
+
+ const trustedWindow = (event: IpcMainEvent | IpcMainInvokeEvent): BrowserWindow | null => {
+ const win = BrowserWindow.fromWebContents(event.sender)
+
+ if (!win || win.isDestroyed() || event.senderFrame !== event.sender.mainFrame) {
+ return null
+ }
+
+ try {
+ const url = new URL(event.senderFrame.url)
+
+ return url.protocol === expectedUrl.protocol && url.host === expectedUrl.host && url.pathname === expectedUrl.pathname ? win : null
+ } catch {
+ return null
+ }
+ }
+
+ const publish = () => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ win.webContents.send('hermes:screenshot:status', status())
+ }
+ }
+ }
+
+ const start = (requestPermission = false) => {
+ const current = ++generation
+ monitor.start(window => {
+ if (disposed || !enabled || current !== generation) {
+ return
+ }
+
+ // Retain the last Hermes chat window when another application takes focus.
+ // Closing it cancels this destination; never silently pick another chat.
+ const focused = BrowserWindow.getFocusedWindow()
+ const recipient = focused && recipients.has(focused.webContents.id) ? focused : lastRecipient
+
+ if (!recipient || recipient.isDestroyed() || !recipients.has(recipient.webContents.id)) {
+ return
+ }
+
+ const requestId = capture.request(recipient.webContents.id, window)
+
+ if (requestId) {
+ recipient.webContents.send('hermes:screenshot:request', requestId)
+ }
+ }, result => {
+ if (disposed || current !== generation) {
+ return
+ }
+
+ monitorState = result.type === 'error'
+ ? result.code === 'permission-required' ? 'input-permission' : 'unavailable'
+ : result.type === 'stopped' ? 'disabled' : result.type
+ publish()
+ }, requestPermission)
+ }
+
+ const onFocus = (_event: unknown, win: BrowserWindow) => {
+ if (recipients.has(win.webContents.id)) {
+ lastRecipient = win
+ }
+ }
+
+ const onSubscribe = (event: IpcMainEvent, subscribed: unknown) => {
+ const win = trustedWindow(event)
+
+ if (!win) {
+ return
+ }
+
+ if (subscribed === true) {
+ if (!recipients.has(event.sender.id)) {
+ const id = event.sender.id
+ const onDestroyed = () => {
+ recipients.delete(id)
+ if (lastRecipient === win) {
+ lastRecipient = null
+ }
+ }
+ event.sender.once('destroyed', onDestroyed)
+ recipients.set(id, () => event.sender.removeListener('destroyed', onDestroyed))
+ }
+
+ if (!lastRecipient || BrowserWindow.getFocusedWindow() === win) {
+ lastRecipient = win
+ }
+ } else if (subscribed === false) {
+ recipients.get(event.sender.id)?.()
+ recipients.delete(event.sender.id)
+ if (lastRecipient === win) {
+ lastRecipient = null
+ }
+ }
+ }
+
+ const channels: string[] = []
+ const handle = (name: string, callback: (event: IpcMainInvokeEvent, value: unknown) => unknown) => {
+ const channel = `hermes:screenshot:${name}`
+ channels.push(channel)
+ ipcMain.handle(channel, async (event, value) => {
+ if (!trustedWindow(event)) {
+ throw new Error('Screenshot request from an untrusted frame')
+ }
+
+ return callback(event, value)
+ })
+ }
+
+ handle('settings:get', () => status())
+ handle('settings:set', async (_event, value) => {
+ if (typeof value !== 'boolean') {
+ throw new Error('Screenshot setting must be a boolean')
+ }
+
+ // Persist first: a failed authoritative write must not leave a live monitor.
+ mkdirSync(path.dirname(configPath), { recursive: true })
+ writeFileSync(`${configPath}.tmp`, JSON.stringify({ enabled: value }), { mode: 0o600 })
+ renameSync(`${configPath}.tmp`, configPath)
+ enabled = value
+ generation += 1
+ capture.clear()
+ monitor.stop()
+
+ if (enabled) {
+ start(true)
+ if (!hasScreenPermission()) {
+ // Zero-size thumbnails skip content capture and may never request TCC
+ // consent. Request the smallest thumbnail only on explicit opt-in;
+ // discard it rather than retaining or attaching permission-probe pixels.
+ await desktopCapturer.getSources({ types: ['window'], thumbnailSize: { width: 1, height: 1 }, fetchWindowIcons: false }).catch(() => undefined)
+ }
+ } else {
+ monitorState = 'disabled'
+ }
+
+ publish()
+
+ return status()
+ })
+ handle('capture', async (event, requestId) => {
+ const result = await capture.take(event.sender.id, requestId)
+ if (!result.ok && result.reason === 'screen-permission') {
+ publish()
+ }
+
+ return result
+ })
+ handle('permission', async (_event, kind) => {
+ const pane = kind === 'input' ? 'Privacy_ListenEvent' : kind === 'screen' ? 'Privacy_ScreenCapture' : null
+ if (!pane) {
+ throw new Error('Unknown screenshot permission')
+ }
+ await shell.openExternal(`x-apple.systempreferences:com.apple.preference.security?${pane}`)
+ })
+ ipcMain.on('hermes:screenshot:subscribe', onSubscribe)
+ app.on('browser-window-focus', onFocus)
+
+ const dispose = () => {
+ disposed = true
+ capture.clear()
+ monitor.stop()
+ recipients.forEach(unsubscribe => unsubscribe())
+ recipients.clear()
+ lastRecipient = null
+ channels.forEach(channel => ipcMain.removeHandler(channel))
+ ipcMain.removeListener('hermes:screenshot:subscribe', onSubscribe)
+ app.removeListener('browser-window-focus', onFocus)
+ app.removeListener('will-quit', dispose)
+ }
+
+ app.once('will-quit', dispose)
+ if (enabled) {
+ start()
+ }
+
+ return dispose
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 4b9aa813cd8..b0d26919533 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -94,6 +94,7 @@ import {
import { detectBundleSkew } from './bundle-skew'
import { detectBundleSwap } from './bundle-swap'
import { registerChatOnboardingWindow } from './chat-onboarding-window'
+import { installCommandScreenshot } from './command-screenshot'
import { writeComposerPaste } from './composer-paste'
import { applyConnectionChange, teardownSshState } from './connection-apply'
import {
@@ -18303,6 +18304,7 @@ app.whenReady().then(() => {
// it without the renderer visiting Settings. A failed registration is logged
// here and surfaced in Settings via the IPC state (never silent).
applyQuickEntrySettings(readQuickEntrySettings())
+ installCommandScreenshot({ rendererUrl: DEV_SERVER || pathToFileURL(resolveRendererIndex()).toString() })
if (IS_MAC) {
const reposition = () => wakeIndicatorController.reposition()
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 5e53c06a544..f30f203b8e1 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -174,6 +174,34 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
return () => ipcRenderer.removeListener('hermes:hud:game-overlay', listener)
}
},
+ // macOS native screenshot gesture; captures require a main-issued request.
+ screenshot: process.platform === 'darwin' ? {
+ getSettings: () => ipcRenderer.invoke('hermes:screenshot:settings:get'),
+ setEnabled: enabled => ipcRenderer.invoke('hermes:screenshot:settings:set', enabled),
+ openPermissionSettings: kind => ipcRenderer.invoke('hermes:screenshot:permission', kind),
+ capture: requestId => ipcRenderer.invoke('hermes:screenshot:capture', requestId),
+ onStatus: callback => {
+ const listener = (_event, status) => callback(status)
+ ipcRenderer.on('hermes:screenshot:status', listener)
+
+ return () => ipcRenderer.removeListener('hermes:screenshot:status', listener)
+ },
+ onRequest: callback => {
+ const channel = 'hermes:screenshot:request'
+ const listener = (_event, requestId) => callback(requestId)
+ if (ipcRenderer.listenerCount(channel) === 0) {
+ ipcRenderer.send('hermes:screenshot:subscribe', true)
+ }
+ ipcRenderer.on(channel, listener)
+
+ return () => {
+ ipcRenderer.removeListener(channel, listener)
+ if (ipcRenderer.listenerCount(channel) === 0) {
+ ipcRenderer.send('hermes:screenshot:subscribe', false)
+ }
+ }
+ }
+ } : undefined,
// Quick Entry: the global-hotkey mini composer window. Main owns the OS
// shortcut + the persisted preference; the quick window only captures text
// and hands it back, and the primary renderer submits it through the normal
diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.ts
index 1f596e423b2..274fea5be34 100644
--- a/apps/desktop/src/app/chat/composer/focus.ts
+++ b/apps/desktop/src/app/chat/composer/focus.ts
@@ -178,7 +178,7 @@ const dispatchNow = <T>(name: string, detail: T) => {
}
/** Unique identity for the visible composer surface addressed by a submit. */
-const getVisibleComposerSurfaceId = (target: ComposerTarget): string | null => {
+export const getVisibleComposerSurfaceId = (target: ComposerTarget): string | null => {
if (typeof document === 'undefined') {
return null
}
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsx
new file mode 100644
index 00000000000..bd3db8f0ae8
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsx
@@ -0,0 +1,85 @@
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import type { PropsWithChildren } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { I18nProvider } from '@/i18n'
+import { createComposerAttachmentScope } from '@/store/composer'
+
+import type { ScreenshotApi } from '../../../../../electron/command-screenshot-types'
+import { markActiveComposer } from '../focus'
+import { ComposerScopeProvider, ComposerSurfaceProvider, MAIN_COMPOSER_SCOPE } from '../scope'
+
+import { useComposerScreenshot } from './use-composer-screenshot'
+
+const listeners = new Set<(id: string) => void>()
+const capture = vi.fn<ScreenshotApi['capture']>()
+const onAttach = vi.fn(async (_blob: Blob, isCurrent?: () => boolean) => isCurrent?.() ?? true)
+
+function mount(target: string, surfaceId: string, key = 'draft-a') {
+ const scope = { ...MAIN_COMPOSER_SCOPE, target, attachments: createComposerAttachmentScope() }
+ const Wrapper = ({ children }: PropsWithChildren) => (
+ <I18nProvider configClient={null}>
+ <ComposerScopeProvider value={scope}>
+ <ComposerSurfaceProvider value={surfaceId}>
+ <div data-composer-surface-id={surfaceId} data-composer-target={target}>{children}</div>
+ </ComposerSurfaceProvider>
+ </ComposerScopeProvider>
+ </I18nProvider>
+ )
+
+ return renderHook(({ sessionKey }) => useComposerScreenshot({ sessionKey, onAttachImageBlob: onAttach }), {
+ initialProps: { sessionKey: key }, wrapper: Wrapper
+ })
+}
+
+function bridge() {
+ window.hermesDesktop = { ...window.hermesDesktop, screenshot: {
+ getSettings: vi.fn(), setEnabled: vi.fn(), openPermissionSettings: vi.fn(), onStatus: () => () => undefined,
+ capture,
+ onRequest: callback => { listeners.add(callback); return () => listeners.delete(callback) }
+ } as ScreenshotApi }
+}
+
+afterEach(() => {
+ cleanup()
+ listeners.clear()
+ vi.clearAllMocks()
+ delete window.hermesDesktop.screenshot
+ markActiveComposer('main')
+})
+
+describe('screenshot composer routing', () => {
+ it('attaches once to the active split composer even without document focus, preserving its draft', async () => {
+ bridge()
+ capture.mockResolvedValue({ ok: true, png: new Uint8Array([1, 2, 3]) })
+ mount('main', 'primary')
+ mount('tile:second', 'second')
+ markActiveComposer('tile:second')
+ expect(document.hasFocus()).toBe(false)
+ act(() => listeners.forEach(listener => listener('gesture')))
+ await waitFor(() => expect(onAttach).toHaveBeenCalledTimes(1))
+ expect(capture).toHaveBeenCalledExactlyOnceWith('gesture')
+ expect(onAttach.mock.calls[0]![0].type).toBe('image/png')
+ })
+
+ it('rejects a late screenshot after a draft round trip and invalidates the image-write continuation', async () => {
+ bridge()
+ let finish!: (value: Awaited<ReturnType<ScreenshotApi['capture']>>) => void
+ capture.mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const hook = mount('main', 'primary')
+ act(() => listeners.forEach(listener => listener('first')))
+ hook.rerender({ sessionKey: 'draft-b' })
+ hook.rerender({ sessionKey: 'draft-a' })
+ await act(async () => finish({ ok: true, png: new Uint8Array([1]) }))
+ expect(onAttach).not.toHaveBeenCalled()
+
+ capture.mockResolvedValue({ ok: true, png: new Uint8Array([1]) })
+ let isCurrent!: () => boolean
+ onAttach.mockImplementation(async (_blob, guard) => { isCurrent = guard!; return true })
+ act(() => listeners.forEach(listener => listener('second')))
+ await waitFor(() => expect(onAttach).toHaveBeenCalledOnce())
+ expect(isCurrent()).toBe(true)
+ hook.rerender({ sessionKey: 'draft-b' })
+ expect(isCurrent()).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.ts
new file mode 100644
index 00000000000..b1fd9ff4c79
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.ts
@@ -0,0 +1,93 @@
+import { useLayoutEffect, useRef } from 'react'
+
+import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
+import { useI18n } from '@/i18n'
+import { $activeGatewayRoute } from '@/store/gateway'
+import { notify } from '@/store/notifications'
+
+import { getActiveComposer, getVisibleComposerSurfaceId } from '../focus'
+import { useComposerScope, useComposerSurfaceId } from '../scope'
+import type { ChatBarProps } from '../types'
+
+interface ScreenshotComposerOptions {
+ sessionKey: string | null
+ focusKey?: string | null
+ onAttachImageBlob: ChatBarProps['onAttachImageBlob']
+}
+
+/** Capture into the exact draft that owned the gesture, even when the OS focus is elsewhere. */
+export function useComposerScreenshot({ sessionKey, focusKey, onAttachImageBlob }: ScreenshotComposerOptions) {
+ const scope = useComposerScope()
+ const surfaceId = useComposerSurfaceId()
+ const visible = usePaneVisible()
+ const { t } = useI18n()
+ const latest = useRef({ onAttachImageBlob, copy: t.settings.screenshot })
+ latest.current = { onAttachImageBlob, copy: t.settings.screenshot }
+
+ useLayoutEffect(() => {
+ const api = window.hermesDesktop?.screenshot
+ if (!api || !surfaceId || !visible) {
+ return
+ }
+
+ let generation = 0
+ let mounted = true
+ let busy = false
+ const offRoute = $activeGatewayRoute.listen(() => {
+ generation += 1
+ })
+ const offStatus = api.onStatus(status => {
+ if (!status.enabled) {
+ generation += 1
+ }
+ })
+ const offRequest = api.onRequest(requestId => {
+ if (busy || getActiveComposer() !== scope.target || getVisibleComposerSurfaceId(scope.target) !== surfaceId) {
+ return
+ }
+ const attach = latest.current.onAttachImageBlob
+ if (!attach) {
+ return
+ }
+
+ const capturedGeneration = generation
+ const isCurrent = () => mounted && capturedGeneration === generation
+ const report = (message: string) => notify({ kind: 'error', title: latest.current.copy.enabledTitle, message })
+ busy = true
+
+ void (async () => {
+ try {
+ const result = await api.capture(requestId)
+ if (!isCurrent()) {
+ report(latest.current.copy.contextChanged)
+ return
+ }
+
+ if (!result.ok) {
+ report(latest.current.copy.captureFailed)
+ return
+ }
+
+ // Reuse paste/image ingestion. Its final guard runs AFTER saving the
+ // native bytes, before adding a chip, so a session swap cannot leak it.
+ const blob = new Blob([new Uint8Array(result.png)], { type: 'image/png' })
+ await attach(blob, isCurrent)
+ if (!isCurrent()) {
+ report(latest.current.copy.contextChanged)
+ }
+ } catch {
+ report(latest.current.copy.captureFailed)
+ } finally {
+ busy = false
+ }
+ })()
+ })
+
+ return () => {
+ mounted = false
+ offRoute()
+ offStatus()
+ offRequest()
+ }
+ }, [sessionKey, focusKey, visible, scope.target, surfaceId])
+}
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index cb0a16cb379..b5fd4776f36 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -58,6 +58,7 @@ import { useComposerMetrics } from './hooks/use-composer-metrics'
import { useComposerPlaceholder } from './hooks/use-composer-placeholder'
import { useComposerPopout } from './hooks/use-composer-popout'
import { useComposerQueue } from './hooks/use-composer-queue'
+import { useComposerScreenshot } from './hooks/use-composer-screenshot'
import { useComposerSubmit } from './hooks/use-composer-submit'
import { triggerKeyUpHandler, useComposerTrigger } from './hooks/use-composer-trigger'
import { useComposerUndo } from './hooks/use-composer-undo'
@@ -272,6 +273,8 @@ export function ChatBar({
syncDraftFromEditor
} = useComposerDraft({ activeQueueSessionKey, focusKey, inputDisabled, queueEditRef, sessionId })
+ useComposerScreenshot({ sessionKey: activeQueueSessionKey, focusKey, onAttachImageBlob })
+
// Undo/redo. The rich editor bypasses Chromium's editing pipeline for speed,
// which also bypasses its undo stack — so we own the stack and every edit
// path below banks its pre-edit state through `recordUndoPoint`.
diff --git a/apps/desktop/src/app/chat/composer/types.ts b/apps/desktop/src/app/chat/composer/types.ts
index 40f4400af42..c43c6b460bf 100644
--- a/apps/desktop/src/app/chat/composer/types.ts
+++ b/apps/desktop/src/app/chat/composer/types.ts
@@ -49,7 +49,7 @@ export interface ChatBarProps {
onCancel: () => Promise<void> | void
onAddContextRef?: (refText: string, label?: string, detail?: string) => void
onAddUrl?: (url: string) => void
- onAttachImageBlob?: (blob: Blob) => Promise<boolean | void> | boolean | void
+ onAttachImageBlob?: (blob: Blob, isCurrent?: () => boolean) => Promise<boolean | void> | boolean | void
onAttachDroppedItems?: (candidates: DroppedFile[]) => Promise<boolean | void> | boolean | void
/** Pasted GitHub PR-comment deep link → structured review attachment.
* Returns true when the paste was consumed as an attachment. */
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
index f34d041df01..270d48f444e 100644
--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
@@ -297,6 +297,26 @@ describe('useComposerActions native image drops', () => {
vi.clearAllMocks()
})
+ it('does not attach a screenshot when its draft changes during native image saving', async () => {
+ let finishSave!: (path: string) => void
+ const saveImageBuffer = vi.fn(() => new Promise<string>(resolve => { finishSave = resolve }))
+ const add = vi.fn()
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { saveImageBuffer } })
+ const { result } = renderHook(() => useComposerActions({
+ activeSessionId: null,
+ currentCwd: '/test',
+ requestGateway: vi.fn(),
+ scope: { add, remove: vi.fn(() => null), target: 'main', update: vi.fn(() => true), updateIfCurrent: vi.fn(() => true) }
+ }))
+ let current = true
+ const pending = result.current.attachImageBlob(new Blob([new Uint8Array([1])], { type: 'image/png' }), () => current)
+ await vi.waitFor(() => expect(saveImageBuffer).toHaveBeenCalledOnce())
+ current = false
+ finishSave('/test/screenshot.png')
+ expect(await pending).toBe(false)
+ expect(add).not.toHaveBeenCalled()
+ })
+
it('copies dropped screenshot bytes before trusting a transient macOS path', async () => {
const transientPath =
'/var/folders/x7/example/T/TemporaryItems/NSIRD_screencaptureui_4roSuW/Screen Shot 2026-08-11.png'
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
index 157c2082eaf..fb5ac54263c 100644
--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
@@ -552,8 +552,8 @@ export function useComposerActions({
)
const attachImageBlob = useCallback(
- async (blob: Blob) => {
- if (blob.size === 0) {
+ async (blob: Blob, isCurrent: () => boolean = () => true) => {
+ if (blob.size === 0 || !isCurrent()) {
return false
}
@@ -563,6 +563,11 @@ export function useComposerActions({
try {
const buffer = await blob.arrayBuffer()
+
+ if (!isCurrent()) {
+ return false
+ }
+
const data = new Uint8Array(buffer)
const name = blob instanceof File ? blob.name : undefined
const savedPath = await window.hermesDesktop?.saveImageBuffer(data, blobExtension(blob), name)
@@ -573,7 +578,7 @@ export function useComposerActions({
return false
}
- return attachImagePath(savedPath)
+ return isCurrent() ? attachImagePath(savedPath) : false
} catch (err) {
notifyError(err, copy.imageAttachFailed)
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx
index 704fd00f93a..768537b82e1 100644
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@ -96,7 +96,7 @@ interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
onAddUrl: (url: string) => void
onBranchInNewChat?: (messageId: string) => void
maxVoiceRecordingSeconds?: number
- onAttachImageBlob: (blob: Blob) => Promise<boolean | void> | boolean | void
+ onAttachImageBlob: (blob: Blob, isCurrent?: () => boolean) => Promise<boolean | void> | boolean | void
onAttachDroppedItems: (candidates: DroppedFile[]) => Promise<boolean | void> | boolean | void
onAttachPrCommentUrl?: (url: string) => boolean
onAttachPastedText?: (text: string) => Promise<boolean> | boolean
diff --git a/apps/desktop/src/app/settings/keybind-settings.tsx b/apps/desktop/src/app/settings/keybind-settings.tsx
index b65a9ecfff3..91e91a62aed 100644
--- a/apps/desktop/src/app/settings/keybind-settings.tsx
+++ b/apps/desktop/src/app/settings/keybind-settings.tsx
@@ -31,6 +31,7 @@ import {
} from '@/store/keybinds'
import { SettingsContent } from './primitives'
+import { ScreenshotSettings } from './screenshot-settings'
export function KeybindSettings() {
const { t } = useI18n()
@@ -114,6 +115,10 @@ export function KeybindSettings() {
</button>
</div>
+ {(!isSearching || t.settings.screenshot.enabledTitle.toLowerCase().includes(query.toLowerCase())) && (
+ <ScreenshotSettings />
+ )}
+
<div className="pb-3">
<SearchField
aria-label={k.search}
diff --git a/apps/desktop/src/app/settings/screenshot-settings.test.tsx b/apps/desktop/src/app/settings/screenshot-settings.test.tsx
new file mode 100644
index 00000000000..e713d79aeb4
--- /dev/null
+++ b/apps/desktop/src/app/settings/screenshot-settings.test.tsx
@@ -0,0 +1,170 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { ar } from '@/i18n/ar'
+import { en } from '@/i18n/en'
+import { ja } from '@/i18n/ja'
+import { ru } from '@/i18n/ru'
+import { zh } from '@/i18n/zh'
+import { zhHant } from '@/i18n/zh-hant'
+
+import type { ScreenshotStatus } from '../../../electron/command-screenshot-types'
+
+import { ScreenshotSettings } from './screenshot-settings'
+
+vi.mock('@/i18n', () => ({ useI18n: () => ({ t: en }) }))
+
+const copy = en.settings.screenshot
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(yes => {
+ resolve = yes
+ })
+
+ return { promise, resolve }
+}
+
+function installBridge() {
+ let onStatus: (status: ScreenshotStatus) => void = () => {}
+ const unsubscribe = vi.fn()
+ const api = {
+ getSettings: vi.fn<() => Promise<ScreenshotStatus>>(),
+ setEnabled: vi.fn<(enabled: boolean) => Promise<ScreenshotStatus>>(),
+ openPermissionSettings: vi.fn<(kind: 'input' | 'screen') => Promise<void>>().mockResolvedValue(undefined),
+ onStatus: vi.fn((callback: (status: ScreenshotStatus) => void) => {
+ onStatus = callback
+ return unsubscribe
+ })
+ }
+ vi.stubGlobal('hermesDesktop', { screenshot: api })
+
+ return { api, emit: (status: ScreenshotStatus) => onStatus(status), unsubscribe }
+}
+
+async function click(element: HTMLElement) {
+ await act(async () => fireEvent.click(element))
+}
+
+afterEach(() => {
+ cleanup()
+ vi.unstubAllGlobals()
+})
+
+describe('ScreenshotSettings', () => {
+ it('requires opt-in and explicit permission retry before claiming the shortcut is ready', async () => {
+ const { api, emit, unsubscribe } = installBridge()
+ const initial = deferred<ScreenshotStatus>()
+ const enabling = deferred<ScreenshotStatus>()
+ api.getSettings.mockReturnValue(initial.promise)
+ api.setEnabled.mockReturnValueOnce(enabling.promise)
+ const view = render(<ScreenshotSettings />)
+ const toggle = screen.getByRole('switch', { name: copy.enabledTitle })
+
+ expect(toggle).toHaveProperty('disabled', true)
+ expect(toggle).toHaveProperty('ariaChecked', 'false')
+ expect(api.setEnabled).not.toHaveBeenCalled()
+ await act(async () => initial.resolve({ enabled: false, state: 'disabled' }))
+ await click(toggle)
+ expect(api.setEnabled).toHaveBeenLastCalledWith(true)
+ expect(toggle).toHaveProperty('ariaChecked', 'false')
+ expect(screen.queryByText(copy.ready)).toBeNull()
+ await act(async () => enabling.resolve({ enabled: true, state: 'input-permission' }))
+ expect(toggle).toHaveProperty('ariaChecked', 'true')
+ expect(screen.getByText(copy.inputPermission)).toBeTruthy()
+ expect(screen.queryByText(copy.ready)).toBeNull()
+
+ await click(screen.getByRole('button', { name: copy.openSettings }))
+ expect(api.openPermissionSettings).toHaveBeenLastCalledWith('input')
+ expect(api.setEnabled).toHaveBeenCalledTimes(1)
+ api.setEnabled.mockResolvedValueOnce({ enabled: true, state: 'screen-permission' })
+ await click(screen.getByRole('button', { name: copy.retry }))
+ expect(api.setEnabled).toHaveBeenLastCalledWith(true)
+ expect(screen.getByText(copy.screenPermission)).toBeTruthy()
+ await click(screen.getByRole('button', { name: copy.openSettings }))
+ expect(api.openPermissionSettings).toHaveBeenLastCalledWith('screen')
+
+ api.setEnabled.mockResolvedValueOnce({ enabled: true, state: 'starting' })
+ await click(screen.getByRole('button', { name: copy.retry }))
+ expect(screen.getByText(copy.starting)).toBeTruthy()
+ expect(screen.queryByText(copy.ready)).toBeNull()
+ await act(async () => emit({ enabled: true, state: 'ready' }))
+ expect(screen.getByText(copy.ready)).toBeTruthy()
+ api.setEnabled.mockResolvedValueOnce({ enabled: false, state: 'disabled' })
+ await click(toggle)
+ expect(api.setEnabled).toHaveBeenLastCalledWith(false)
+ expect(toggle).toHaveProperty('ariaChecked', 'false')
+ expect(screen.queryByText(copy.ready)).toBeNull()
+ view.unmount()
+ expect(unsubscribe).toHaveBeenCalledOnce()
+ })
+
+ it('keeps read, write, and permission failures recoverable without claiming success', async () => {
+ const { api, emit } = installBridge()
+ api.getSettings.mockRejectedValueOnce(new Error('IPC unavailable'))
+ render(<ScreenshotSettings />)
+ const toggle = screen.getByRole('switch', { name: copy.enabledTitle })
+ expect(await screen.findByText(copy.loadFailed)).toBeTruthy()
+ expect(toggle).toHaveProperty('disabled', true)
+ expect(api.setEnabled).not.toHaveBeenCalled()
+
+ api.getSettings.mockResolvedValueOnce({ enabled: false, state: 'disabled' })
+ await click(screen.getByRole('button', { name: copy.retry }))
+ expect(toggle).toHaveProperty('disabled', false)
+ api.setEnabled.mockImplementationOnce(async () => {
+ emit({ enabled: false, state: 'disabled' })
+ throw new Error('Unconfirmed write')
+ })
+ await click(toggle)
+ expect(screen.getByText(copy.saveFailed)).toBeTruthy()
+ expect(toggle).toHaveProperty('ariaChecked', 'false')
+ expect(screen.queryByText(copy.ready)).toBeNull()
+
+ // A write may have landed even if IPC rejected: reread, don't guess.
+ api.getSettings.mockResolvedValueOnce({ enabled: true, state: 'screen-permission' })
+ await click(screen.getByRole('button', { name: copy.retry }))
+ expect(toggle).toHaveProperty('ariaChecked', 'true')
+ api.openPermissionSettings.mockRejectedValueOnce(new Error('Cannot open settings'))
+ await click(screen.getByRole('button', { name: copy.openSettings }))
+ expect(screen.getByText(copy.permissionFailed)).toBeTruthy()
+ expect(screen.queryByText(copy.ready)).toBeNull()
+
+ // Manual permission recovery must restart the listener, not just reread.
+ api.setEnabled.mockResolvedValueOnce({ enabled: true, state: 'unavailable' })
+ await click(screen.getByRole('button', { name: copy.retry }))
+ expect(api.setEnabled).toHaveBeenCalledTimes(2)
+ expect(screen.getByText(copy.unavailable)).toBeTruthy()
+ api.setEnabled.mockResolvedValueOnce({ enabled: true, state: 'ready' })
+ await click(screen.getByRole('button', { name: copy.retry }))
+ expect(screen.getByText(copy.ready)).toBeTruthy()
+ })
+
+ it('keeps newer native status over stale reads and hides without the native capability', async () => {
+ const { api, emit, unsubscribe } = installBridge()
+ const initial = deferred<ScreenshotStatus>()
+ api.getSettings.mockReturnValue(initial.promise)
+ const view = render(<ScreenshotSettings />)
+ await act(async () => emit({ enabled: false, state: 'disabled' }))
+ await act(async () => initial.resolve({ enabled: true, state: 'ready' }))
+ expect(screen.getByRole('switch')).toHaveProperty('ariaChecked', 'false')
+ expect(screen.queryByText(copy.ready)).toBeNull()
+ expect(api.setEnabled).not.toHaveBeenCalled()
+ view.unmount()
+ expect(unsubscribe).toHaveBeenCalledOnce()
+
+ vi.stubGlobal('hermesDesktop', {})
+ const unsupported = render(<ScreenshotSettings />)
+ expect(unsupported.container.childElementCount).toBe(0)
+ })
+
+ it('provides every screenshot message in each locale', () => {
+ for (const locale of [en, ja, zh, zhHant, ar, ru]) {
+ expect(Object.keys(locale.settings.screenshot).sort()).toEqual(Object.keys(copy).sort())
+ for (const text of Object.values(locale.settings.screenshot)) {
+ expect(typeof text).toBe('string')
+ expect(text.trim()).not.toBe('')
+ }
+ }
+ })
+})
diff --git a/apps/desktop/src/app/settings/screenshot-settings.tsx b/apps/desktop/src/app/settings/screenshot-settings.tsx
new file mode 100644
index 00000000000..b30b094724f
--- /dev/null
+++ b/apps/desktop/src/app/settings/screenshot-settings.tsx
@@ -0,0 +1,159 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+
+import { Button } from '@/components/ui/button'
+import { ErrorIcon } from '@/components/ui/error-state'
+import { Loader } from '@/components/ui/loader'
+import { useI18n } from '@/i18n'
+
+import type { ScreenshotStatus } from '../../../electron/command-screenshot-types'
+
+import { ListRow, ToggleRow } from './primitives'
+
+type SettingsError = 'loadFailed' | 'saveFailed' | 'permissionFailed'
+
+export function ScreenshotSettings() {
+ const { t } = useI18n()
+ const s = t.settings.screenshot
+ const api = window.hermesDesktop?.screenshot
+ const [status, setStatus] = useState<ScreenshotStatus | null>(null)
+ const [busy, setBusy] = useState(true)
+ const [error, setError] = useState<SettingsError | null>(null)
+ const requestId = useRef(0)
+ const statusVersion = useRef(0)
+
+ const refresh = useCallback(
+ async (enabled?: boolean) => {
+ if (!api) {
+ return
+ }
+
+ const id = ++requestId.current
+ const version = statusVersion.current
+ setBusy(true)
+ setError(null)
+
+ try {
+ const next = await (enabled === undefined ? api.getSettings() : api.setEnabled(enabled))
+
+ // Native events must not be overwritten by an older IPC snapshot.
+ if (id === requestId.current && version === statusVersion.current) {
+ setStatus(next)
+ }
+ } catch {
+ if (id === requestId.current && (enabled !== undefined || version === statusVersion.current)) {
+ setError(enabled === undefined ? 'loadFailed' : 'saveFailed')
+ }
+ } finally {
+ if (id === requestId.current) {
+ setBusy(false)
+ }
+ }
+ },
+ [api]
+ )
+
+ // eslint-disable-next-line no-restricted-syntax -- IPC request/status generations, not atom mirrors.
+ useEffect(() => {
+ if (!api) {
+ return
+ }
+
+ const unsubscribe = api.onStatus(next => {
+ statusVersion.current += 1
+ setStatus(next)
+ setError(null)
+ })
+ void refresh()
+
+ return () => {
+ requestId.current += 1
+ unsubscribe()
+ }
+ }, [api, refresh])
+
+ if (!api) {
+ return null
+ }
+
+ const permission =
+ status?.state === 'input-permission' ? 'input' : status?.state === 'screen-permission' ? 'screen' : null
+
+ const openSettings = async () => {
+ if (!permission) {
+ return
+ }
+
+ const id = ++requestId.current
+ setBusy(true)
+ setError(null)
+
+ try {
+ await api.openPermissionSettings(permission)
+ } catch {
+ if (id === requestId.current) {
+ setError('permissionFailed')
+ }
+ } finally {
+ if (id === requestId.current) {
+ setBusy(false)
+ }
+ }
+ }
+
+ const descriptions: Record<ScreenshotStatus['state'], string> = {
+ disabled: s.disabled,
+ starting: s.starting,
+ ready: status?.enabled ? s.ready : s.disabled,
+ 'input-permission': s.inputPermission,
+ 'screen-permission': s.screenPermission,
+ unavailable: s.unavailable
+ }
+ const description = busy ? s.checking : error ? s[error] : descriptions[status?.state ?? 'disabled']
+ const showStatus = busy || error || status?.enabled || status?.state !== 'disabled'
+ const canRetry = error || (status?.state !== 'ready' && status?.state !== 'disabled')
+ // Failed reads/writes need reconciliation; permission recovery needs a restart.
+ const retryEnabled = status?.enabled && error !== 'loadFailed' && error !== 'saveFailed' ? true : undefined
+
+ return (
+ <>
+ <ToggleRow
+ checked={status?.enabled ?? false}
+ description={s.enabledDesc}
+ disabled={!status || busy}
+ label={s.enabledTitle}
+ onChange={enabled => void refresh(enabled)}
+ />
+ {showStatus && (
+ <ListRow
+ action={
+ busy ? (
+ <Loader className="size-5" label={s.checking} />
+ ) : (
+ <div className="flex flex-wrap items-center gap-2">
+ {permission && (
+ <Button onClick={() => void openSettings()} size="sm" variant="secondary">
+ {s.openSettings}
+ </Button>
+ )}
+ {canRetry && (
+ <Button onClick={() => void refresh(retryEnabled)} size="sm" variant="secondary">
+ {s.retry}
+ </Button>
+ )}
+ </div>
+ )
+ }
+ description={<span aria-live="polite">{description}</span>}
+ title={
+ error ? (
+ <span className="flex items-center gap-2">
+ <ErrorIcon size="1rem" />
+ {s.errorTitle}
+ </span>
+ ) : s.statusTitle
+ }
+ />
+ )}
+ </>
+ )
+}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index ff31c93d143..89ef4c4d048 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1,6 +1,7 @@
import type { GatewayWsUrlResult } from '@hermes/shared'
import type { TranslucencyState } from '@hermes/shared/translucency'
+import type { ScreenshotApi } from '../electron/command-screenshot-types'
import type { HermesNotification } from '../electron/notification-types'
import type { PoolLimits } from '../electron/pool-limits'
@@ -167,6 +168,8 @@ declare global {
onCursor: (callback: (point: { x: number; y: number } | null) => void) => () => void
onGameOverlay: (callback: (state: { active: boolean; app: string }) => void) => () => void
}
+ // macOS native screenshot gesture; absent on other platforms.
+ screenshot?: ScreenshotApi
// Quick Entry: a global-hotkey mini composer window. Main owns the OS
// shortcut registration + the persisted preference (it must restore the
// shortcut on a cold launch without the renderer visiting Settings), so
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index fa8e083c2be..a66272dce12 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -871,6 +871,29 @@ export const ar = defineLocale({
imported: 'تم استيراد الإعدادات',
invalidJson: 'JSON غير صالح'
},
+ screenshot: {
+ enabledTitle: 'اختصار لقطة الشاشة',
+ enabledDesc:
+ 'اضغط مفتاحَي Command معًا من أي تطبيق لالتقاط النافذة الأمامية وإرفاقها بمسودة Hermes الحالية. لا يُرسل أي شيء تلقائيًا. معطّل افتراضيًا ويُطبَّق على جهاز Mac هذا فقط. قد تتضمن النافذة محتوى حساسًا، لذا راجع المرفق قبل الإرسال.',
+ statusTitle: 'حالة اختصار لقطة الشاشة',
+ checking: 'جارٍ التحقق من اختصار لقطة الشاشة…',
+ disabled: 'اختصار لقطة الشاشة معطّل.',
+ starting: 'جارٍ بدء رصد الاختصار. لم يصبح جاهزًا بعد.',
+ ready: 'الاختصار جاهز. تُرفق اللقطات بالمسودة الحالية دون إرسالها.',
+ inputPermission:
+ 'يتيح إذن مراقبة الإدخال لـ Hermes رصد مفتاحَي Command أثناء استخدام تطبيق آخر. اسمح لـ Hermes في إعدادات النظام ← الخصوصية والأمان ← مراقبة الإدخال، ثم عُد إلى هنا وأعد المحاولة.',
+ screenPermission:
+ 'يتيح إذن تسجيل الشاشة لـ Hermes التقاط نافذة التطبيق الأمامية عند استخدام هذا الاختصار. اسمح لـ Hermes في إعدادات النظام ← الخصوصية والأمان ← تسجيل الشاشة، ثم عُد إلى هنا وأعد المحاولة. أعد تشغيل Hermes إذا طلب macOS ذلك.',
+ openSettings: 'فتح إعدادات النظام',
+ retry: 'إعادة المحاولة',
+ unavailable: 'اختصار لقطة الشاشة غير متاح. أعد المحاولة أو عطّله.',
+ errorTitle: 'خطأ في اختصار لقطة الشاشة',
+ loadFailed: 'تعذّرت قراءة حالة الاختصار. أعد المحاولة للتحقق من إعداده الحالي.',
+ saveFailed: 'تعذّر تأكيد تغيير الاختصار. أعد المحاولة للتحقق من إعداده الحالي.',
+ permissionFailed: 'تعذّر فتح إعدادات النظام. افتح الخصوصية والأمان يدويًا، ثم أعد المحاولة.',
+ captureFailed: 'تعذّر التقاط النافذة الأمامية. لم يُرفق أو يُرسل أي شيء.',
+ contextChanged: 'تغيّرت المسودة الحالية أثناء الالتقاط. لم تُرفق اللقطة أو تُرسل.'
+ },
quickEntry: {
enabledTitle: 'الإدخال السريع',
enabledDesc: 'استدعِ محرّرا صغيرا من أي مكان باختصار عام وأرسل طلبا دون فتح Hermes.',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index fd0d1bd1e9b..1431a1bc505 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -998,6 +998,29 @@ export const en: Translations = {
attachmentSizeLabel: 'Max preview / image load size in megabytes',
showOptions: 'Show options'
},
+ screenshot: {
+ enabledTitle: 'Screenshot shortcut',
+ enabledDesc:
+ 'Press both Command keys together from any app to capture its frontmost window and attach it to your current Hermes draft. Never sends automatically. Off by default; applies only to this Mac. Window contents may be sensitive — review the attachment before sending.',
+ statusTitle: 'Screenshot shortcut status',
+ checking: 'Checking screenshot shortcut…',
+ disabled: 'Screenshot shortcut is off.',
+ starting: 'Starting the shortcut listener. It is not ready yet.',
+ ready: 'Shortcut is ready. Screenshots attach to your current draft without sending.',
+ inputPermission:
+ 'Input Monitoring permission lets Hermes detect both Command keys while another app is active. Allow Hermes in System Settings → Privacy & Security → Input Monitoring, then return here and retry.',
+ screenPermission:
+ 'Screen Recording permission lets Hermes capture the frontmost app window when you use this shortcut. Allow Hermes in System Settings → Privacy & Security → Screen Recording, then return here and retry. Restart Hermes if macOS asks.',
+ openSettings: 'Open System Settings',
+ retry: 'Retry',
+ unavailable: 'The screenshot shortcut is unavailable. Retry, or turn it off.',
+ errorTitle: 'Screenshot shortcut error',
+ loadFailed: 'Could not read the shortcut status. Retry to check its current setting.',
+ saveFailed: 'Could not confirm the shortcut change. Retry to check its current setting.',
+ permissionFailed: 'Could not open System Settings. Open Privacy & Security manually, then retry.',
+ captureFailed: 'Could not capture the frontmost window. Nothing was attached or sent.',
+ contextChanged: 'The current draft changed during capture. The screenshot was not attached or sent.'
+ },
quickEntry: {
enabledTitle: 'Quick Entry',
enabledDesc:
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 59c3056cae0..797fe7ff9e9 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -947,6 +947,29 @@ export const ja = defineLocale({
keepAwakeTitle: 'コンピューターをスリープさせない',
keepAwakeDesc: '本体のスリープを防ぎ、長時間や夜通しの実行を継続します。画面は暗転できます。'
},
+ screenshot: {
+ enabledTitle: 'スクリーンショットのショートカット',
+ enabledDesc:
+ 'どのアプリからでも左右の Command キーを同時に押すと、最前面のウインドウを撮影し、Hermes の現在の下書きに添付します。自動送信はしません。初期設定はオフで、この Mac にのみ適用されます。機密情報が写る可能性があるため、送信前に添付画像を確認してください。',
+ statusTitle: 'スクリーンショットのショートカットの状態',
+ checking: 'スクリーンショットのショートカットを確認中…',
+ disabled: 'スクリーンショットのショートカットはオフです。',
+ starting: 'ショートカットの検出を開始しています。まだ使用できません。',
+ ready: 'ショートカットを使用できます。撮影した画像は現在の下書きに添付され、送信はされません。',
+ inputPermission:
+ '入力監視の許可により、他のアプリがアクティブな間も両方の Command キーを検出できます。システム設定 → プライバシーとセキュリティ → 入力監視で Hermes を許可し、ここに戻って再試行してください。',
+ screenPermission:
+ '画面収録の許可により、このショートカットを使ったときに最前面のアプリのウインドウを撮影できます。システム設定 → プライバシーとセキュリティ → 画面収録で Hermes を許可し、ここに戻って再試行してください。macOS に求められた場合は Hermes を再起動してください。',
+ openSettings: 'システム設定を開く',
+ retry: '再試行',
+ unavailable: 'スクリーンショットのショートカットは使用できません。再試行するか、オフにしてください。',
+ errorTitle: 'スクリーンショットのショートカットのエラー',
+ loadFailed: 'ショートカットの状態を読み取れませんでした。再試行して現在の設定を確認してください。',
+ saveFailed: 'ショートカットの変更を確認できませんでした。再試行して現在の設定を確認してください。',
+ permissionFailed: 'システム設定を開けませんでした。プライバシーとセキュリティを手動で開き、再試行してください。',
+ captureFailed: '最前面のウインドウを撮影できませんでした。添付も送信もされていません。',
+ contextChanged: '撮影中に現在の下書きが変わりました。画像は添付も送信もされていません。'
+ },
quickEntry: {
enabledTitle: 'クイック入力',
enabledDesc:
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index a5c6b850b87..5fcff28fd9c 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -1042,6 +1042,29 @@ export const ru = defineLocale({
attachmentSizeUnit: 'МБ',
attachmentSizeLabel: 'Макс. размер превью / загрузки изображений в мегабайтах'
},
+ screenshot: {
+ enabledTitle: 'Сочетание клавиш для снимка окна',
+ enabledDesc:
+ 'Нажмите обе клавиши Command одновременно в любом приложении, чтобы снять его переднее окно и прикрепить снимок к текущему черновику Hermes. Автоматической отправки нет. По умолчанию выключено; действует только на этом Mac. Окно может содержать конфиденциальные данные — проверьте вложение перед отправкой.',
+ statusTitle: 'Состояние сочетания для снимка окна',
+ checking: 'Проверка сочетания для снимка окна…',
+ disabled: 'Сочетание для снимка окна выключено.',
+ starting: 'Запускается отслеживание сочетания. Оно пока не готово.',
+ ready: 'Сочетание готово. Снимки прикрепляются к текущему черновику без отправки.',
+ inputPermission:
+ 'Разрешение на мониторинг ввода позволяет Hermes распознавать обе клавиши Command, когда активно другое приложение. Разрешите Hermes доступ в Системных настройках → Конфиденциальность и безопасность → Мониторинг ввода, затем вернитесь сюда и повторите попытку.',
+ screenPermission:
+ 'Разрешение на запись экрана позволяет Hermes снимать переднее окно приложения при использовании этого сочетания. Разрешите Hermes доступ в Системных настройках → Конфиденциальность и безопасность → Запись экрана, затем вернитесь сюда и повторите попытку. Перезапустите Hermes, если macOS попросит.',
+ openSettings: 'Открыть Системные настройки',
+ retry: 'Повторить',
+ unavailable: 'Сочетание для снимка окна недоступно. Повторите попытку или выключите его.',
+ errorTitle: 'Ошибка сочетания для снимка окна',
+ loadFailed: 'Не удалось прочитать состояние сочетания. Повторите попытку, чтобы проверить текущую настройку.',
+ saveFailed: 'Не удалось подтвердить изменение сочетания. Повторите попытку, чтобы проверить текущую настройку.',
+ permissionFailed: 'Не удалось открыть Системные настройки. Откройте раздел «Конфиденциальность и безопасность» вручную и повторите попытку.',
+ captureFailed: 'Не удалось снять переднее окно. Ничего не прикреплено и не отправлено.',
+ contextChanged: 'Текущий черновик изменился во время съёмки. Снимок не прикреплён и не отправлен.'
+ },
quickEntry: {
enabledTitle: 'Быстрый ввод',
enabledDesc:
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 2ef07391a9e..963eb547594 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -870,6 +870,26 @@ export interface Translations {
attachmentSizeLabel: string
showOptions: string
}
+ screenshot: {
+ enabledTitle: string
+ enabledDesc: string
+ statusTitle: string
+ checking: string
+ disabled: string
+ starting: string
+ ready: string
+ inputPermission: string
+ screenPermission: string
+ openSettings: string
+ retry: string
+ unavailable: string
+ errorTitle: string
+ loadFailed: string
+ saveFailed: string
+ permissionFailed: string
+ captureFailed: string
+ contextChanged: string
+ }
quickEntry: {
enabledTitle: string
enabledDesc: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 3cbed17ac25..f485672b680 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -987,6 +987,29 @@ export const zhHant = defineLocale({
keepAwakeDesc: '阻止本機睡眠,讓長時間或整夜執行持續進行。螢幕仍可變暗。',
showOptions: '顯示選項'
},
+ screenshot: {
+ enabledTitle: '螢幕截圖快速鍵',
+ enabledDesc:
+ '在任何應用程式中同時按下左右兩個 Command 鍵,即可擷取最前方的視窗並附加到目前的 Hermes 草稿。絕不會自動傳送。預設關閉,僅適用於這台 Mac。視窗可能包含敏感內容,請在傳送前檢查附件。',
+ statusTitle: '螢幕截圖快速鍵狀態',
+ checking: '正在檢查螢幕截圖快速鍵…',
+ disabled: '螢幕截圖快速鍵已關閉。',
+ starting: '正在啟動快速鍵偵測,尚未就緒。',
+ ready: '快速鍵已就緒。截圖會附加到目前的草稿,不會傳送。',
+ inputPermission:
+ '輸入監控權限可讓 Hermes 在其他應用程式使用中時偵測兩個 Command 鍵。請在系統設定 → 隱私權與安全性 → 輸入監控中允許 Hermes,然後返回此處重試。',
+ screenPermission:
+ '螢幕錄製權限可讓 Hermes 在你使用此快速鍵時擷取最前方的應用程式視窗。請在系統設定 → 隱私權與安全性 → 螢幕錄製中允許 Hermes,然後返回此處重試。如果 macOS 提示,請重新啟動 Hermes。',
+ openSettings: '開啟系統設定',
+ retry: '重試',
+ unavailable: '螢幕截圖快速鍵無法使用。請重試或將其關閉。',
+ errorTitle: '螢幕截圖快速鍵錯誤',
+ loadFailed: '無法讀取快速鍵狀態。請重試以檢查目前的設定。',
+ saveFailed: '無法確認快速鍵變更。請重試以檢查目前的設定。',
+ permissionFailed: '無法開啟系統設定。請手動開啟「隱私權與安全性」,然後重試。',
+ captureFailed: '無法擷取最前方的視窗。未附加或傳送任何內容。',
+ contextChanged: '截圖期間目前的草稿已變更。截圖未附加或傳送。'
+ },
quickEntry: {
enabledTitle: '快速輸入',
enabledDesc: '用全域快速鍵在任何地方喚出一個小輸入框,無需開啟 Hermes 即可送出提示。',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index b3b5342d677..aa9eb6da0a0 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1202,6 +1202,29 @@ export const zh = defineLocale({
attachmentSizeLabel: '预览 / 图片加载大小上限(MB)',
showOptions: '显示选项'
},
+ screenshot: {
+ enabledTitle: '截图快捷键',
+ enabledDesc:
+ '在任意应用中同时按下左右两个 Command 键,即可截取最前面的窗口并附加到当前 Hermes 草稿。绝不会自动发送。默认关闭,仅适用于这台 Mac。窗口可能包含敏感内容,请在发送前检查附件。',
+ statusTitle: '截图快捷键状态',
+ checking: '正在检查截图快捷键…',
+ disabled: '截图快捷键已关闭。',
+ starting: '正在启动快捷键监听,尚未就绪。',
+ ready: '快捷键已就绪。截图会附加到当前草稿,不会发送。',
+ inputPermission:
+ '输入监控权限允许 Hermes 在其他应用处于活动状态时检测两个 Command 键。请在系统设置 → 隐私与安全性 → 输入监控中允许 Hermes,然后返回此处重试。',
+ screenPermission:
+ '屏幕录制权限允许 Hermes 在你使用此快捷键时截取最前面的应用窗口。请在系统设置 → 隐私与安全性 → 屏幕录制中允许 Hermes,然后返回此处重试。如果 macOS 提示,请重启 Hermes。',
+ openSettings: '打开系统设置',
+ retry: '重试',
+ unavailable: '截图快捷键不可用。请重试或将其关闭。',
+ errorTitle: '截图快捷键错误',
+ loadFailed: '无法读取快捷键状态。请重试以检查当前设置。',
+ saveFailed: '无法确认快捷键更改。请重试以检查当前设置。',
+ permissionFailed: '无法打开系统设置。请手动打开“隐私与安全性”,然后重试。',
+ captureFailed: '无法截取最前面的窗口。未附加或发送任何内容。',
+ contextChanged: '截图期间当前草稿发生了变化。截图未附加或发送。'
+ },
quickEntry: {
enabledTitle: '快速输入',
enabledDesc: '用全局快捷键在任何地方唤出一个小输入框,无需打开 Hermes 即可发送提示。',