fix(desktop): polish HUD movement and resizing on X11

This commit is contained in:
howdeploy
2026-08-24 12:35:55 +03:00
committed by brooklyn!
parent 4fee6f31a0
commit 81baae6bc3
16 changed files with 693 additions and 111 deletions
+18 -1
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
import { applyHudResetBounds, defaultHudBounds } from './hud-geometry'
import { applyHudResetBounds, defaultHudBounds, normalizeHudResizeBounds } from './hud-geometry'
test('defaultHudBounds restores the standard centered bottom layout', () => {
assert.deepEqual(defaultHudBounds({ x: 0, y: 25, width: 1440, height: 875 }), {
@@ -28,6 +28,7 @@ test('defaultHudBounds keeps the spawn fallback when no display is available', (
test('applyHudResetBounds restores the resize lock and reports native failure', () => {
let resizable = false
const win = {
isDestroyed: () => false,
isResizable: () => resizable,
@@ -46,6 +47,7 @@ test('applyHudResetBounds restores the resize lock and reports native failure',
test('applyHudResetBounds flips resizable on while the size changes', () => {
let resizable = false
const applied: Array<{ height: number; width: number }> = []
const win = {
isDestroyed: () => false,
isResizable: () => resizable,
@@ -62,3 +64,18 @@ test('applyHudResetBounds flips resizable on while the size changes', () => {
assert.equal(resizable, false)
assert.deepEqual(applied, [{ width: 620, height: 320 }])
})
test('normalizeHudResizeBounds rounds finite geometry and clamps the HUD minimums', () => {
assert.deepEqual(normalizeHudResizeBounds({ x: 10.4, y: -20.6, width: 100, height: 80 }), {
x: 10,
y: -21,
width: 380,
height: 160
})
})
test('normalizeHudResizeBounds rejects incomplete or non-finite native geometry', () => {
assert.equal(normalizeHudResizeBounds(null), null)
assert.equal(normalizeHudResizeBounds({ x: 0, y: 0, width: Number.NaN, height: 320 }), null)
assert.equal(normalizeHudResizeBounds({ x: 0, y: 0, width: 620 }), null)
})
+31
View File
@@ -38,6 +38,37 @@ export interface HudBoundsWindow {
setResizable(resizable: boolean): void
}
export interface HudResizeBounds {
height: number
width: number
x: number
y: number
}
/** Validate renderer-provided resize geometry before it reaches native APIs. */
export function normalizeHudResizeBounds(value: unknown): HudResizeBounds | null {
if (!value || typeof value !== 'object') {
return null
}
const candidate = value as Partial<Record<keyof HudResizeBounds, unknown>>
const x = Number(candidate.x)
const y = Number(candidate.y)
const width = Number(candidate.width)
const height = Number(candidate.height)
if (![x, y, width, height].every(Number.isFinite)) {
return null
}
return {
x: Math.round(x),
y: Math.round(y),
width: Math.max(380, Math.round(width)),
height: Math.max(160, Math.round(height))
}
}
/**
* Apply recovery bounds. The HUD is created non-resizable (a transparent
* frameless window must not expose a system resize hot-zone), which on
+19 -1
View File
@@ -8,7 +8,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
import { hudInputPolicy } from './hud-input-policy'
import { hudInputPolicy, hudUsesNativeDrag, hudUsesWorkspaceTransfer } from './hud-input-policy'
const X11_SESSION = { DISPLAY: ':0', XDG_SESSION_TYPE: 'x11' }
const WAYLAND_SESSION = { WAYLAND_DISPLAY: 'wayland-0', XDG_SESSION_TYPE: 'wayland' }
@@ -71,3 +71,21 @@ test('a backend nobody recognises follows the session, not a silent X11 default'
assert.equal(hudInputPolicy('linux', WAYLAND_SESSION, ['--ozone-platform=headless']), 'click-through')
assert.equal(hudInputPolicy('linux', {}, []), 'solid')
})
test('only a native Wayland HUD gets a compositor drag region', () => {
assert.equal(hudUsesNativeDrag('darwin', WAYLAND_SESSION, []), false)
assert.equal(hudUsesNativeDrag('win32', WAYLAND_SESSION, []), false)
assert.equal(hudUsesNativeDrag('linux', X11_SESSION, []), false)
assert.equal(hudUsesNativeDrag('linux', WAYLAND_SESSION, []), true)
assert.equal(hudUsesNativeDrag('linux', WAYLAND_SESSION, ['--ozone-platform=x11']), false)
assert.equal(hudUsesNativeDrag('linux', X11_SESSION, ['--ozone-platform=wayland']), true)
})
test('only a renderer-driven Linux HUD needs temporary all-workspace visibility', () => {
assert.equal(hudUsesWorkspaceTransfer('darwin', X11_SESSION, []), false)
assert.equal(hudUsesWorkspaceTransfer('win32', X11_SESSION, []), false)
assert.equal(hudUsesWorkspaceTransfer('linux', X11_SESSION, []), true)
assert.equal(hudUsesWorkspaceTransfer('linux', WAYLAND_SESSION, []), false)
assert.equal(hudUsesWorkspaceTransfer('linux', WAYLAND_SESSION, ['--ozone-platform=x11']), true)
assert.equal(hudUsesWorkspaceTransfer('linux', X11_SESSION, ['--ozone-platform=wayland']), false)
})
+30
View File
@@ -96,3 +96,33 @@ export function hudInputPolicy(platform: string, env: NodeJS.ProcessEnv, argv: r
return linuxBackend(env, argv) === 'x11' ? 'solid' : 'click-through'
}
/**
* Whether the renderer needs a native compositor drag region for the HUD.
*
* Native Wayland cannot honour app-driven window positions, so it needs
* `-webkit-app-region: drag`. X11 can use the renderer's `moveBy` path and
* must not install that region: it consumes the pointer stream needed by the
* renderer's immediate Ctrl+primary-button drag.
*/
export function hudUsesNativeDrag(platform: string, env: NodeJS.ProcessEnv, argv: readonly string[]): boolean {
return platform === 'linux' && hudInputPolicy(platform, env, argv) === 'click-through'
}
/**
* Whether a renderer-driven HUD move needs the X11 workspace-transfer bridge.
*
* While the pointer is grabbed the window is made temporarily visible on all
* desktops. Releasing the grab clears that flag; Chromium's X11 backend then
* reads `_NET_CURRENT_DESKTOP` and sends `_NET_WM_DESKTOP` for that desktop,
* which gives KWin the same "hold window + switch desktop" behaviour as a
* native titlebar drag. Native Wayland already delegates movement to the
* compositor and must stay out of this path.
*/
export function hudUsesWorkspaceTransfer(
platform: string,
env: NodeJS.ProcessEnv,
argv: readonly string[]
): boolean {
return platform === 'linux' && hudInputPolicy(platform, env, argv) === 'solid'
}
+55 -12
View File
@@ -4,7 +4,8 @@
// latch when handing the session back to the app window.
import { type BrowserWindow, ipcMain } from 'electron'
import { hudInputPolicy } from './hud-input-policy'
import { normalizeHudResizeBounds } from './hud-geometry'
import { hudInputPolicy, hudUsesNativeDrag, hudUsesWorkspaceTransfer } from './hud-input-policy'
import { hudFrostFor, type TranslucencyState } from './translucency'
export interface HudIpcDeps {
@@ -27,6 +28,38 @@ export function registerHudIpc({
resetHudLayout,
setHudSessionId
}: HudIpcDeps) {
// The renderer needs this before first paint so X11 never installs the
// Chromium drag region that steals modifier-drag gestures from the WM.
// Main answers because it owns the actual Ozone backend selection.
ipcMain.on('hermes:hud:native-drag', event => {
event.returnValue = hudUsesNativeDrag(process.platform, process.env, process.argv)
})
// X11/KWin window transfer: a renderer-driven grab is temporarily sticky so
// the user can keep Ctrl+primary-button held while invoking KDE's desktop
// switch shortcut. Clearing sticky on release makes Chromium assign the
// window to `_NET_CURRENT_DESKTOP`, exactly like releasing a native titlebar
// drag on the destination desktop. Native Wayland owns its move loop and
// Windows/macOS stay out of this Linux-specific bridge.
ipcMain.on('hermes:hud:workspace-transfer', (event, transferring) => {
const hudWindow = getHudWindow()
if (
!hudWindow ||
hudWindow.isDestroyed() ||
event.sender !== hudWindow.webContents ||
!hudUsesWorkspaceTransfer(process.platform, process.env, process.argv)
) {
return
}
try {
hudWindow.setVisibleOnAllWorkspaces(Boolean(transferring))
} catch {
// Workspace APIs are window-manager capabilities — best effort.
}
})
// Whether the band currently covers the window below the bar. The renderer
// is the only party that can know this (it measures the transcript), and it
// is half of the frost decision — the other half is the user's setting,
@@ -159,7 +192,7 @@ export function registerHudIpc({
})
})
// Resize from the HUD's corner handle. The window is created non-resizable
// Resize from the HUD's edge/corner handles. The window is created non-resizable
// (see spawnHudWindow — a transparent frameless window must not expose a
// system resize hot-zone, or dragging grows it), which on Windows/Linux also
// blocks programmatic setBounds sizing — so briefly flip resizable on while
@@ -171,20 +204,30 @@ export function registerHudIpc({
return
}
const win = hudWindow
const width = Math.max(380, Math.round(Number(bounds.width)))
const height = Math.max(160, Math.round(Number(bounds.height)))
const [curW, curH] = win.getSize()
const resizing = width !== curW || height !== curH
const nextBounds = normalizeHudResizeBounds(bounds)
if (resizing && !win.isResizable()) {
win.setResizable(true)
if (!nextBounds) {
return
}
win.setBounds({ x: Math.round(Number(bounds.x)), y: Math.round(Number(bounds.y)), width, height })
const win = hudWindow
const { width, height } = nextBounds
const [curW, curH] = win.getSize()
const resizing = width !== curW || height !== curH
const restoreResizeLock = resizing && !win.isResizable()
if (resizing) {
win.setResizable(false)
try {
if (restoreResizeLock) {
win.setResizable(true)
}
win.setBounds(nextBounds)
} catch {
// The window may disappear between validation and the native call.
} finally {
if (restoreResizeLock && !win.isDestroyed()) {
win.setResizable(false)
}
}
})
+11 -8
View File
@@ -11897,7 +11897,7 @@ function spawnHudWindow(sessionId, profile) {
// interprets pointer capture near the edge as a resize gesture, so the
// window grows a few px every drag (worse at >100% DPI scaling). The
// composer drag calls setPosition, which must move the window, not resize
// it. Resizing is done by the renderer's corner handle through
// it. Resizing is done by the renderer's edge/corner handles through
// `hermes:hud:set-bounds`, which flips resizable on for the call — the
// same pattern the pet overlay uses for its wheel-scale.
resizable: false,
@@ -11931,15 +11931,18 @@ function spawnHudWindow(sessionId, profile) {
win.setAlwaysOnTop(true, IS_MAC ? 'floating' : 'screen-saver')
win.setHiddenInMissionControl?.(true)
try {
win.setVisibleOnAllWorkspaces(
true,
IS_MAC ? { visibleOnFullScreen: true, skipTransformProcessType: true } : undefined
)
} catch {
// Not supported everywhere — best effort.
if (IS_MAC) {
try {
win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, skipTransformProcessType: true })
} catch {
// Not supported everywhere — best effort.
}
}
// Linux intentionally starts on ONE virtual desktop. During a renderer
// grab, hermes:hud:workspace-transfer temporarily makes the X11 window
// sticky; releasing it assigns the HUD to KDE's then-current desktop.
// Streaming into a window that is ALWAYS blurred (the user is in another
// app) is the entire feature, so it gets the same stream-aware unthrottling
// every chat window does.
+3
View File
@@ -8,6 +8,7 @@ import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'
// "Desktop IPC bridge is unavailable"). No reply means no glass, which degrades
// to an ordinary opaque window rather than a page thinned over nothing.
const translucencySupport = ipcRenderer.sendSync('hermes:translucency:support')
const hudNativeDrag = ipcRenderer.sendSync('hermes:hud:native-drag') === true
contextBridge.exposeInMainWorld('hermesDesktop', {
glassSupported: translucencySupport?.glass === true,
@@ -70,10 +71,12 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
// sized as a floating bar, so it mounts the real composer. Main owns the
// window; `onChanged` keeps every window's toggle truthful.
hud: {
nativeDrag: hudNativeDrag,
open: request => ipcRenderer.invoke('hermes:hud:open', request),
close: () => ipcRenderer.invoke('hermes:hud:close'),
setIgnoreMouse: ignore => ipcRenderer.send('hermes:hud:ignore-mouse', ignore),
moveBy: delta => ipcRenderer.send('hermes:hud:move-by', delta),
setWorkspaceTransfer: transferring => ipcRenderer.send('hermes:hud:workspace-transfer', transferring),
setBounds: bounds => ipcRenderer.send('hermes:hud:set-bounds', bounds),
resetLayout: () => ipcRenderer.invoke('hermes:hud:reset-layout'),
// Whether the band covers the window below the bar. Main pairs it with the
+18 -11
View File
@@ -108,7 +108,13 @@ export function ChatBar({
onTranscribeAudio
}: ChatBarProps) {
const hudMode = useStore($hudMode)
const { grabbing: hudGrabbing, onPointerDown: onHudDragPointerDown } = useHudComposerDrag(hudMode)
const hudNativeDrag = hudMode && window.hermesDesktop?.hud?.nativeDrag === true
const hudX11Drag = hudMode && isLinuxPlatform() && !hudNativeDrag
const { grabbing: hudGrabbing, onPointerDown: onHudDragPointerDown } = useHudComposerDrag(hudMode && !hudNativeDrag, {
controlDrag: hudX11Drag,
workspaceTransfer: hudX11Drag
})
// Typed stop phrase during an active voice conversation ends it — same
// semantics as SAYING "stop" (voice-stop-word.ts) or clicking the pill's
@@ -1008,10 +1014,10 @@ export function ChatBar({
'**:data-ref-text:cursor-default',
stacked && 'pl-3',
stacked ? 'w-full' : 'min-w-(--composer-input-inline-min-width) flex-1',
// Inside the Linux HUD drag region: a drag region swallows the page's
// mouse input whole, so the input must opt back out or it becomes
// unclickable. Buttons are covered by the global no-drag rule.
hudMode && isLinuxPlatform() && '[-webkit-app-region:no-drag]'
// Inside the native Wayland HUD drag region: a drag region swallows
// the page's mouse input whole, so the input must opt back out or it
// becomes unclickable. Buttons use the global no-drag rule.
hudNativeDrag && '[-webkit-app-region:no-drag]'
)}
contentEditable={!inputDisabled}
data-placeholder={placeholder}
@@ -1190,11 +1196,11 @@ export function ChatBar({
'group/composer relative w-full overflow-visible rounded-2xl',
poppedOut && 'bg-transparent',
dragging && 'cursor-grabbing select-none touch-none',
// Linux HUD: the bar is a native compositor drag handle
// (xdg_toplevel.move / _NET_WM_MOVERESIZE). setBounds position
// is a no-op on Wayland, so this is the only way to move it
// there. pt-4 is the grab band once the input/buttons opt out.
hudMode && isLinuxPlatform() && 'hud-native-drag pt-4 [-webkit-app-region:drag]'
// Native Wayland HUD: setBounds cannot position a top-level
// surface, so the bar must ask the compositor to move it. X11
// stays out of app-region mode so the renderer receives its
// Ctrl+primary-button drag. pt-4 is the carved-out grab band.
hudNativeDrag && 'hud-native-drag pt-4 [-webkit-app-region:drag]'
)}
data-drag-active={dragActive ? '' : undefined}
data-hud-grabbing={hudGrabbing ? '' : undefined}
@@ -1206,7 +1212,8 @@ export function ChatBar({
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
onPointerDown={hudMode ? onHudDragPointerDown : popoutAllowed ? onComposerGesturePointerDown : undefined}
onPointerDown={!hudMode && popoutAllowed ? onComposerGesturePointerDown : undefined}
onPointerDownCapture={hudMode ? onHudDragPointerDown : undefined}
onSubmit={e => {
e.preventDefault()
+96 -2
View File
@@ -1,4 +1,5 @@
import { act, renderHook } from '@testing-library/react'
import { act, render, renderHook } from '@testing-library/react'
import { createElement } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useHudComposerDrag } from './composer-drag'
@@ -10,6 +11,7 @@ const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDeskt
const initialHermesDesktop = desktopWindow.hermesDesktop
const moveBy = vi.fn()
const setWorkspaceTransfer = vi.fn()
function setWindowSize(width: number, height: number) {
Object.defineProperty(window, 'outerWidth', { configurable: true, value: width })
@@ -30,8 +32,9 @@ function pressTarget() {
beforeEach(() => {
vi.useFakeTimers()
moveBy.mockClear()
setWorkspaceTransfer.mockClear()
setWindowSize(620, 320)
desktopWindow.hermesDesktop = { hud: { moveBy } } as unknown as Window['hermesDesktop']
desktopWindow.hermesDesktop = { hud: { moveBy, setWorkspaceTransfer } } as unknown as Window['hermesDesktop']
})
afterEach(() => {
@@ -63,6 +66,7 @@ describe('useHudComposerDrag', () => {
act(() => void window.dispatchEvent(new PointerEvent('pointermove', { pointerId: 1, screenX: 110, screenY: 210 })))
expect(moveBy).toHaveBeenCalledWith({ x: 10, y: 10, width: 620, height: 320 })
expect(setWorkspaceTransfer).not.toHaveBeenCalled()
// A window that drifted wider mid-drag must not feed its new size back in —
// that is exactly how the Windows growth compounded.
@@ -88,5 +92,95 @@ describe('useHudComposerDrag', () => {
act(() => void window.dispatchEvent(new PointerEvent('pointermove', { pointerId: 1, screenX: 102, screenY: 201 })))
expect(moveBy).not.toHaveBeenCalled()
expect(setWorkspaceTransfer).not.toHaveBeenCalled()
})
it('spans X11 workspaces only for an armed grab, then pins to the current desktop on release', () => {
const target = pressTarget()
const { result } = renderHook(() =>
useHudComposerDrag(true, { controlDrag: true, workspaceTransfer: true })
)
act(() =>
result.current.onPointerDown({
button: 0,
ctrlKey: true,
currentTarget: target,
pointerId: 9,
preventDefault: vi.fn(),
screenX: 100,
screenY: 200
} as never)
)
expect(setWorkspaceTransfer).toHaveBeenLastCalledWith(true)
act(() => void window.dispatchEvent(new PointerEvent('pointerup', { pointerId: 9 })))
expect(setWorkspaceTransfer).toHaveBeenLastCalledWith(false)
})
it('moves immediately with Ctrl over selected text without destroying the selection', () => {
function Harness() {
const { onPointerDown } = useHudComposerDrag(true, { controlDrag: true })
return createElement(
'form',
{ 'data-testid': 'composer', onPointerDownCapture: onPointerDown },
createElement(
'div',
{ contentEditable: true, 'data-testid': 'editor', suppressContentEditableWarning: true, tabIndex: 0 },
'selected text stays selected'
)
)
}
const { getByTestId } = render(createElement(Harness))
const editor = getByTestId('editor')
const text = editor.firstChild!
editor.focus()
const range = document.createRange()
range.setStart(text, 0)
range.setEnd(text, 13)
const selection = window.getSelection()!
selection.removeAllRanges()
selection.addRange(range)
const down = new PointerEvent('pointerdown', {
bubbles: true,
button: 0,
buttons: 1,
cancelable: true,
ctrlKey: true,
pointerId: 7,
screenX: 300,
screenY: 180
})
act(() => void editor.dispatchEvent(down))
expect(down.defaultPrevented).toBe(true)
expect(document.activeElement).toBe(editor)
expect(selection.toString()).toBe('selected text')
const dragStart = new Event('dragstart', { bubbles: true, cancelable: true })
const selectStart = new Event('selectstart', { bubbles: true, cancelable: true })
act(() => void editor.dispatchEvent(dragStart))
act(() => void editor.dispatchEvent(selectStart))
expect(dragStart.defaultPrevented).toBe(true)
expect(selectStart.defaultPrevented).toBe(true)
act(
() =>
void window.dispatchEvent(
new PointerEvent('pointermove', { buttons: 1, cancelable: true, pointerId: 7, screenX: 301, screenY: 182 })
)
)
expect(moveBy).toHaveBeenCalledWith({ x: 1, y: 2, width: 620, height: 320 })
expect(document.activeElement).toBe(editor)
expect(selection.toString()).toBe('selected text')
})
})
+107 -19
View File
@@ -12,26 +12,61 @@ interface PressState {
armed: boolean
lastX: number
lastY: number
mode: 'control' | 'hold'
originH: number
originW: number
pointerId: number
startX: number
startY: number
target: HTMLElement
workspaceTransfer: boolean
}
interface HudComposerDragOptions {
/** X11 escape hatch: Ctrl+primary-button grabs immediately instead of
* competing with Chromium's text-selection drag until the hold timer. */
controlDrag?: boolean
/** X11/KWin only: keep the grabbed window visible while the user changes
* virtual desktops, then pin it to the destination desktop on release. */
workspaceTransfer?: boolean
}
function capturePointer(state: PressState): void {
try {
state.target.setPointerCapture?.(state.pointerId)
} catch {
// A renderer can reject capture after selection/native-drag bookkeeping.
// Window capture-phase listeners below still keep the in-window gesture
// alive, so a failed capture must not abort the drag altogether.
}
}
function releasePointer(state: PressState): void {
try {
if (state.target.hasPointerCapture?.(state.pointerId)) {
state.target.releasePointerCapture?.(state.pointerId)
}
} catch {
// Pointer cancellation may invalidate the id before React cleans up.
}
}
function setWorkspaceTransfer(transferring: boolean): void {
window.hermesDesktop?.hud?.setWorkspaceTransfer?.(transferring)
}
/**
* HUD-only: press and hold the composer, then drag to move the window.
* HUD-only: press and hold the composer, then drag to move the window. On X11,
* Ctrl+primary-button is an immediate grab that also works over selected text.
*
* The way to move the HUD on macOS/Windows. An `-webkit-app-region: drag`
* handle is the obvious alternative and cannot work THERE: the window manager
* takes a drag region's mouse input whole, which starves `useHudClickThrough`
* of the moves it decides solidity from, so the window is already transparent
* by the time the press lands and it falls through to the app behind. See
* click-through.ts. On Linux the composer bar itself is a native drag region
* instead (root drag + input no-drag), so this gesture is only the fallback
* for presses that land on the interactive surface — and a no-op for position
* on native Wayland, where the compositor owns placement.
* click-through.ts. Native Wayland uses a compositor drag region instead,
* because apps cannot place their own top-level surfaces there. X11 stays on
* this renderer path and additionally supports an immediate Ctrl-drag.
*
* Deltas are read in SCREEN coordinates. Client coordinates are relative to the
* window we are moving, so a window that keeps up with the cursor reports the
@@ -41,7 +76,10 @@ interface PressState {
* (see hermes:hud:move-by — a transparent frameless window drifts wider on
* Windows otherwise). Same shape as the pet overlay's drag.
*/
export function useHudComposerDrag(enabled: boolean) {
export function useHudComposerDrag(
enabled: boolean,
{ controlDrag = false, workspaceTransfer = false }: HudComposerDragOptions = {}
) {
const [grabbing, setGrabbing] = useState(false)
const stateRef = useRef<PressState | null>(null)
const timerRef = useRef<number | null>(null)
@@ -54,8 +92,12 @@ export function useHudComposerDrag(enabled: boolean) {
const state = stateRef.current
if (state?.target.hasPointerCapture(state.pointerId)) {
state.target.releasePointerCapture(state.pointerId)
if (state) {
if (state.workspaceTransfer) {
setWorkspaceTransfer(false)
}
releasePointer(state)
}
stateRef.current = null
@@ -69,23 +111,50 @@ export function useHudComposerDrag(enabled: boolean) {
}
const target = event.currentTarget
const immediate = controlDrag && event.ctrlKey
stateRef.current = {
armed: false,
// A press over an existing contentEditable selection otherwise starts
// Chromium's native text drag, which cancels our pointer stream. Cancel
// that default action before it is chosen; do not blur or rewrite the
// Selection, so the user's selected text survives moving the window.
if (immediate) {
event.preventDefault()
}
const state: PressState = {
armed: immediate,
lastX: event.screenX,
lastY: event.screenY,
mode: immediate ? 'control' : 'hold',
originH: window.outerHeight,
originW: window.outerWidth,
pointerId: event.pointerId,
startX: event.screenX,
startY: event.screenY,
target
target,
workspaceTransfer: false
}
stateRef.current = state
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current)
}
if (immediate) {
state.workspaceTransfer = workspaceTransfer
if (workspaceTransfer) {
setWorkspaceTransfer(true)
}
setGrabbing(true)
triggerHaptic('selection')
capturePointer(state)
return
}
timerRef.current = window.setTimeout(() => {
const state = stateRef.current
@@ -94,19 +163,25 @@ export function useHudComposerDrag(enabled: boolean) {
}
state.armed = true
state.workspaceTransfer = workspaceTransfer
if (workspaceTransfer) {
setWorkspaceTransfer(true)
}
setGrabbing(true)
triggerHaptic('selection')
// Capture so the moves keep arriving once the cursor outruns the bar,
// and drop the caret so the drag isn't also extending a selection.
state.target.setPointerCapture(state.pointerId)
capturePointer(state)
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
}, LONG_PRESS_MS)
},
[enabled]
[controlDrag, enabled, workspaceTransfer]
)
useEffect(() => {
@@ -163,14 +238,27 @@ export function useHudComposerDrag(enabled: boolean) {
reset()
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onUp)
const preventEditorGesture = (event: Event) => {
if (stateRef.current?.mode === 'control') {
event.preventDefault()
}
}
// Capture phase wins the race against contentEditable selection/drag
// handlers. `dragstart` is a second guard for an already-selected range;
// `selectstart` stops the same press from replacing that range.
window.addEventListener('pointermove', onMove, true)
window.addEventListener('pointerup', onUp, true)
window.addEventListener('pointercancel', onUp, true)
window.addEventListener('dragstart', preventEditorGesture, true)
window.addEventListener('selectstart', preventEditorGesture, true)
return () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
window.removeEventListener('pointercancel', onUp)
window.removeEventListener('pointermove', onMove, true)
window.removeEventListener('pointerup', onUp, true)
window.removeEventListener('pointercancel', onUp, true)
window.removeEventListener('dragstart', preventEditorGesture, true)
window.removeEventListener('selectstart', preventEditorGesture, true)
}
}, [enabled, reset])
+17 -15
View File
@@ -14,7 +14,7 @@ import { useHudGameOverlay } from './game-overlay'
import { useHudGlass } from './glass'
import { useHudGoto, useReportHudSession } from './handoff'
import { hudTranscriptHeight } from './layout'
import { useHudResizeHandle } from './resize-handle'
import { hudResizeDirections, useHudResizeHandle } from './resize-handle'
import { useHudThreadFocus } from './thread-focus'
/** How long the transcript lingers at its glanceable opacity — after a turn
@@ -372,11 +372,12 @@ export function HudShell() {
useHudClickThrough(rootRef)
useHudThreadFocus(rootRef)
// Corner resize handle. The window is created non-resizable so dragging can
// Edge/corner resize frame. The window is created non-resizable so dragging can
// never be misread as a resize gesture (the Windows transparent-frameless
// growth bug); the handle is the one sanctioned way to change size, driving
// the same flip-resizable-for-the-call pattern the pet overlay uses.
const { resizing: hudResizing, onPointerDown: onHudResizePointerDown } = useHudResizeHandle()
const resizeDirections = hudResizeDirections(window.hermesDesktop?.hud?.nativeDrag === true)
// Force the HOST layers transparent. index.html's pre-paint script writes an
// opaque themed background onto <html> as an INLINE style (the anti-white-
@@ -421,19 +422,20 @@ export function HudShell() {
<WiredPane part="chatRoutes" />
{/* The resize handle: bottom-right corner, the one sanctioned way to
change the HUD's size. Invisible chrome — a hot corner, not a
button — so it never reads as part of the surface. `data-hud-grabbing`
is the same flag the composer drag raises: a gesture in progress owns
the window, so click-through can't hand the mouse away mid-resize
when the growing edge outruns the cursor. */}
<div
aria-hidden
className="absolute bottom-0 right-0 z-20"
data-hud-grabbing={hudResizing ? '' : undefined}
data-hud-resize=""
onPointerDown={onHudResizePointerDown}
/>
{/* CanvasTTY-style resize frame. Windows/macOS/X11 get every edge and
corner; native Wayland gets the right/bottom handles it can honour
without forbidden global positioning. The handles are invisible
chrome with native cursors. `data-hud-grabbing` keeps click-through
from handing the pointer away while the window changes under it. */}
{resizeDirections.map(direction => (
<div
aria-hidden
data-hud-grabbing={hudResizing ? '' : undefined}
data-hud-resize={direction}
key={direction}
onPointerDown={event => onHudResizePointerDown(event, direction)}
/>
))}
</div>
)
}
@@ -0,0 +1,98 @@
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { HUD_RESIZE_DIRECTIONS, hudResizeBounds, hudResizeDirections, useHudResizeHandle } from './resize-handle'
const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }
const initialHermesDesktop = desktopWindow.hermesDesktop
const setBounds = vi.fn()
function setWindowBounds(x: number, y: number, width: number, height: number): void {
Object.defineProperty(window, 'screenX', { configurable: true, value: x })
Object.defineProperty(window, 'screenY', { configurable: true, value: y })
Object.defineProperty(window, 'outerWidth', { configurable: true, value: width })
Object.defineProperty(window, 'outerHeight', { configurable: true, value: height })
}
function resizeTarget(): HTMLElement {
const target = document.createElement('div')
target.setPointerCapture = vi.fn()
target.hasPointerCapture = vi.fn(() => false)
target.releasePointerCapture = vi.fn()
document.body.append(target)
return target
}
beforeEach(() => {
setBounds.mockClear()
setWindowBounds(100, 200, 620, 320)
desktopWindow.hermesDesktop = { hud: { setBounds } } as unknown as Window['hermesDesktop']
})
afterEach(() => {
document.body.innerHTML = ''
if (initialHermesDesktop) {
desktopWindow.hermesDesktop = initialHermesDesktop
} else {
delete desktopWindow.hermesDesktop
}
})
describe('hudResizeBounds', () => {
const origin = { x: 100, y: 200, width: 620, height: 320 }
it('resizes from every CanvasTTY edge and corner while preserving the opposite edges', () => {
expect(hudResizeBounds(origin, 'n', 40, 30)).toEqual({ x: 100, y: 230, width: 620, height: 290 })
expect(hudResizeBounds(origin, 'ne', 40, 30)).toEqual({ x: 100, y: 230, width: 660, height: 290 })
expect(hudResizeBounds(origin, 'e', 40, 30)).toEqual({ x: 100, y: 200, width: 660, height: 320 })
expect(hudResizeBounds(origin, 'se', 40, 30)).toEqual({ x: 100, y: 200, width: 660, height: 350 })
expect(hudResizeBounds(origin, 's', 40, 30)).toEqual({ x: 100, y: 200, width: 620, height: 350 })
expect(hudResizeBounds(origin, 'sw', 40, 30)).toEqual({ x: 140, y: 200, width: 580, height: 350 })
expect(hudResizeBounds(origin, 'w', 40, 30)).toEqual({ x: 140, y: 200, width: 580, height: 320 })
expect(hudResizeBounds(origin, 'nw', 40, 30)).toEqual({ x: 140, y: 230, width: 580, height: 290 })
})
it('clamps at the minimum without moving the opposite edge', () => {
expect(hudResizeBounds(origin, 'nw', 1000, 1000)).toEqual({ x: 340, y: 360, width: 380, height: 160 })
expect(hudResizeBounds(origin, 'se', -1000, -1000)).toEqual({ x: 100, y: 200, width: 380, height: 160 })
})
})
describe('hudResizeDirections', () => {
it('keeps every edge and corner on platforms with global window positioning', () => {
expect(hudResizeDirections(false)).toBe(HUD_RESIZE_DIRECTIONS)
})
it('exposes only position-preserving handles on native Wayland', () => {
expect(hudResizeDirections(true)).toEqual(['e', 'se', 's'])
})
})
describe('useHudResizeHandle', () => {
it('sends the selected edge geometry through the HUD bridge', () => {
const target = resizeTarget()
const { result } = renderHook(() => useHudResizeHandle())
act(() =>
result.current.onPointerDown(
{
button: 0,
currentTarget: target,
pointerId: 4,
preventDefault: vi.fn(),
screenX: 300,
screenY: 300,
stopPropagation: vi.fn()
} as never,
'nw'
)
)
act(() =>
void window.dispatchEvent(new PointerEvent('pointermove', { pointerId: 4, screenX: 250, screenY: 275 }))
)
expect(setBounds).toHaveBeenCalledWith({ x: 50, y: 175, width: 670, height: 345 })
})
})
+105 -21
View File
@@ -4,7 +4,27 @@ import { type PointerEvent as ReactPointerEvent, useCallback, useEffect, useRef,
const HUD_MIN_WIDTH = 380
const HUD_MIN_HEIGHT = 160
export const HUD_RESIZE_DIRECTIONS = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as const
export type HudResizeDirection = (typeof HUD_RESIZE_DIRECTIONS)[number]
const HUD_WAYLAND_RESIZE_DIRECTIONS = ['e', 'se', 's'] as const satisfies readonly HudResizeDirection[]
/** Native Wayland cannot read or change a top-level window's global x/y, so
* only edges that preserve the existing top-left position are truthful. */
export function hudResizeDirections(nativeDrag: boolean): readonly HudResizeDirection[] {
return nativeDrag ? HUD_WAYLAND_RESIZE_DIRECTIONS : HUD_RESIZE_DIRECTIONS
}
export interface HudResizeBounds {
height: number
width: number
x: number
y: number
}
interface ResizeState {
direction: HudResizeDirection
startX: number
startY: number
originX: number
@@ -12,10 +32,63 @@ interface ResizeState {
originW: number
originH: number
pointerId: number
target: HTMLElement
}
/** Resize one or two anchored edges while preserving every opposite edge. */
export function hudResizeBounds(
origin: HudResizeBounds,
direction: HudResizeDirection,
dx: number,
dy: number
): HudResizeBounds {
const right = origin.x + origin.width
const bottom = origin.y + origin.height
const west = direction.includes('w')
const east = direction.includes('e')
const north = direction.includes('n')
const south = direction.includes('s')
const width = west
? Math.max(HUD_MIN_WIDTH, origin.width - dx)
: east
? Math.max(HUD_MIN_WIDTH, origin.width + dx)
: origin.width
const height = north
? Math.max(HUD_MIN_HEIGHT, origin.height - dy)
: south
? Math.max(HUD_MIN_HEIGHT, origin.height + dy)
: origin.height
return {
x: west ? right - width : origin.x,
y: north ? bottom - height : origin.y,
width,
height
}
}
function capturePointer(state: ResizeState): void {
try {
state.target.setPointerCapture?.(state.pointerId)
} catch {
// Window capture-phase listeners below keep the in-window gesture alive.
}
}
function releasePointer(state: ResizeState): void {
try {
if (state.target.hasPointerCapture?.(state.pointerId)) {
state.target.releasePointerCapture?.(state.pointerId)
}
} catch {
// Pointer cancellation may invalidate the id before cleanup.
}
}
/**
* HUD-only: drag the corner handle to resize the window.
* HUD-only: drag any edge or corner handle to resize the window.
*
* The window is created `resizable: false` (see spawnHudWindow — a transparent
* frameless window must not expose a system resize hot-zone, or every drag
@@ -23,41 +96,50 @@ interface ResizeState {
* screen bounds and main flips resizable on for the setBounds call. Same
* pattern as the pet overlay's wheel-scale (`hermes:pet-overlay:set-bounds`).
*
* The top-left corner is anchored; only the bottom-right follows the pointer.
* Deltas are read in SCREEN coordinates, like the composer drag: client
* coordinates are relative to a window that is changing size, so they cannot
* be trusted mid-resize.
* Each handle preserves its opposite edge, matching ordinary desktop windows
* and CanvasTTY cards. Deltas are read in SCREEN coordinates, like the composer
* drag: client coordinates are relative to a window that is changing position
* and size, so they cannot be trusted mid-resize.
*/
export function useHudResizeHandle(): {
resizing: boolean
onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void
onPointerDown: (event: ReactPointerEvent<HTMLElement>, direction: HudResizeDirection) => void
} {
const [resizing, setResizing] = useState(false)
const stateRef = useRef<ResizeState | null>(null)
const reset = useCallback(() => {
const state = stateRef.current
if (state) {
releasePointer(state)
}
stateRef.current = null
setResizing(false)
}, [])
const onPointerDown = useCallback((event: ReactPointerEvent<HTMLElement>) => {
const onPointerDown = useCallback((event: ReactPointerEvent<HTMLElement>, direction: HudResizeDirection) => {
if (event.button !== 0) {
return
}
stateRef.current = {
direction,
startX: event.screenX,
startY: event.screenY,
originX: window.screenX,
originY: window.screenY,
originW: window.outerWidth,
originH: window.outerHeight,
pointerId: event.pointerId
pointerId: event.pointerId,
target: event.currentTarget
}
setResizing(true)
event.currentTarget.setPointerCapture(event.pointerId)
capturePointer(stateRef.current)
event.preventDefault()
event.stopPropagation()
}, [])
useEffect(() => {
@@ -73,12 +155,14 @@ export function useHudResizeHandle(): {
const dx = event.screenX - state.startX
const dy = event.screenY - state.startY
window.hermesDesktop?.hud?.setBounds?.({
x: state.originX,
y: state.originY,
width: Math.max(HUD_MIN_WIDTH, state.originW + dx),
height: Math.max(HUD_MIN_HEIGHT, state.originH + dy)
})
window.hermesDesktop?.hud?.setBounds?.(
hudResizeBounds(
{ x: state.originX, y: state.originY, width: state.originW, height: state.originH },
state.direction,
dx,
dy
)
)
}
const onUp = (event: PointerEvent) => {
@@ -91,14 +175,14 @@ export function useHudResizeHandle(): {
reset()
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onUp)
window.addEventListener('pointermove', onMove, true)
window.addEventListener('pointerup', onUp, true)
window.addEventListener('pointercancel', onUp, true)
return () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
window.removeEventListener('pointercancel', onUp)
window.removeEventListener('pointermove', onMove, true)
window.removeEventListener('pointerup', onUp, true)
window.removeEventListener('pointercancel', onUp, true)
}
}, [reset])
+2
View File
@@ -91,10 +91,12 @@ declare global {
// bar — so it mounts the real composer rather than a lookalike. Main
// owns the window; `onChanged` keeps every window's toggle truthful.
hud?: {
nativeDrag: boolean
open: (request?: { sessionId?: null | string; profile?: null | string }) => Promise<{ ok: boolean }>
close: () => Promise<{ ok: boolean }>
setIgnoreMouse: (ignore: boolean) => void
moveBy: (delta: { x: number; y: number; width: number; height: number }) => void
setWorkspaceTransfer?: (transferring: boolean) => void
setBounds: (bounds: { x: number; y: number; width: number; height: number }) => void
resetLayout: () => Promise<{ ok: boolean }>
setFrost: (showing: boolean) => Promise<{ ok: boolean }>
+81 -19
View File
@@ -3136,22 +3136,22 @@ button[data-slot='aui_msg-reactions'] svg {
--thread-viewport-height: 100%;
}
/* `-webkit-app-region: drag` in HUD mode is LINUX ONLY. The window manager
takes a draggable region's mouse input whole, so the page never sees the
/* `-webkit-app-region: drag` in HUD mode is NATIVE WAYLAND ONLY. The window
manager takes a draggable region's mouse input whole, so the page never sees the
cursor arrive there — on macOS/Windows that starves `useHudClickThrough`,
which decides solidity from exactly those moves, so the press falls through
to the app behind (every app-region attempt there was therefore unusable,
and left the HUD solid over dead space once you left it). On Linux the
and left the HUD solid over dead space once you left it). Native Wayland's
click-through decision is fed by MAIN's cursor poll (`startHudCursorFeed`),
not by page events, so a drag region cannot starve it: the bar stays solid,
the compositor takes the press, and the window moves natively
(xdg_toplevel.move on Wayland, _NET_WM_MOVERESIZE on X11). The composer's
interactive surface opts back out with `-webkit-app-region: no-drag` (input
element + the global button rule); the rest of the bar is the handle.
macOS/Windows keep dragging on `useHudComposerDrag` — press and hold the
bar, then move. */
not page events, and apps cannot position their own top-level surfaces, so
the compositor takes the press and moves the window with xdg_toplevel.move.
X11 deliberately keeps the renderer drag path: a Chromium drag region
intercepts the pointer stream needed by Ctrl+primary-button drag. The
composer's interactive surface opts out with `-webkit-app-region: no-drag`
(input element + global button rule); the rest of the bar is the handle.
macOS/Windows/X11 use `useHudComposerDrag` — press and hold, then move. */
/* Grip affordance for the Linux drag band: the composer's top padding (pt-4)
/* Grip affordance for the native Wayland drag band: the top padding (pt-4)
is the only surface the region owns once the input/buttons are carved out,
so make it look like a handle — a centered pill, like a mobile grip. */
.hud-native-drag::before {
@@ -3335,23 +3335,85 @@ button[data-slot='aui_msg-reactions'] svg {
Both problems were the placement, not the button: on the bar it is already
on our surface. */
/* The corner resize handle — a hot corner, not a button. The window is created
/* The resize frame — hot edges/corners, not buttons. The window is created
non-resizable (the transparent-frameless Windows drag-growth bug), so this
is the one sanctioned way to change the HUD's size; it drives
`hermes:hud:set-bounds`, which flips resizable on for the call.
Deliberately invisible chrome: no glyph, no border — the corner of the bar
reads as the affordance, and painting a handle on a surface that lives over
other apps would be a stray UI fragment. It opts in to pointer events the
same way every other HUD control does (the shell defaults to none). */
CanvasTTY grammar: four edge strips + four larger corner targets, each with
its native resize cursor and each preserving the opposite edge. Deliberately
invisible chrome: no glyph or border over whatever app is below the HUD. */
[data-hud-shell] [data-hud-resize] {
width: 1.25rem;
height: 1.25rem;
cursor: nwse-resize;
position: absolute;
z-index: 20;
pointer-events: auto;
touch-action: none;
}
[data-hud-shell] [data-hud-resize='n'] {
top: 0;
right: 1.25rem;
left: 1.25rem;
height: 0.625rem;
cursor: ns-resize;
}
[data-hud-shell] [data-hud-resize='e'] {
top: 1.25rem;
right: 0;
bottom: 1.25rem;
width: 0.625rem;
cursor: ew-resize;
}
[data-hud-shell] [data-hud-resize='s'] {
right: 1.25rem;
bottom: 0;
left: 1.25rem;
height: 0.625rem;
cursor: ns-resize;
}
[data-hud-shell] [data-hud-resize='w'] {
top: 1.25rem;
bottom: 1.25rem;
left: 0;
width: 0.625rem;
cursor: ew-resize;
}
[data-hud-shell] [data-hud-resize='ne'],
[data-hud-shell] [data-hud-resize='se'],
[data-hud-shell] [data-hud-resize='sw'],
[data-hud-shell] [data-hud-resize='nw'] {
width: 1.25rem;
height: 1.25rem;
}
[data-hud-shell] [data-hud-resize='ne'] {
top: 0;
right: 0;
cursor: nesw-resize;
}
[data-hud-shell] [data-hud-resize='se'] {
right: 0;
bottom: 0;
cursor: nwse-resize;
}
[data-hud-shell] [data-hud-resize='sw'] {
bottom: 0;
left: 0;
cursor: nesw-resize;
}
[data-hud-shell] [data-hud-resize='nw'] {
top: 0;
left: 0;
cursor: nwse-resize;
}
/* The composer's drop target is a full-window dashed sheet sized for the app's
chat column. In the HUD it is a white slab hanging under the bar on a fresh
thread, and there is nowhere to drop anything into a bar anyway. */
+2 -2
View File
@@ -131,8 +131,8 @@ Talk to Hermes and hear it back, the same [voice mode](./features/voice-mode.md)
**⌘/Ctrl+Shift+H** (or the titlebar button) detaches the chat into a chrome-free, always-on-top floating bar that sits over whatever you are working in. The app window steps aside; the HUD keeps your live conversation and a composer. Where you park it is context — the bar's position tells Hermes which app and screen you're asking about, so "this", "here", and "that page" resolve to what's underneath it.
- **Moving the bar** — on macOS and Windows, **press and hold** anywhere on the composer for a beat, then drag. A quick press still types; a held press grabs the window. On Linux the composer bar is a native window-manager drag handle (the compositor moves it — the only way that works on Wayland, where an app cannot place its own window).
- **Resizing** — drag the bottom-right corner of the bar.
- **Moving the bar** — on macOS and Windows, **press and hold** anywhere on the composer for a beat, then drag. On Linux/X11, hold **Ctrl** and drag with the primary mouse button for an immediate grab (including over selected text); press-and-hold remains available too. Keep the grab held while invoking your desktop switch shortcut to carry the HUD onto another virtual desktop. On native Wayland the composer bar is a compositor drag handle (the only way to move it, because an app cannot place its own window).
- **Resizing** — drag any edge or corner of the bar; the opposite edge stays anchored. Native Wayland exposes the right and bottom edges because the compositor does not allow apps to position top-level windows themselves.
- **Reset layout** — the discard control on the bar restores the default size and (on X11 / macOS / Windows) position. Use this if a persisted size leaves the HUD unusable.
- **Snap to pointer** — **⌘/Ctrl+Shift+G** (a global hotkey, works from any app) jumps the HUD to wherever your cursor is. On native Wayland this is a no-op — the compositor owns placement.
- **Exiting** — click the exit button on the bar, or press **⌘/Ctrl+Shift+H** again. The app window comes back with your session intact.