diff --git a/src/renderer/src/features/settings/lib/settingsRegistry.ts b/src/renderer/src/features/settings/lib/settingsRegistry.ts index deedd9382..8c97fc1fe 100644 --- a/src/renderer/src/features/settings/lib/settingsRegistry.ts +++ b/src/renderer/src/features/settings/lib/settingsRegistry.ts @@ -562,13 +562,16 @@ export function getSettingsRegistry( // respect, not a single command's preference. Commands only declare // whether they require a rendered feed; the central display policy turns // that into "available, disabled, or temporarily render in hybrid." + // + // Inherits DEFAULT_SETTING_METADATA (`apply: 'immediate'`): live panes + // without a per-session override switch surface immediately when the + // global mode changes. id: 'agent-view-mode', category: 'workspace', title: 'Agent View Mode', description: - 'Choose whether Claude and Codex panes show Agent Code rendering, the provider terminal, or terminal-first Hybrid mode that renders only while a feature needs the feed.', + 'Choose whether PTY-backed agent panes (Claude, Codex, Grok) show the provider terminal, Agent Code rendering, or terminal-first Hybrid mode that renders only while a feature needs the feed. Terminal-only providers (OpenCode Terminal, Pi) always use their native terminal; structured-only providers (OpenCode, Hermes, Antigravity) always use Agent Code rendering.', keywords: ['agent', 'view', 'mode', 'terminal', 'raw', 'hybrid', 'renderer', 'feed', 'tui'], - metadata: { scope: 'app', apply: 'new-session', storage: 'settings' }, control: { type: 'select', getValue: settings => settings.agentViewMode, @@ -628,7 +631,7 @@ export function getSettingsRegistry( id: 'worktree-badges', category: 'workspace', title: 'Worktree Badges', - description: 'Show the inferred git worktree or branch for each agent pane above the composer.', + description: 'Show the inferred git worktree or branch for each agent pane above the composer. (Agent view only.)', keywords: ['worktree', 'branch', 'badge', 'git', 'agent'], control: { type: 'toggle', @@ -690,7 +693,7 @@ export function getSettingsRegistry( category: 'workspace', title: 'Auto-send Prompt Suggestions', description: - 'When on, clicking a prompt-suggestion chip sends it immediately as the next prompt. When off, clicking only fills the composer so you can edit it first. On by default.', + 'When on, clicking a prompt-suggestion chip sends it immediately as the next prompt. When off, clicking only fills the composer so you can edit it first. Off by default. Applies in Agent/Hybrid view.', keywords: ['prompt', 'suggestion', 'chip', 'autosend', 'send', 'composer', 'next prompt'], control: { type: 'toggle', @@ -943,8 +946,8 @@ export function getSettingsRegistry( category: 'dictation', title: 'Inline Dictation', description: - 'Show a voice control inside each composer and insert transcripts as editable draft text.', - keywords: ['voice', 'dictation', 'speech', 'stt', 'composer', 'microphone'], + 'Enable voice dictation in composers and terminal panes. Shows a voice control inside each composer and inserts transcripts as editable draft text or terminal input.', + keywords: ['voice', 'dictation', 'speech', 'stt', 'composer', 'terminal', 'microphone'], control: { type: 'toggle', getValue: settings => settings.dictationEnabled, @@ -1144,7 +1147,7 @@ export function getSettingsRegistry( title: 'Providers', description: 'Choose which coding agents Agent Code offers. Detected CLIs start on; turning a provider off hides it from pickers, switching, and usage — running sessions keep running. Reset returns a provider to detection.', - keywords: ['provider', 'providers', 'enable', 'disable', 'claude', 'codex', 'opencode', 'grok', 'pi', 'antigravity', 'hermes', 'antigravity', 'usage', 'hide'], + keywords: ['provider', 'providers', 'enable', 'disable', 'claude', 'codex', 'opencode', 'grok', 'pi', 'antigravity', 'hermes', 'usage', 'hide'], // Main's setup.json is the truth (storage: 'setup'); the row mirrors it. metadata: { scope: 'app', apply: 'new-session', storage: 'setup' }, control: { type: 'providers-enablement' }, diff --git a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx index eb28f6de5..46f891140 100644 --- a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx +++ b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.renderer.test.tsx @@ -42,4 +42,14 @@ describe('Agent View Mode picker', () => { fireEvent.click(apply) expect(setSessionAgentViewModeOverride).toHaveBeenCalledWith('agent', 'agent') }) + + it('uses provider-specific copy rather than OpenCode-only copy for Antigravity and Hermes panes', () => { + const workspace = { + state: { sessions: { agent: { cwd: '/repo', kind: 'hermes', projectId: 'tab', joinedAt: 0 } } }, + setSessionAgentViewModeOverride: vi.fn(() => true), + } as unknown as Workspace + render( {}} />) + expect(screen.getByText('Hermes has no native terminal; it always uses Agent Code rendering.')).toBeTruthy() + expect(screen.queryByText(/Choose OpenCode Terminal/)).toBeNull() + }) }) diff --git a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx index 386645c24..4024350a1 100644 --- a/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx +++ b/src/renderer/src/features/workspace/ui/AgentViewModePickerModal.tsx @@ -73,12 +73,14 @@ export function AgentViewModePickerModal({ value: 'terminal', label: 'Terminal', description: nativeUnavailable - ? 'Choose OpenCode Terminal when creating an agent; this structured session has no PTY.' + ? kind === 'opencode' + ? 'Choose OpenCode Terminal when creating an agent; this structured session has no PTY.' + : `${provider.name} has no native terminal; it always uses Agent Code rendering.` : 'Always show the provider native terminal for this session.', disabled: nativeUnavailable, }, ], - [globalMode, nativeUnavailable, terminalRuntime], + [globalMode, kind, nativeUnavailable, provider.name, terminalRuntime], ) const pick = (value: PickerValue) => { diff --git a/src/renderer/src/workspace/hook/index.ts b/src/renderer/src/workspace/hook/index.ts index 326dcf775..548234e8b 100644 --- a/src/renderer/src/workspace/hook/index.ts +++ b/src/renderer/src/workspace/hook/index.ts @@ -179,7 +179,11 @@ export function useWorkspace( // future native-mode work to distinguish "real user override" from // "stale impossible override." Reject it at the write boundary; the // display-policy pin remains the read-side safety net. - showToast('Choose OpenCode Terminal when creating the agent to use the native TUI') + showToast( + kind === 'opencode' + ? 'Choose OpenCode Terminal when creating the agent to use the native TUI' + : `${providerChoiceLabel(kind)} has no native terminal; it always uses Agent Code rendering.`, + ) return false } if (effectiveProviderRuntime(kind, meta.providerRuntime) === 'terminal' && override === 'agent') { diff --git a/src/renderer/src/workspace/terminal/osc52Clipboard.test.ts b/src/renderer/src/workspace/terminal/osc52Clipboard.test.ts new file mode 100644 index 000000000..f5a2f4fb8 --- /dev/null +++ b/src/renderer/src/workspace/terminal/osc52Clipboard.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest' + +import { + attachOsc52ClipboardHandler, + parseOsc52ClipboardWrite, +} from '@renderer/workspace/terminal/osc52Clipboard' + +describe('OSC 52 write-only clipboard handler', () => { + it('decodes valid UTF-8 base64 payloads and writes to the clipboard', () => { + let registeredCallback: ((data: string) => boolean) | null = null + const dispose = vi.fn() + const term = { + parser: { + registerOscHandler: vi.fn((ident: number, cb: (data: string) => boolean) => { + expect(ident).toBe(52) + registeredCallback = cb + return { dispose } + }), + }, + } + const writeClipboard = vi.fn() + + const handle = attachOsc52ClipboardHandler(term as never, writeClipboard) + expect(registeredCallback).not.toBeNull() + + // "hello — 世界" encoded as UTF-8 base64. + const payload = Buffer.from('hello — 世界', 'utf8').toString('base64') + expect(registeredCallback!(`c;${payload}`)).toBe(true) + expect(writeClipboard).toHaveBeenCalledTimes(1) + expect(writeClipboard).toHaveBeenCalledWith('hello — 世界') + + handle.dispose() + expect(dispose).toHaveBeenCalledTimes(1) + }) + + it('ignores clipboard read queries (?) without touching the clipboard', () => { + let registeredCallback: ((data: string) => boolean) | null = null + const term = { + parser: { + registerOscHandler: (_ident: number, cb: (data: string) => boolean) => { + registeredCallback = cb + return { dispose: () => {} } + }, + }, + } + const writeClipboard = vi.fn() + + attachOsc52ClipboardHandler(term as never, writeClipboard) + + // Both `c;?` and `;?` are standard OSC 52 read queries. + expect(registeredCallback!('c;?')).toBe(true) + expect(registeredCallback!(';?')).toBe(true) + expect(writeClipboard).not.toHaveBeenCalled() + }) + + it('rejects malformed, empty, or oversized (> 1 MiB) payloads', () => { + expect(parseOsc52ClipboardWrite('no-semicolon')).toBeNull() + expect(parseOsc52ClipboardWrite('c;')).toBeNull() + expect(parseOsc52ClipboardWrite('c;%%%not-base64%%%')).toBeNull() + + const oversized = Buffer.alloc(1024 * 1024 + 1, 0x61).toString('base64') + expect(parseOsc52ClipboardWrite(`c;${oversized}`)).toBeNull() + }) +}) diff --git a/src/renderer/src/workspace/terminal/osc52Clipboard.ts b/src/renderer/src/workspace/terminal/osc52Clipboard.ts new file mode 100644 index 000000000..a739bf0bd --- /dev/null +++ b/src/renderer/src/workspace/terminal/osc52Clipboard.ts @@ -0,0 +1,100 @@ +import type { Terminal } from '@xterm/xterm' + +/** + * Write-only OSC 52 clipboard handler for xterm.js panes. + * + * WHY this exists (#1551): + * Agent Code enables `tmux mouse on` so trackpad scrolling works naturally in + * Terminal-default panes. Under tmux mouse mode, dragging to select text + * triggers tmux's copy-mode, which copies to the host clipboard by emitting an + * OSC 52 escape sequence (`\x1b]52;;\x07`). Without an + * xterm OSC 52 handler, xterm silently drops the sequence and mouse-drag copy + * never reaches the macOS clipboard. + * + * WHY write-only (ignoring `?` read queries): + * OSC 52 also defines a clipboard-read query (`\x1b]52;c;?\x07`) where a + * terminal replies with the user's current clipboard contents. Answering read + * queries would let any untrusted process or remote SSH session running inside + * a pane silently exfiltrate passwords or secrets from the macOS clipboard. + * Returning `true` on `?` consumes the query cleanly without touching the + * clipboard or replying to the PTY. + * + * WHY a 1 MiB cap: + * A runaway or malicious escape sequence carrying tens of megabytes of base64 + * would stall the renderer during `atob` / UTF-8 decoding. 1 MiB covers every + * realistic terminal selection while keeping decoding bounded. + */ + +const MAX_OSC52_DECODED_BYTES = 1024 * 1024 +// Base64 expands 3 bytes into 4 chars; add a small slack for optional padding +// and line-wrapping before rejecting without decoding. +const MAX_OSC52_BASE64_CHARS = Math.ceil((MAX_OSC52_DECODED_BYTES * 4) / 3) + 64 +// Guard the raw string BEFORE regex whitespace stripping so an adversarial +// multi-megabyte whitespace-padded sequence is rejected in O(1) without +// allocating a stripped copy. +const MAX_OSC52_RAW_PAYLOAD_CHARS = MAX_OSC52_BASE64_CHARS * 2 + +type Disposable = { dispose(): void } + +/** + * Parses an xterm OSC 52 payload (`;`) into UTF-8 text. + * Returns `null` for clipboard read queries (`?`), malformed parameters, + * oversized payloads, or invalid base64. + */ +export function parseOsc52ClipboardWrite(data: string): string | null { + const separator = data.indexOf(';') + if (separator === -1) return null + + const payload = data.slice(separator + 1) + // Ignore clipboard read queries (`?`) for security — never expose host + // clipboard contents back to the PTY. + if (payload === '?' || payload.length === 0 || payload.length > MAX_OSC52_RAW_PAYLOAD_CHARS) { + return null + } + + // Strip ASCII whitespace that some multiplexers insert when wrapping long + // base64 payloads, then enforce the size cap before allocating a decoded + // buffer. + const compact = payload.replace(/\s+/g, '') + if (compact.length === 0 || compact.length > MAX_OSC52_BASE64_CHARS) return null + + try { + const binary = atob(compact) + if (binary.length > MAX_OSC52_DECODED_BYTES) return null + const bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i += 1) { + bytes[i] = binary.charCodeAt(i) + } + return new TextDecoder('utf-8', { fatal: false }).decode(bytes) + } catch { + return null + } +} + +/** + * Registers a write-only OSC 52 clipboard handler on an xterm.js `Terminal`. + * + * Tolerates minimal test doubles that omit `term.parser` so unrelated leaf + * tests do not need to mock xterm's parser internals. + */ +export function attachOsc52ClipboardHandler( + term: Pick, + writeClipboard: (text: string) => Promise | void = text => + navigator.clipboard?.writeText(text), +): Disposable { + if (!term.parser || typeof term.parser.registerOscHandler !== 'function') { + return { dispose() {} } + } + + return term.parser.registerOscHandler(52, data => { + const text = parseOsc52ClipboardWrite(data) + if (text === null) return true + try { + void Promise.resolve(writeClipboard(text)).catch(() => undefined) + } catch { + // Clipboard writes can be rejected in unfocused or headless contexts; + // swallow so an OSC 52 sequence never surfaces as an uncaught error. + } + return true + }) +} diff --git a/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.statusHeader.renderer.test.tsx b/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.statusHeader.renderer.test.tsx index 27601a80c..f95ed18a8 100644 --- a/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.statusHeader.renderer.test.tsx +++ b/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.statusHeader.renderer.test.tsx @@ -255,7 +255,10 @@ describe('terminal-view status header wiring', () => { // draws a PaneHeader with `data-status-lit`, so without this a routing // change could pass the assertion below without touching the wiring // under test. - expect(screen.getByText('raw claude')).toBeTruthy() + expect(container.querySelector('[data-agent-terminal-leaf="true"]')).not.toBeNull() + expect(screen.getByText('Claude Code')).toBeTruthy() + expect(screen.queryByText('raw claude')).toBeNull() + expect(screen.queryByText('terminal view')).toBeNull() expect(statusRow(container).getAttribute('data-status-lit')).toBe(String(showStatusMode)) }) }) diff --git a/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.tsx b/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.tsx index 8e4e356db..f86701619 100644 --- a/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.tsx +++ b/src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.tsx @@ -24,12 +24,14 @@ import { useComposerDictation } from '@renderer/workspace/tile-tree/TileLeaf/use import { useAgentTerminalDimensionActive, useAgentTerminalOwnerVisible } from '@renderer/workspace/terminal/AgentTerminalOwnership' import { subscribeToAgentPtyData } from '@renderer/workspace/terminal/sessionDataDispatcher' import { attachXtermWebglRenderer } from '@renderer/workspace/terminal/xtermWebglRenderer' +import { attachOsc52ClipboardHandler } from '@renderer/workspace/terminal/osc52Clipboard' import { attachTerminalWheelBoundary } from '@renderer/workspace/terminal/terminalWheelBoundary' import { createTerminalInputForwarder } from '@renderer/workspace/tile-tree/terminalInputForwarder' import { encodeTerminalPaste, registerTerminalPasteTarget } from '@renderer/workspace/terminal/textPasteTarget' import { AgentTerminalActions } from '@renderer/workspace/tile-tree/AgentTerminalActions' import { useTerminalFollow } from '@renderer/workspace/tile-tree/terminalFollow' import type { AgentProviderKind } from '@shared/types/providerKind' +import { getRendererProviderCapabilities } from '@providers/registry.renderer.capabilities' type Props = { sessionId: SessionId @@ -180,6 +182,7 @@ export function AgentTerminalLeaf({ let fit: FitAddon | null = null let webglRenderer: ReturnType | null = null let wheelBoundary: ReturnType | null = null + let osc52Disposable: { dispose(): void } | null = null let onDataDisposable: { dispose(): void } | null = null let offPtyData: (() => void) | null = null // Nullable like the disposables above: xterm init can throw before the @@ -303,6 +306,9 @@ export function AgentTerminalLeaf({ fit = new FitAddon() term.loadAddon(fit) term.open(container) + // Write-only OSC 52 clipboard support so tmux mouse-drag selections copy + // to the macOS clipboard without exposing clipboard reads to the PTY. + osc52Disposable = attachOsc52ClipboardHandler(term) // Host-level, after open(): bubbles after every xterm wheel listener so // xterm keeps first refusal — see terminalWheelBoundary.ts. wheelBoundary = attachTerminalWheelBoundary(container) @@ -579,6 +585,7 @@ export function AgentTerminalLeaf({ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame) resizeObserver?.disconnect() onDataDisposable?.dispose() + osc52Disposable?.dispose() offFollowAttach?.() offPtyData?.() offTextPaste?.() @@ -634,9 +641,12 @@ export function AgentTerminalLeaf({ // below can never disagree with the fill they sit on. const statusLit = paneHeaderStatusLit(showStatusMode, isSessionLive) + const providerLabel = getRendererProviderCapabilities(provider).name + return (
- raw {provider} + {providerLabel} } trailing={ - <> - {/* TAIL pill styling copied from ScrollIndicator so both surfaces - read identically — without it the raw view silently follows - output while showing no state the palette can be checked - against. The one exception is the lit strip: `text-accent` on - `bg-accent` makes TAIL invisible exactly when the agent is - producing the output being followed, so it inherits - `accent-fg` there. */} - {tailActive ? ( - - TAIL - - ) : null} - {/* No color of its own: it inherits the row's `text-muted`, or - `accent-fg` on the lit strip. - - Hidden below 320px of header text room (PaneHeader's label - group is the `@container`, so the flag's quarter is already - subtracted). `raw ` already names this surface, so - the label is the one piece of chrome that can go without losing - information. Without this, a flagged Tiled Dispatch lane - (~250px) had more fixed-width text than room, and the label - slid under the flag with TAIL next. - - The threshold covers the fixed row content with every piece - shown, measured at the 10px code font: pane label chip - (~26px), `raw opencode` (~72px), TAIL (~26px), this label - (~76px) and the gaps, about 236px, plus roughly 80px so the cwd - keeps a readable tail. */} - - terminal view + tailActive ? ( + + TAIL - + ) : null } /> diff --git a/src/renderer/src/workspace/tile-tree/TerminalLeaf.tsx b/src/renderer/src/workspace/tile-tree/TerminalLeaf.tsx index 67a718cea..838eda28e 100644 --- a/src/renderer/src/workspace/tile-tree/TerminalLeaf.tsx +++ b/src/renderer/src/workspace/tile-tree/TerminalLeaf.tsx @@ -19,6 +19,7 @@ import { createTerminalInputForwarder } from '@renderer/workspace/tile-tree/term import { encodeTerminalPaste, registerTerminalPasteTarget } from '@renderer/workspace/terminal/textPasteTarget' import { subscribeToTerminalData } from '@renderer/workspace/terminal/sessionDataDispatcher' import { attachXtermWebglRenderer } from '@renderer/workspace/terminal/xtermWebglRenderer' +import { attachOsc52ClipboardHandler } from '@renderer/workspace/terminal/osc52Clipboard' import { isEngagementKeydown } from '@renderer/workspace/tile-tree/engagementKeydown' import { attachTerminalWheelBoundary } from '@renderer/workspace/terminal/terminalWheelBoundary' import { PaneHeader } from '@renderer/workspace/tile-tree/TileLeaf/PaneHeader' @@ -159,8 +160,11 @@ export function TerminalLeaf({ // The xterm instance itself. Kept in a ref so the effects below // can access it without triggering re-renders on every data tick. const termRef = useRef(null) - const focusedRef = useRef(focused) - focusedRef.current = focused + // Mirror AgentTerminalLeaf (#1493 / #1551): the keyboard region joins + // `focused` for input/paste ownership so a shell lane stops capturing focus + // or paste events while the Sidekick panel owns keyboard focus. + const focusedRef = useRef(focused && regionActive) + focusedRef.current = focused && regionActive // Session metadata and activity as PRIMITIVE selectors (#865). This leaf // deliberately never takes the runtime as a prop: the xterm owns its output // path, and a runtime prop would re-render the leaf on every PTY chunk. Each @@ -217,6 +221,7 @@ export function TerminalLeaf({ let fit: FitAddon | null = null let webglRenderer: ReturnType | null = null let wheelBoundary: ReturnType | null = null + let osc52Disposable: { dispose(): void } | null = null let onDataDisposable: { dispose(): void } | null = null let offUserInput: (() => void) | null = null let offTerminalData: (() => void) | null = null @@ -341,6 +346,9 @@ export function TerminalLeaf({ fit = new FitAddon() term.loadAddon(fit) term.open(container) + // Write-only OSC 52 clipboard support so tmux mouse-drag selections copy + // to the macOS clipboard without exposing clipboard reads to the PTY. + osc52Disposable = attachOsc52ClipboardHandler(term) // Host-level, after open(): bubbles after every xterm wheel listener so // xterm keeps first refusal — see terminalWheelBoundary.ts. wheelBoundary = attachTerminalWheelBoundary(container) @@ -588,6 +596,7 @@ export function TerminalLeaf({ if (resizeFrame !== null) cancelAnimationFrame(resizeFrame) resizeObserver?.disconnect() onDataDisposable?.dispose() + osc52Disposable?.dispose() offTerminalData?.() offFollowAttach?.() offTextPaste?.() @@ -618,15 +627,17 @@ export function TerminalLeaf({ // focused at the workspace level. For that we have the // synchronous `focusTerminal()` handler below, wired into the // outer div's onMouseDown. - const prevFocusedRef = useRef(focused) + const prevFocusedRef = useRef(focused && regionActive) useEffect(() => { - const focusChanged = prevFocusedRef.current !== focused - prevFocusedRef.current = focused - if (!focused || !ownerVisible) return + const activeFocus = focused && regionActive + const focusChanged = prevFocusedRef.current !== activeFocus + prevFocusedRef.current = activeFocus + if (!activeFocus || !ownerVisible) return // On a reveal only take an unowned focus (see focusIsUnowned): editor- - // fullscreen exit must leave the caret in Monaco. + // fullscreen exit must leave the caret in Monaco, and Sidekick must keep + // keyboard focus while regionActive is false. if (focusChanged || focusIsUnowned()) termRef.current?.focus() - }, [focused, ownerVisible]) + }, [focused, regionActive, ownerVisible]) // Imperative re-focus. Called from outer-div mousedown so that // ANY click inside the terminal pane re-focuses xterm's helper