Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions src/renderer/src/features/settings/lib/settingsRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(<AgentViewModePickerModal open sessionId="agent" workspace={workspace} globalMode="terminal" onClose={() => {}} />)
expect(screen.getByText('Hermes has no native terminal; it always uses Agent Code rendering.')).toBeTruthy()
expect(screen.queryByText(/Choose OpenCode Terminal/)).toBeNull()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
6 changes: 5 additions & 1 deletion src/renderer/src/workspace/hook/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
64 changes: 64 additions & 0 deletions src/renderer/src/workspace/terminal/osc52Clipboard.test.ts
Original file line number Diff line number Diff line change
@@ -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()
})
})
100 changes: 100 additions & 0 deletions src/renderer/src/workspace/terminal/osc52Clipboard.ts
Original file line number Diff line number Diff line change
@@ -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;<selection>;<base64>\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 (`<selection>;<base64>`) 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<Terminal, 'parser'>,
writeClipboard: (text: string) => Promise<void> | 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
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
})
60 changes: 22 additions & 38 deletions src/renderer/src/workspace/tile-tree/AgentTerminalLeaf.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -180,6 +182,7 @@ export function AgentTerminalLeaf({
let fit: FitAddon | null = null
let webglRenderer: ReturnType<typeof attachXtermWebglRenderer> | null = null
let wheelBoundary: ReturnType<typeof attachTerminalWheelBoundary> | 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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -579,6 +585,7 @@ export function AgentTerminalLeaf({
if (resizeFrame !== null) cancelAnimationFrame(resizeFrame)
resizeObserver?.disconnect()
onDataDisposable?.dispose()
osc52Disposable?.dispose()
offFollowAttach?.()
offPtyData?.()
offTextPaste?.()
Expand Down Expand Up @@ -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 (
<div
data-pane-id={sessionId}
data-agent-terminal-leaf="true"
className={`
flex flex-col h-full min-h-0 min-w-0
border ${focused ? 'border-accent' : 'border-border'}
Expand Down Expand Up @@ -680,50 +690,24 @@ export function AgentTerminalLeaf({
statusMode={showStatusMode}
isSessionLive={isSessionLive}
completionUnseen={completionUnseen}
// `text-ink` lifts the surface name above the muted cwd on the plain
// strip. On the lit strip it inherits `accent-fg`, since ink is not
// guaranteed to contrast with a user-chosen accent.
// Clean provider display name (#1551): Terminal is now the default
// agent surface, so debug-sounding `raw ${provider}` + redundant
// `terminal view` chrome only adds noise on every pane header.
// `text-ink` lifts the provider name above the muted cwd on the plain
// strip; on the lit strip it inherits `accent-fg`.
badge={
<span className={`flex-shrink-0 ${statusLit ? '' : 'text-ink'}`}>
raw {provider}
{providerLabel}
</span>
}
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 ? (
<span
className={`text-[10px] font-code uppercase tracking-wider ${statusLit ? '' : 'text-accent'}`}
>
TAIL
</span>
) : 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 <provider>` 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. */}
<span className="hidden text-[10px] uppercase tracking-wider @min-[320px]:inline">
terminal view
tailActive ? (
<span
className={`text-[10px] font-code uppercase tracking-wider ${statusLit ? '' : 'text-accent'}`}
>
TAIL
</span>
</>
) : null
}
/>

Expand Down
Loading
Loading