feat(native-chat): per-leaf toggle eligibility + composer UX (paste, draft, scrollbar, focus) (#6783)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -7,13 +7,16 @@ import {
|
||||
useRef,
|
||||
useState
|
||||
} from 'react'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { useAppStore } from '../../store'
|
||||
import type { AgentType } from '../../../../shared/agent-status-types'
|
||||
import { NATIVE_FILE_DROP_TARGET } from '../../../../shared/native-file-drop'
|
||||
import { sendRuntimePtyInput } from '@/runtime/runtime-terminal-inspection'
|
||||
import { getSettingsForAgentTabRuntimeOwner } from '@/lib/agent-paste-draft'
|
||||
import { sendNativeChatMessage, submitNativeChatPrompt } from './native-chat-runtime-send'
|
||||
import {
|
||||
sendNativeChatMessage,
|
||||
sendNativeChatMessageWithImageAttachments,
|
||||
submitNativeChatPrompt
|
||||
} from './native-chat-runtime-send'
|
||||
import { getAgentSlashCommands } from './native-chat-agent-commands'
|
||||
import { emitNativeChatMessageSent } from '@/lib/native-chat-telemetry'
|
||||
import {
|
||||
@@ -28,7 +31,8 @@ import {
|
||||
type HistoryState,
|
||||
type SlashCommandSuggestion
|
||||
} from './native-chat-composer-state'
|
||||
import { resolveImagePaste } from './native-chat-image-paste'
|
||||
import { readNativeChatDraftCache } from './native-chat-draft-cache'
|
||||
import { useNativeChatDraft } from './use-native-chat-draft'
|
||||
import { NativeChatComposerField } from './NativeChatComposerField'
|
||||
import {
|
||||
nativeChatComposerTargetIsRemote,
|
||||
@@ -36,6 +40,7 @@ import {
|
||||
} from './native-chat-composer-target'
|
||||
import { useNativeChatSkills } from './use-native-chat-skills'
|
||||
import { useNativeChatComposerAttachments } from './use-native-chat-composer-attachments'
|
||||
import { useNativeChatComposerPaste } from './use-native-chat-composer-paste'
|
||||
import { dispatchDictationControl } from '../dictation/dictation-control-events'
|
||||
import { useNativeChatComposerKeyDown } from './use-native-chat-composer-keydown'
|
||||
|
||||
@@ -74,6 +79,17 @@ export type NativeChatComposerProps = {
|
||||
export type NativeChatComposerHandle = {
|
||||
focus: () => boolean
|
||||
insertTypedText: (text: string) => boolean
|
||||
/** Handle a paste event captured at the pane root (the OS frequently
|
||||
* retargets the paste off the focused textarea, so its own onPaste can't be
|
||||
* relied on). An image is intercepted and attached; text falls through. */
|
||||
handlePasteEvent: (event: {
|
||||
clipboardData: DataTransfer | null
|
||||
preventDefault: () => void
|
||||
defaultPrevented: boolean
|
||||
}) => void
|
||||
/** Paste the clipboard into the composer with no event in hand (menu paste):
|
||||
* an image becomes an attachment, otherwise text is inserted at the caret. */
|
||||
pasteFromClipboard: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,8 +114,11 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
},
|
||||
ref
|
||||
): React.JSX.Element {
|
||||
const [draft, setDraft] = useState('')
|
||||
const [caret, setCaret] = useState(0)
|
||||
// Scope key shared with image attachments so an unsent draft + its attached
|
||||
// images survive the composer unmounting on a TUI/GUI toggle.
|
||||
const draftScopeKey = targetPtyId ?? terminalTabId
|
||||
const { draft, setDraft } = useNativeChatDraft(draftScopeKey)
|
||||
const [caret, setCaret] = useState(draft.length)
|
||||
const [history, setHistory] = useState<HistoryState>(EMPTY_HISTORY)
|
||||
const [activeSuggestion, setActiveSuggestion] = useState(0)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
@@ -116,6 +135,15 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
dictationState === 'listening' ||
|
||||
dictationState === 'stopping'
|
||||
|
||||
// Place the caret at the end of the (possibly restored) draft when the
|
||||
// composer is reused for a different pane. Adjusted during render (matching
|
||||
// the draft reload) so caret and text stay consistent on the first paint.
|
||||
const lastDraftScopeKey = useRef(draftScopeKey)
|
||||
if (lastDraftScopeKey.current !== draftScopeKey) {
|
||||
lastDraftScopeKey.current = draftScopeKey
|
||||
setCaret(readNativeChatDraftCache(draftScopeKey).length)
|
||||
}
|
||||
|
||||
const agentCommands = useMemo(() => getAgentSlashCommands(agent), [agent])
|
||||
const autocomplete = useMemo(
|
||||
() =>
|
||||
@@ -173,7 +201,7 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
})
|
||||
return true
|
||||
},
|
||||
[caret, draft]
|
||||
[caret, draft, setDraft]
|
||||
)
|
||||
|
||||
const focus = useCallback((): boolean => {
|
||||
@@ -185,7 +213,21 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
return true
|
||||
}, [])
|
||||
|
||||
useImperativeHandle(ref, () => ({ focus, insertTypedText }), [focus, insertTypedText])
|
||||
const { handlePaste, pasteFromClipboard } = useNativeChatComposerPaste({
|
||||
agent,
|
||||
disabled,
|
||||
caret,
|
||||
attachLocalPaths,
|
||||
insertTypedText,
|
||||
setCaret,
|
||||
setNotice
|
||||
})
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({ focus, insertTypedText, handlePasteEvent: handlePaste, pasteFromClipboard }),
|
||||
[focus, insertTypedText, handlePaste, pasteFromClipboard]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
return window.api.ui.onFileDrop((payload) => {
|
||||
@@ -236,17 +278,24 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
if (!target) {
|
||||
return
|
||||
}
|
||||
// Images are pasted into the hosted TUI as soon as they are attached, so the
|
||||
// Send action only submits the text body (if any) plus Enter.
|
||||
if (text.trim().length > 0) {
|
||||
// Slash commands are TUI controls, not chat turns — never attach images to
|
||||
// one (the chat turn is suppressed below, so the images would leak into the
|
||||
// runtime with no visible message). Otherwise images are deferred to submit
|
||||
// (like text) so the GUI chips and TUI input stay in sync and removing a
|
||||
// chip needs no TUI un-paste: send images, then text, then Enter atomically.
|
||||
const isSlashCommand = isSlashCommandDraft(text)
|
||||
if (isSlashCommand) {
|
||||
sendNativeChatMessage(target.settings, target.ptyId, text)
|
||||
} else if (imagePaths.length > 0) {
|
||||
sendNativeChatMessageWithImageAttachments(target.settings, target.ptyId, text, imagePaths)
|
||||
} else if (text.trim().length > 0) {
|
||||
sendNativeChatMessage(target.settings, target.ptyId, text)
|
||||
} else {
|
||||
submitNativeChatPrompt(target.settings, target.ptyId)
|
||||
}
|
||||
// Slash commands are TUI controls, not chat turns: don't echo a user bubble,
|
||||
// but DO surface a small "Ran /clear" system line so the command leaves a
|
||||
// visible trace instead of seeming to do nothing.
|
||||
if (isSlashCommandDraft(text)) {
|
||||
// Slash commands don't echo a user bubble, but DO surface a small
|
||||
// "Ran /clear" system line so the command leaves a visible trace.
|
||||
if (isSlashCommand) {
|
||||
onSlashCommand?.(text.trim())
|
||||
} else {
|
||||
onOptimisticSend?.(text, imagePaths)
|
||||
@@ -270,7 +319,8 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
disabled,
|
||||
resolveTarget,
|
||||
onOptimisticSend,
|
||||
onSlashCommand
|
||||
onSlashCommand,
|
||||
setDraft
|
||||
])
|
||||
|
||||
const interrupt = useCallback(() => {
|
||||
@@ -285,13 +335,16 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
sendRuntimePtyInput(target.settings, target.ptyId, ESC)
|
||||
}, [isWorking, onStop, resolveTarget])
|
||||
|
||||
const chooseSlash = useCallback((command: SlashCommandSuggestion) => {
|
||||
const next = applySlashSuggestion(command)
|
||||
setDraft(next)
|
||||
setCaret(next.length)
|
||||
setActiveSuggestion(0)
|
||||
textareaRef.current?.focus()
|
||||
}, [])
|
||||
const chooseSlash = useCallback(
|
||||
(command: SlashCommandSuggestion) => {
|
||||
const next = applySlashSuggestion(command)
|
||||
setDraft(next)
|
||||
setCaret(next.length)
|
||||
setActiveSuggestion(0)
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
[setDraft]
|
||||
)
|
||||
|
||||
const dispatchSlash = useCallback(
|
||||
(command: SlashCommandSuggestion) => {
|
||||
@@ -314,42 +367,7 @@ export const NativeChatComposer = forwardRef<NativeChatComposerHandle, NativeCha
|
||||
setActiveSuggestion(0)
|
||||
setNotice(null)
|
||||
},
|
||||
[agent, disabled, resolveTarget, onSlashCommand]
|
||||
)
|
||||
|
||||
const handlePaste = useCallback(
|
||||
(event: React.ClipboardEvent<HTMLTextAreaElement>) => {
|
||||
const hasImage = Array.from(event.clipboardData.items).some((item) =>
|
||||
item.type.startsWith('image/')
|
||||
)
|
||||
if (!hasImage) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
// Why: snapshot the caret before the async temp-file round-trip — `caret`
|
||||
// state can move (further typing/selection) while the await is in flight.
|
||||
const caretAtPaste = caret
|
||||
void (async () => {
|
||||
const tempPath = await window.api.ui.saveClipboardImageAsTempFile()
|
||||
if (!tempPath) {
|
||||
return
|
||||
}
|
||||
const result = resolveImagePaste(agent, tempPath)
|
||||
if (result.kind === 'unsupported') {
|
||||
setNotice(
|
||||
translate(
|
||||
'components.native-chat.composer.imageUnsupported',
|
||||
'Image paste is not supported for this agent.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
attachLocalPaths([result.path])
|
||||
setCaret(caretAtPaste)
|
||||
setNotice(null)
|
||||
})()
|
||||
},
|
||||
[agent, attachLocalPaths, caret]
|
||||
[agent, disabled, resolveTarget, onSlashCommand, setDraft]
|
||||
)
|
||||
|
||||
const handleKeyDown = useNativeChatComposerKeyDown({
|
||||
|
||||
@@ -4,6 +4,7 @@ import { translate } from '@/i18n/i18n'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { NATIVE_FILE_DROP_TARGET } from '../../../../shared/native-file-drop'
|
||||
import { basename } from '@/lib/path'
|
||||
import { isNativeChatPastedImagePath } from './native-chat-image-paste'
|
||||
import type { ComposerAutocomplete, SlashCommandSuggestion } from './native-chat-composer-state'
|
||||
import {
|
||||
NativeChatMentionHint,
|
||||
@@ -125,7 +126,14 @@ export function NativeChatComposerField({
|
||||
title={attachment.path}
|
||||
>
|
||||
<ImageIcon className="size-3.5 shrink-0" />
|
||||
<span className="max-w-56 truncate">{basename(attachment.path)}</span>
|
||||
<span className="max-w-56 truncate">
|
||||
{isNativeChatPastedImagePath(attachment.path)
|
||||
? translate(
|
||||
'components.native-chat.composer.pastedImageLabel',
|
||||
'Pasted image'
|
||||
)
|
||||
: basename(attachment.path)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveImageAttachment(attachment.id)}
|
||||
@@ -152,8 +160,10 @@ export function NativeChatComposerField({
|
||||
onSelect={(e) => onTextareaSelect(e.currentTarget)}
|
||||
placeholder={nativeChatComposerPlaceholder(hasPty, canSend)}
|
||||
// Why: coarse-pointer min-height follows the app's touch target convention.
|
||||
// scrollbar-sleek keeps the overflow gutter from showing the heavy
|
||||
// native scrollbar once the draft exceeds max-height.
|
||||
className={cn(
|
||||
'min-h-12 max-h-28 w-full resize-none bg-transparent px-2 py-1 text-sm outline-none pointer-coarse:min-h-14',
|
||||
'scrollbar-sleek min-h-12 max-h-28 w-full resize-none bg-transparent px-2 py-1 text-sm outline-none pointer-coarse:min-h-14',
|
||||
'placeholder:text-muted-foreground/60 disabled:cursor-not-allowed disabled:opacity-50'
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -14,6 +14,7 @@ import { orderNativeChatMessages } from './native-chat-message-grouping'
|
||||
import { stripNoiseMessages } from './native-chat-noise'
|
||||
import { foldToolMessages, splitNativeChatBlocks } from './native-chat-tool-fold'
|
||||
import { isNearBottom, shouldShowJumpToLatest, type ScrollGeometry } from './native-chat-autoscroll'
|
||||
import { isNativeChatPastedImagePath } from './native-chat-image-paste'
|
||||
import { NativeChatToolRun } from './NativeChatToolRun'
|
||||
import { NativeChatCopyButton } from './NativeChatCopyButton'
|
||||
import { NATIVE_CHAT_STREAMING_ID } from '../../../../shared/native-chat-streaming'
|
||||
@@ -43,7 +44,12 @@ function ImageAttachmentRefs({ blocks }: { blocks: NativeChatBlock[] }): React.J
|
||||
<div className="mb-2 flex flex-wrap gap-1.5">
|
||||
{images.map((image, index) => {
|
||||
const label = image.alt ?? image.path ?? image.url ?? 'Image'
|
||||
const name = image.path ? basename(image.path) : label
|
||||
const name =
|
||||
image.path && isNativeChatPastedImagePath(image.path)
|
||||
? translate('components.native-chat.composer.pastedImageLabel', 'Pasted image')
|
||||
: image.path
|
||||
? basename(image.path)
|
||||
: label
|
||||
return (
|
||||
<div
|
||||
key={`${label}-${index}`}
|
||||
|
||||
@@ -37,14 +37,13 @@ import {
|
||||
nativeChatStreamingMessage
|
||||
} from '../../../../shared/native-chat-streaming'
|
||||
import {
|
||||
shouldFocusNativeChatComposerFromEditingKey,
|
||||
shouldFocusNativeChatPaneFromPointerTarget,
|
||||
shouldRedirectNativeChatTyping
|
||||
} from './native-chat-typing-redirect'
|
||||
import { useNativeChatContextMenu } from './use-native-chat-context-menu'
|
||||
import type { NativeChatContextMenuActions } from './use-native-chat-context-menu'
|
||||
import { isMacPlatform } from './native-chat-shortcut'
|
||||
|
||||
const NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES = 16 * 1024 * 1024
|
||||
const emptyNativeChatContextMenuActions: Omit<NativeChatContextMenuActions, 'onPaste'> = {
|
||||
onSplitRight: () => {},
|
||||
onSplitDown: () => {},
|
||||
@@ -165,16 +164,11 @@ function NativeChatResolvedView({
|
||||
const [workingInterrupted, setWorkingInterrupted] = useState(false)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const composerRef = useRef<NativeChatComposerHandle>(null)
|
||||
const isMac = useMemo(() => isMacPlatform(), [])
|
||||
// Delegate to the composer so a pane-level Cmd/Ctrl+V (or context-menu /
|
||||
// app-menu paste) attaches a clipboard image when present, falling back to
|
||||
// text — matching the textarea's own paste behavior and the hosted TUI.
|
||||
const pasteClipboardIntoComposer = useCallback(() => {
|
||||
void window.api.ui
|
||||
.readClipboardText({ maxBytes: NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES })
|
||||
.then((text) => {
|
||||
if (text.length > 0) {
|
||||
composerRef.current?.insertTypedText(text)
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
composerRef.current?.pasteFromClipboard()
|
||||
}, [])
|
||||
const contextMenu = useNativeChatContextMenu({
|
||||
rootRef,
|
||||
@@ -185,39 +179,38 @@ function NativeChatResolvedView({
|
||||
}
|
||||
})
|
||||
|
||||
// Handle Cmd/Ctrl+V at the pane root rather than relying on the composer
|
||||
// textarea's own onPaste: the React-bound onPaste proved unreliable here (the
|
||||
// composer can mount more than once, and the live `paste` event does not
|
||||
// consistently dispatch to the textarea's React handler). A root capture
|
||||
// listener catches the paste for the focused pane in every case.
|
||||
useEffect(() => {
|
||||
const root = rootRef.current
|
||||
if (!root) {
|
||||
return
|
||||
}
|
||||
const onKeyPaste = (event: KeyboardEvent): void => {
|
||||
if (
|
||||
!matchesNativeChatPasteShortcut(event, isMac) ||
|
||||
!shouldFocusNativeChatPaneFromPointerTarget(event.target)
|
||||
) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
pasteClipboardIntoComposer()
|
||||
const onPaste = (event: ClipboardEvent): void => {
|
||||
composerRef.current?.handlePasteEvent(event)
|
||||
}
|
||||
|
||||
root.addEventListener('keydown', onKeyPaste, { capture: true })
|
||||
// Capture phase so the image is intercepted before the textarea's own
|
||||
// bubble-phase onPaste fires (which would otherwise attach it twice).
|
||||
root.addEventListener('paste', onPaste, { capture: true })
|
||||
return () => {
|
||||
root.removeEventListener('keydown', onKeyPaste, { capture: true })
|
||||
root.removeEventListener('paste', onPaste, { capture: true })
|
||||
}
|
||||
}, [isMac, pasteClipboardIntoComposer])
|
||||
}, [])
|
||||
|
||||
// Real Cmd/Ctrl+V is claimed by the Edit > Paste menu accelerator, which
|
||||
// sends this app-menu paste event instead of producing a DOM `paste` event on
|
||||
// the composer. Route it into the composer whenever focus is anywhere inside
|
||||
// this chat pane — including the composer textarea itself (the previous
|
||||
// non-interactive-target guard skipped exactly the focused-textarea case,
|
||||
// which is why Cmd+V appeared to do nothing).
|
||||
useEffect(() => {
|
||||
const onAppMenuPaste = (event: Event): void => {
|
||||
const root = rootRef.current
|
||||
const activeElement = document.activeElement
|
||||
if (
|
||||
!root ||
|
||||
!(activeElement instanceof Element) ||
|
||||
!root.contains(activeElement) ||
|
||||
!shouldFocusNativeChatPaneFromPointerTarget(activeElement)
|
||||
) {
|
||||
if (!root || !(activeElement instanceof Element) || !root.contains(activeElement)) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
@@ -367,6 +360,12 @@ function NativeChatResolvedView({
|
||||
}
|
||||
}}
|
||||
onKeyDownCapture={(event) => {
|
||||
// Backspace/Delete outside an input focuses the composer (like typing)
|
||||
// but inserts nothing — let the now-focused field handle the keystroke.
|
||||
if (shouldFocusNativeChatComposerFromEditingKey(event)) {
|
||||
composerRef.current?.focus()
|
||||
return
|
||||
}
|
||||
if (!shouldRedirectNativeChatTyping(event)) {
|
||||
return
|
||||
}
|
||||
@@ -418,13 +417,3 @@ function NativeChatResolvedView({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function matchesNativeChatPasteShortcut(
|
||||
event: Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey' | 'altKey' | 'shiftKey'>,
|
||||
isMac: boolean
|
||||
): boolean {
|
||||
if (event.altKey || event.shiftKey || event.key.toLowerCase() !== 'v') {
|
||||
return false
|
||||
}
|
||||
return isMac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@ export type NativeChatResolvedTarget = {
|
||||
settings: ReturnType<typeof getSettingsForAgentTabRuntimeOwner>
|
||||
}
|
||||
|
||||
/** Upper bound for clipboard text pulled into the composer via Cmd/Ctrl+V, so a
|
||||
* pathological clipboard can't stall the round-trip. */
|
||||
export const NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES = 16 * 1024 * 1024
|
||||
|
||||
export function nativeChatComposerPlaceholder(hasPty: boolean, canSend: boolean): string {
|
||||
if (!hasPty) {
|
||||
return translate(
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
clearNativeChatDraftCacheForTests,
|
||||
readNativeChatDraftCache,
|
||||
writeNativeChatDraftCache
|
||||
} from './native-chat-draft-cache'
|
||||
|
||||
afterEach(() => {
|
||||
clearNativeChatDraftCacheForTests()
|
||||
})
|
||||
|
||||
describe('native-chat draft cache', () => {
|
||||
it('returns an empty string for an unknown scope', () => {
|
||||
expect(readNativeChatDraftCache('pty-1')).toBe('')
|
||||
})
|
||||
|
||||
it('round-trips a draft per scope key', () => {
|
||||
writeNativeChatDraftCache('pty-1', 'hello')
|
||||
writeNativeChatDraftCache('pty-2', 'world')
|
||||
expect(readNativeChatDraftCache('pty-1')).toBe('hello')
|
||||
expect(readNativeChatDraftCache('pty-2')).toBe('world')
|
||||
})
|
||||
|
||||
it('drops the entry when the draft is cleared so stale text never resurfaces', () => {
|
||||
writeNativeChatDraftCache('pty-1', 'hello')
|
||||
writeNativeChatDraftCache('pty-1', '')
|
||||
expect(readNativeChatDraftCache('pty-1')).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
// Module-level cache for the composer's in-progress draft text, keyed by the
|
||||
// same scope as image attachments (targetPtyId ?? terminalTabId). The composer
|
||||
// unmounts when the pane toggles back to the hosted terminal, so without this
|
||||
// the typed-but-unsent draft would be lost on every TUI/GUI round-trip. Mirrors
|
||||
// the attachment cache so both halves of an unsent message survive the toggle.
|
||||
|
||||
const draftCache = new Map<string, string>()
|
||||
|
||||
export function readNativeChatDraftCache(scopeKey: string): string {
|
||||
return draftCache.get(scopeKey) ?? ''
|
||||
}
|
||||
|
||||
export function writeNativeChatDraftCache(scopeKey: string, draft: string): void {
|
||||
// An empty draft carries no state worth retaining; drop the entry so a stale
|
||||
// scope key never resurrects cleared text.
|
||||
if (draft === '') {
|
||||
draftCache.delete(scopeKey)
|
||||
return
|
||||
}
|
||||
draftCache.set(scopeKey, draft)
|
||||
}
|
||||
|
||||
export function clearNativeChatDraftCacheForTests(): void {
|
||||
draftCache.clear()
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getAgentImageHandling, resolveImagePaste } from './native-chat-image-paste'
|
||||
import {
|
||||
getAgentImageHandling,
|
||||
isNativeChatPastedImagePath,
|
||||
resolveImagePaste
|
||||
} from './native-chat-image-paste'
|
||||
|
||||
describe('image paste agent map', () => {
|
||||
it('known image-capable agent attaches the temp file path', () => {
|
||||
@@ -23,3 +27,20 @@ describe('image paste agent map', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('isNativeChatPastedImagePath', () => {
|
||||
it('detects clipboard-paste temp files (so the chip shows a friendly label)', () => {
|
||||
expect(
|
||||
isNativeChatPastedImagePath(
|
||||
'/var/folders/x/orca-paste-1782775228480-c9a3c86b-1234-5678-9abc-def012345678.png'
|
||||
)
|
||||
).toBe(true)
|
||||
// Windows-style separators resolve to the same basename.
|
||||
expect(isNativeChatPastedImagePath('C:\\Temp\\orca-paste-1-2.png')).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves picked/dropped files showing their real name', () => {
|
||||
expect(isNativeChatPastedImagePath('/Users/me/Pictures/hero-image-2.png')).toBe(false)
|
||||
expect(isNativeChatPastedImagePath('/tmp/screenshot.png')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -45,3 +45,11 @@ export function resolveImagePaste(agent: AgentType, tempFilePath: string): Image
|
||||
export function isNativeChatImageAttachmentPath(path: string): boolean {
|
||||
return isImageDropPath(path)
|
||||
}
|
||||
|
||||
/** True when a path is a clipboard-paste temp file (`orca-paste-<ts>-<uuid>.png`).
|
||||
* Those names are noise in the UI, so the composer shows a friendly label
|
||||
* instead of the basename. */
|
||||
export function isNativeChatPastedImagePath(path: string): boolean {
|
||||
const base = path.split(/[\\/]/).filter(Boolean).at(-1) ?? path
|
||||
return /^orca-paste-.+\.png$/i.test(base)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { NativeChatMessage } from '../../../../shared/native-chat-types'
|
||||
import { normalizeImageTranscriptMessages } from './native-chat-image-transcript-markers'
|
||||
|
||||
function userText(id: string, text: string): NativeChatMessage {
|
||||
return {
|
||||
id,
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text }],
|
||||
timestamp: 1,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
describe('normalizeImageTranscriptMessages', () => {
|
||||
it('merges the paired [Image: source]/[Image #1] turns into one image-ref turn', () => {
|
||||
const out = normalizeImageTranscriptMessages([
|
||||
userText('a', '[Image: source: /tmp/orca-paste-1-2.png]'),
|
||||
userText('b', '[Image #1] describe this')
|
||||
])
|
||||
expect(out).toHaveLength(1)
|
||||
expect(out[0]!.blocks).toEqual([
|
||||
{ type: 'image-ref', path: '/tmp/orca-paste-1-2.png' },
|
||||
{ type: 'text', text: 'describe this' }
|
||||
])
|
||||
})
|
||||
|
||||
it('converts a lone [Image: source] turn (no prompt) into an image-ref instead of raw text', () => {
|
||||
const out = normalizeImageTranscriptMessages([
|
||||
userText('a', '[Image: source: /Users/me/Pictures/hero-image-2.png]')
|
||||
])
|
||||
expect(out).toHaveLength(1)
|
||||
expect(out[0]!.blocks).toEqual([
|
||||
{ type: 'image-ref', path: '/Users/me/Pictures/hero-image-2.png' }
|
||||
])
|
||||
})
|
||||
|
||||
it('leaves ordinary user text untouched', () => {
|
||||
const out = normalizeImageTranscriptMessages([userText('a', 'how about this')])
|
||||
expect(out[0]!.blocks).toEqual([{ type: 'text', text: 'how about this' }])
|
||||
})
|
||||
|
||||
it('leaves assistant messages untouched', () => {
|
||||
const assistant: NativeChatMessage = {
|
||||
id: 'a',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: '[Image: source: /tmp/x.png]' }],
|
||||
timestamp: 1,
|
||||
source: 'transcript'
|
||||
}
|
||||
expect(normalizeImageTranscriptMessages([assistant])).toEqual([assistant])
|
||||
})
|
||||
})
|
||||
@@ -75,6 +75,16 @@ export function normalizeImageTranscriptMessages(
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
// A lone `[Image: source: /path]` turn (no following `[Image #1]` prompt —
|
||||
// e.g. an image sent with no caption) still renders as an image chip rather
|
||||
// than the raw marker text.
|
||||
if (imagePath) {
|
||||
normalized.push({
|
||||
...message,
|
||||
blocks: [{ type: 'image-ref', path: imagePath }]
|
||||
})
|
||||
continue
|
||||
}
|
||||
normalized.push({
|
||||
...message,
|
||||
blocks: stripFirstImagePromptMarker(message.blocks)
|
||||
|
||||
@@ -10,7 +10,6 @@ vi.mock('@/runtime/runtime-terminal-inspection', () => ({
|
||||
import {
|
||||
sendNativeChatMessage,
|
||||
sendNativeChatMessageWithImageAttachments,
|
||||
sendNativeChatImageAttachments,
|
||||
submitNativeChatPrompt,
|
||||
sendNativeChatAnswer,
|
||||
nativeChatQuestionOffsets,
|
||||
@@ -114,23 +113,12 @@ describe('sendNativeChatMessageWithImageAttachments', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('pre-pasted image attachment sends', () => {
|
||||
describe('empty prompt submit', () => {
|
||||
beforeEach(() => {
|
||||
sendRuntimePtyInput.mockClear()
|
||||
})
|
||||
|
||||
it('pastes image attachments immediately without submitting the prompt', () => {
|
||||
sendNativeChatImageAttachments(SETTINGS, PTY, ['/tmp/orca-paste-image.png'])
|
||||
|
||||
expect(sendRuntimePtyInput).toHaveBeenCalledTimes(1)
|
||||
expect(sendRuntimePtyInput).toHaveBeenLastCalledWith(
|
||||
SETTINGS,
|
||||
PTY,
|
||||
buildNativeChatImagePasteBytes('/tmp/orca-paste-image.png')
|
||||
)
|
||||
})
|
||||
|
||||
it('submits a prompt whose image attachments were already pasted', () => {
|
||||
it('submits an empty prompt with a bare Enter', () => {
|
||||
submitNativeChatPrompt(SETTINGS, PTY)
|
||||
|
||||
expect(sendRuntimePtyInput).toHaveBeenCalledTimes(1)
|
||||
|
||||
@@ -111,19 +111,8 @@ export function sendNativeChatMessageWithImageAttachments(
|
||||
}
|
||||
}
|
||||
|
||||
/** Paste image attachments into the hosted TUI immediately so switching back to
|
||||
* the terminal shows the same image chips a direct terminal paste would show. */
|
||||
export function sendNativeChatImageAttachments(
|
||||
settings: ReturnType<typeof getSettingsForAgentTabRuntimeOwner>,
|
||||
ptyId: string,
|
||||
imagePaths: readonly string[]
|
||||
): void {
|
||||
for (const imagePath of imagePaths) {
|
||||
sendRuntimePtyInput(settings, ptyId, buildNativeChatImagePasteBytes(imagePath))
|
||||
}
|
||||
}
|
||||
|
||||
/** Submit a TUI prompt whose image attachments were already pasted earlier. */
|
||||
/** Submit a TUI prompt with no body (Enter only) — e.g. a plain submit when the
|
||||
* composer is empty. */
|
||||
export function submitNativeChatPrompt(
|
||||
settings: ReturnType<typeof getSettingsForAgentTabRuntimeOwner>,
|
||||
ptyId: string
|
||||
|
||||
@@ -118,7 +118,9 @@ export function assembleNativeChatSession(
|
||||
const ordered: NativeChatMessage[] = [
|
||||
...normalizeImageTranscriptMessages(sources.transcript ?? []),
|
||||
...(sources.hook ?? []),
|
||||
...(sources.scrape ?? [])
|
||||
// Scrape segments carry the same raw `[Image: source: …]` markers (e.g. from
|
||||
// scrollback before the transcript loads), so normalize them too.
|
||||
...normalizeImageTranscriptMessages(sources.scrape ?? [])
|
||||
]
|
||||
|
||||
const byId = new Map<string, NativeChatMessage>()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
shouldFocusNativeChatComposerFromEditingKey,
|
||||
shouldFocusNativeChatPaneFromPointerTarget,
|
||||
shouldRedirectNativeChatTyping
|
||||
} from './native-chat-typing-redirect'
|
||||
@@ -46,6 +47,46 @@ describe('shouldRedirectNativeChatTyping', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldFocusNativeChatComposerFromEditingKey', () => {
|
||||
it('focuses the composer on Backspace/Delete from the pane', () => {
|
||||
expect(shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Backspace' }))).toBe(true)
|
||||
expect(shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Delete' }))).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores other keys, shortcut/editing modifiers, IME composition, and handled events', () => {
|
||||
expect(shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'a' }))).toBe(false)
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(
|
||||
keyEvent({ key: 'Backspace', defaultPrevented: true })
|
||||
)
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Backspace', metaKey: true }))
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Backspace', ctrlKey: true }))
|
||||
).toBe(false)
|
||||
// Shift/Alt chords (cut, delete-word) belong to the focused target.
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Delete', shiftKey: true }))
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Backspace', altKey: true }))
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(keyEvent({ key: 'Backspace', isComposing: true }))
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves interactive targets (the textarea itself) alone', () => {
|
||||
expect(
|
||||
shouldFocusNativeChatComposerFromEditingKey(
|
||||
keyEvent({ key: 'Backspace', target: interactiveTarget() })
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldFocusNativeChatPaneFromPointerTarget', () => {
|
||||
it('focuses the pane for non-interactive clicks', () => {
|
||||
expect(shouldFocusNativeChatPaneFromPointerTarget(inertTarget())).toBe(true)
|
||||
|
||||
@@ -2,6 +2,8 @@ type KeyboardRedirectEvent = {
|
||||
key: string
|
||||
ctrlKey: boolean
|
||||
metaKey: boolean
|
||||
shiftKey?: boolean
|
||||
altKey?: boolean
|
||||
defaultPrevented: boolean
|
||||
isComposing?: boolean
|
||||
target: EventTarget | null
|
||||
@@ -43,6 +45,26 @@ export function shouldFocusNativeChatPaneFromPointerTarget(target: EventTarget |
|
||||
return !isNativeChatInteractiveTarget(target)
|
||||
}
|
||||
|
||||
/** Unmodified Backspace/Delete pressed outside any input should focus the
|
||||
* composer, the same way printable typing does — but unlike typing these keys
|
||||
* are not inserted (their character has no literal form), so the caller only
|
||||
* focuses. Modified chords (Shift/Alt/Ctrl/Cmd+Delete = cut, delete-word, …)
|
||||
* are left to the focused target. */
|
||||
export function shouldFocusNativeChatComposerFromEditingKey(event: KeyboardRedirectEvent): boolean {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey ||
|
||||
(event.key !== 'Backspace' && event.key !== 'Delete')
|
||||
) {
|
||||
return false
|
||||
}
|
||||
return !isNativeChatInteractiveTarget(event.target)
|
||||
}
|
||||
|
||||
function isNativeChatInteractiveTarget(target: EventTarget | null): boolean {
|
||||
const element = eventTargetElement(target)
|
||||
if (!element) {
|
||||
|
||||
+67
-13
@@ -10,10 +10,6 @@ import {
|
||||
} from './use-native-chat-composer-attachments'
|
||||
import type { NativeChatResolvedTarget } from './native-chat-composer-target'
|
||||
|
||||
const sendNativeChatImageAttachments = vi.fn()
|
||||
vi.mock('./native-chat-runtime-send', () => ({
|
||||
sendNativeChatImageAttachments: (...args: unknown[]) => sendNativeChatImageAttachments(...args)
|
||||
}))
|
||||
vi.mock('@/i18n/i18n', () => ({
|
||||
translate: (_key: string, fallback: string) => fallback
|
||||
}))
|
||||
@@ -52,36 +48,57 @@ function Probe({
|
||||
return createElement('textarea', { ref: textareaRef })
|
||||
}
|
||||
|
||||
async function renderProbe(scopeKey: string): Promise<{ root: Root; api: ProbeApi }> {
|
||||
async function renderProbe(
|
||||
scopeKey: string
|
||||
): Promise<{ root: Root; latest: () => ProbeApi; rerender: (scopeKey: string) => Promise<void> }> {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
// onReady fires on every render, so keep the freshest snapshot — reading a
|
||||
// single captured `api` would go stale after attach/remove triggers a render.
|
||||
let api: ProbeApi | null = null
|
||||
const root = createRoot(container)
|
||||
const onReady = (next: ProbeApi): void => {
|
||||
api = next
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(createElement(Probe, { scopeKey, onReady: (next) => (api = next) }))
|
||||
root.render(createElement(Probe, { scopeKey, onReady }))
|
||||
})
|
||||
if (!api) {
|
||||
throw new Error('Probe did not render')
|
||||
}
|
||||
return { root, api }
|
||||
return {
|
||||
root,
|
||||
latest: () => {
|
||||
if (!api) {
|
||||
throw new Error('Probe is not mounted')
|
||||
}
|
||||
return api
|
||||
},
|
||||
rerender: async (nextScopeKey: string) => {
|
||||
await act(async () => {
|
||||
root.render(createElement(Probe, { scopeKey: nextScopeKey, onReady }))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('useNativeChatComposerAttachments', () => {
|
||||
afterEach(() => {
|
||||
clearNativeChatAttachmentCacheForTests()
|
||||
sendNativeChatImageAttachments.mockReset()
|
||||
document.body.replaceChildren()
|
||||
})
|
||||
|
||||
it('pastes image attachments into the TUI immediately and restores native chips on remount', async () => {
|
||||
it('holds attached images as chips (deferred to submit) and restores them on remount', async () => {
|
||||
const first = await renderProbe('pty-1')
|
||||
|
||||
await act(async () => {
|
||||
first.api.attachLocalPaths(['/tmp/orca-native-chat-attach-test.png'])
|
||||
first.latest().attachLocalPaths(['/tmp/orca-native-chat-attach-test.png'])
|
||||
})
|
||||
|
||||
expect(sendNativeChatImageAttachments).toHaveBeenCalledWith(target.settings, 'pty-1', [
|
||||
'/tmp/orca-native-chat-attach-test.png'
|
||||
// Images are NOT sent to the TUI on attach — they ride along on submit, so
|
||||
// the chip and the TUI input never diverge and removing a chip is clean.
|
||||
expect(first.latest().imageAttachments).toMatchObject([
|
||||
{ path: '/tmp/orca-native-chat-attach-test.png' }
|
||||
])
|
||||
expect(readNativeChatAttachmentCache('pty-1')).toMatchObject([
|
||||
{ path: '/tmp/orca-native-chat-attach-test.png' }
|
||||
@@ -90,9 +107,46 @@ describe('useNativeChatComposerAttachments', () => {
|
||||
act(() => first.root.unmount())
|
||||
const second = await renderProbe('pty-1')
|
||||
|
||||
expect(second.api.imageAttachments).toMatchObject([
|
||||
expect(second.latest().imageAttachments).toMatchObject([
|
||||
{ path: '/tmp/orca-native-chat-attach-test.png' }
|
||||
])
|
||||
act(() => second.root.unmount())
|
||||
})
|
||||
|
||||
it('removes an attached image chip cleanly', async () => {
|
||||
const probe = await renderProbe('pty-1')
|
||||
await act(async () => {
|
||||
probe.latest().attachLocalPaths(['/tmp/orca-native-chat-remove-test.png'])
|
||||
})
|
||||
const id = probe.latest().imageAttachments[0]?.id
|
||||
expect(id).toBeDefined()
|
||||
await act(async () => {
|
||||
probe.latest().removeImageAttachment(id as string)
|
||||
})
|
||||
expect(probe.latest().imageAttachments).toMatchObject([])
|
||||
expect(readNativeChatAttachmentCache('pty-1')).toMatchObject([])
|
||||
act(() => probe.root.unmount())
|
||||
})
|
||||
|
||||
it('rescopes attachments when the scope key changes (composer reused for another pane)', async () => {
|
||||
const probe = await renderProbe('pty-1')
|
||||
await act(async () => {
|
||||
probe.latest().attachLocalPaths(['/tmp/orca-native-chat-pane-1.png'])
|
||||
})
|
||||
expect(probe.latest().imageAttachments).toMatchObject([
|
||||
{ path: '/tmp/orca-native-chat-pane-1.png' }
|
||||
])
|
||||
|
||||
// Reused for a different pane: pane-1's chip must not stay live (it would
|
||||
// otherwise be submitted to pane-2's target now that images defer to submit).
|
||||
await probe.rerender('pty-2')
|
||||
expect(probe.latest().imageAttachments).toMatchObject([])
|
||||
|
||||
// Switching back restores pane-1's still-cached chip.
|
||||
await probe.rerender('pty-1')
|
||||
expect(probe.latest().imageAttachments).toMatchObject([
|
||||
{ path: '/tmp/orca-native-chat-pane-1.png' }
|
||||
])
|
||||
act(() => probe.root.unmount())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type NativeChatResolvedTarget
|
||||
} from './native-chat-composer-target'
|
||||
import type { NativeChatComposerImageAttachment } from './NativeChatComposerField'
|
||||
import { sendNativeChatImageAttachments } from './native-chat-runtime-send'
|
||||
|
||||
export type UseNativeChatComposerAttachmentsArgs = {
|
||||
attachmentScopeKey: string
|
||||
@@ -39,6 +38,16 @@ export function useNativeChatComposerAttachments({
|
||||
)
|
||||
const imageAttachmentCounter = useRef(0)
|
||||
|
||||
// Reload chips from the cache when the composer is reused for a different pane
|
||||
// (scope-key change), adjusting state during render rather than in an effect.
|
||||
// Without this the previous pane's chips would stay live and be submitted to
|
||||
// the new target now that images are deferred to submit.
|
||||
const lastScopeKey = useRef(attachmentScopeKey)
|
||||
if (lastScopeKey.current !== attachmentScopeKey) {
|
||||
lastScopeKey.current = attachmentScopeKey
|
||||
setImageAttachments(readNativeChatAttachmentCache(attachmentScopeKey))
|
||||
}
|
||||
|
||||
const updateImageAttachments = useCallback(
|
||||
(
|
||||
updater: (
|
||||
@@ -105,9 +114,9 @@ export function useNativeChatComposerAttachments({
|
||||
}
|
||||
const imagePaths = paths.filter(isNativeChatImageAttachmentPath)
|
||||
const filePaths = paths.filter((path) => !isNativeChatImageAttachmentPath(path))
|
||||
if (imagePaths.length > 0) {
|
||||
sendNativeChatImageAttachments(target.settings, target.ptyId, imagePaths)
|
||||
}
|
||||
// Images are NOT sent to the TUI here — they ride along on submit (see
|
||||
// NativeChatComposer.send) so the GUI chips and the TUI input never
|
||||
// diverge and removing a chip needs no TUI un-paste.
|
||||
appendImageAttachments(imagePaths)
|
||||
insertFileReferences(filePaths)
|
||||
if (imagePaths.length > 0) {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useCallback, useRef } from 'react'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { AgentType } from '../../../../shared/agent-status-types'
|
||||
import { resolveImagePaste } from './native-chat-image-paste'
|
||||
import { NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES } from './native-chat-composer-target'
|
||||
|
||||
export type UseNativeChatComposerPasteArgs = {
|
||||
agent: AgentType
|
||||
/** Live composer-disabled state (no pty / presence-lock); read at await-resume
|
||||
* via a ref so a flip mid-paste doesn't write into a guarded composer. */
|
||||
disabled: boolean
|
||||
caret: number
|
||||
attachLocalPaths: (paths: string[]) => void
|
||||
insertTypedText: (text: string) => boolean
|
||||
setCaret: (caret: number) => void
|
||||
setNotice: (notice: string | null) => void
|
||||
}
|
||||
|
||||
/** Minimal shape shared by React's synthetic ClipboardEvent and the native DOM
|
||||
* ClipboardEvent — the pane-level listener delivers the native one. */
|
||||
type ClipboardEventLike = {
|
||||
clipboardData: DataTransfer | null
|
||||
preventDefault: () => void
|
||||
defaultPrevented: boolean
|
||||
}
|
||||
|
||||
function clipboardEventHasImage(event: ClipboardEventLike): boolean {
|
||||
const data = event.clipboardData
|
||||
if (!data) {
|
||||
return false
|
||||
}
|
||||
return Array.from(data.items).some((item) => item.type.startsWith('image/'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard-paste behavior for the native chat composer: a clipboard image
|
||||
* becomes an attachment (TUI parity), otherwise text is inserted at the caret.
|
||||
* `handlePaste` consumes a paste event (the textarea's onPaste *or* the
|
||||
* pane-level capture listener — the OS often retargets the event off the
|
||||
* focused textarea, so the pane listener is the reliable path);
|
||||
* `pasteFromClipboard` is the menu-driven path with no event in hand.
|
||||
*/
|
||||
export function useNativeChatComposerPaste({
|
||||
agent,
|
||||
disabled,
|
||||
caret,
|
||||
attachLocalPaths,
|
||||
insertTypedText,
|
||||
setCaret,
|
||||
setNotice
|
||||
}: UseNativeChatComposerPasteArgs): {
|
||||
handlePaste: (event: ClipboardEventLike) => void
|
||||
pasteFromClipboard: () => void
|
||||
} {
|
||||
// Re-read the live disabled state after the async clipboard round-trip:
|
||||
// `canSend` can flip (mobile presence-lock) or the pty drop out mid-await, and
|
||||
// the captured closure would otherwise attach/insert into a guarded composer.
|
||||
const disabledRef = useRef(disabled)
|
||||
disabledRef.current = disabled
|
||||
|
||||
const attachClipboardImageTempFile = useCallback(
|
||||
(tempPath: string) => {
|
||||
const result = resolveImagePaste(agent, tempPath)
|
||||
if (result.kind === 'unsupported') {
|
||||
setNotice(
|
||||
translate(
|
||||
'components.native-chat.composer.imageUnsupported',
|
||||
'Image paste is not supported for this agent.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
attachLocalPaths([result.path])
|
||||
setNotice(null)
|
||||
},
|
||||
[agent, attachLocalPaths, setNotice]
|
||||
)
|
||||
|
||||
const handlePaste = useCallback(
|
||||
(event: ClipboardEventLike) => {
|
||||
// Dedupe: the pane-level capture listener runs first and preventDefaults
|
||||
// images, so the textarea's bubble-phase onPaste must not attach again.
|
||||
if (event.defaultPrevented) {
|
||||
return
|
||||
}
|
||||
// Only an image needs interception; plain text falls through so the
|
||||
// textarea's native paste keeps its caret/undo behavior when it is the
|
||||
// event target. (When the OS retargets the paste off the textarea the
|
||||
// pane listener still routes text via pasteFromClipboard.)
|
||||
if (!clipboardEventHasImage(event)) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
// Why: snapshot the caret before the async temp-file round-trip — `caret`
|
||||
// state can move (further typing/selection) while the await is in flight.
|
||||
const caretAtPaste = caret
|
||||
void (async () => {
|
||||
const tempPath = await window.api.ui.saveClipboardImageAsTempFile().catch(() => null)
|
||||
if (!tempPath || disabledRef.current) {
|
||||
return
|
||||
}
|
||||
attachClipboardImageTempFile(tempPath)
|
||||
setCaret(caretAtPaste)
|
||||
})()
|
||||
},
|
||||
[attachClipboardImageTempFile, caret, setCaret]
|
||||
)
|
||||
|
||||
const pasteFromClipboard = useCallback(() => {
|
||||
void (async () => {
|
||||
const tempPath = await window.api.ui.saveClipboardImageAsTempFile().catch(() => null)
|
||||
if (disabledRef.current) {
|
||||
return
|
||||
}
|
||||
if (tempPath) {
|
||||
attachClipboardImageTempFile(tempPath)
|
||||
return
|
||||
}
|
||||
const text = await window.api.ui
|
||||
.readClipboardText({ maxBytes: NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES })
|
||||
.catch(() => '')
|
||||
if (disabledRef.current) {
|
||||
return
|
||||
}
|
||||
if (text.length > 0) {
|
||||
insertTypedText(text)
|
||||
}
|
||||
})()
|
||||
}, [attachClipboardImageTempFile, insertTypedText])
|
||||
|
||||
return { handlePaste, pasteFromClipboard }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { readNativeChatDraftCache, writeNativeChatDraftCache } from './native-chat-draft-cache'
|
||||
|
||||
/**
|
||||
* Composer draft state backed by the scope cache so a typed-but-unsent message
|
||||
* survives the composer unmounting on a TUI/GUI toggle. `scopeKey` is the same
|
||||
* key used for image attachments (targetPtyId ?? terminalTabId); when it changes
|
||||
* (the composer is reused for a different pane) the cached draft is reloaded.
|
||||
*/
|
||||
export function useNativeChatDraft(scopeKey: string): {
|
||||
draft: string
|
||||
setDraft: (next: string | ((previous: string) => string)) => void
|
||||
} {
|
||||
const [draft, setDraftState] = useState(() => readNativeChatDraftCache(scopeKey))
|
||||
|
||||
// Reload the cached draft when reused for a different pane (scope change),
|
||||
// adjusting state during render rather than in an effect so the restored draft
|
||||
// is visible on the first paint after the switch.
|
||||
const lastScopeKey = useRef(scopeKey)
|
||||
if (lastScopeKey.current !== scopeKey) {
|
||||
lastScopeKey.current = scopeKey
|
||||
setDraftState(readNativeChatDraftCache(scopeKey))
|
||||
}
|
||||
|
||||
// Persist every mutation through the cache. Accepts the same value/updater
|
||||
// forms as a useState setter so call sites are drop-in.
|
||||
const setDraft = useCallback(
|
||||
(next: string | ((previous: string) => string)) => {
|
||||
setDraftState((previous) => {
|
||||
const resolved = typeof next === 'function' ? next(previous) : next
|
||||
writeNativeChatDraftCache(scopeKey, resolved)
|
||||
return resolved
|
||||
})
|
||||
},
|
||||
[scopeKey]
|
||||
)
|
||||
|
||||
return { draft, setDraft }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable max-lines -- Why: terminal pane component co-locates title state, layout serialization, and portal rendering to keep pane lifecycle consistent. */
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { CSSProperties } from 'react'
|
||||
import type { IDisposable } from '@xterm/xterm'
|
||||
@@ -79,6 +80,7 @@ import {
|
||||
} from '@/lib/pane-manager/mobile-driver-state'
|
||||
import { shouldChatTakeOverMobileSurface } from '../native-chat/native-chat-send-eligibility'
|
||||
import { canToggleNativeChat } from '../native-chat/native-chat-availability'
|
||||
import type { AgentType } from '../../../../shared/agent-status-types'
|
||||
import { resolvePaneKeyForManager } from '@/lib/pane-manager/pane-key-resolution'
|
||||
import { safeFit } from '@/lib/pane-manager/pane-tree-ops'
|
||||
import { captureTerminalShutdownLayout } from './terminal-shutdown-layout-capture'
|
||||
@@ -559,18 +561,23 @@ export default function TerminalPane({
|
||||
)?.label
|
||||
)
|
||||
// The native-chat toggle joins the pane header's split/close cluster. Eligible
|
||||
// when Orca launched a *supported* agent here or one was detected live (a pane
|
||||
// of this tab has an agent-status entry, keyed `${tabId}:…`). Carry the agent
|
||||
// identity, not just "an agent exists", so the gate can reject Grok et al.
|
||||
const detectedAgent = useAppStore((store) => {
|
||||
for (const [paneKey, entry] of Object.entries(store.agentStatusByPaneKey)) {
|
||||
const sep = paneKey.indexOf(':')
|
||||
if (sep > 0 && paneKey.slice(0, sep) === tabId) {
|
||||
return entry.agentType ?? null
|
||||
// when Orca launched a *supported* agent here or one was detected live for the
|
||||
// leaf, keyed `${tabId}:${leafId}`. Carry the agent identity, not just "an
|
||||
// agent exists", so the gate can reject Grok et al.
|
||||
// Scoped to this tab's panes (leafId → agentType) and shallow-compared so an
|
||||
// unrelated tab's agent status tick doesn't re-render this pane.
|
||||
const tabAgentTypeByLeaf = useAppStore(
|
||||
useShallow((store) => {
|
||||
const prefix = `${tabId}:`
|
||||
const byLeaf: Record<string, AgentType> = {}
|
||||
for (const [paneKey, entry] of Object.entries(store.agentStatusByPaneKey)) {
|
||||
if (paneKey.startsWith(prefix) && entry.agentType) {
|
||||
byLeaf[paneKey.slice(prefix.length)] = entry.agentType
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
return byLeaf
|
||||
})
|
||||
)
|
||||
const toggleTabViewMode = useAppStore((store) => store.toggleTabViewMode)
|
||||
const savedLayout = useAppStore((store) => store.terminalLayoutsByTabId[tabId] ?? EMPTY_LAYOUT)
|
||||
const terminalTab = useAppStore((store) =>
|
||||
@@ -581,14 +588,36 @@ export default function TerminalPane({
|
||||
const titleResolvedAgent =
|
||||
resolveTabAgentFromTitle(unifiedTabLabel ?? '') ??
|
||||
(terminalTab ? resolveTabAgentFromTitle(terminalTab.title) : null)
|
||||
const canToggleChat = canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: nativeChatEnabled,
|
||||
contentType: 'terminal',
|
||||
launchAgent: terminalTab?.launchAgent,
|
||||
detectedAgent,
|
||||
resolvedAgent: titleResolvedAgent,
|
||||
isChatViewMode
|
||||
})
|
||||
// Per-leaf eligibility: a split can mix a supported agent in one leaf with an
|
||||
// unsupported one in another, so the toggle is gated by the specific leaf.
|
||||
// A leaf's own live agent is authoritative; the tab-wide launch/title hints
|
||||
// only fill in before hooks arrive (or for the single-pane case) so they
|
||||
// can't enable the toggle on a sibling actually running an unsupported agent.
|
||||
const canToggleChatForLeaf = useCallback(
|
||||
(leafId: string | null): boolean => {
|
||||
const detectedAgent = leafId ? (tabAgentTypeByLeaf[leafId] ?? null) : null
|
||||
// Scope the "always allow toggling back" rule to the leaf actually showing
|
||||
// chat — passing the tab-wide flag would re-enable the toggle on an
|
||||
// unsupported sibling whenever any leaf in the split is in chat view.
|
||||
const isChatViewForLeaf = effectiveChatViewMode && leafId !== null && chatLeafId === leafId
|
||||
return canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: nativeChatEnabled,
|
||||
contentType: 'terminal',
|
||||
launchAgent: detectedAgent ? null : terminalTab?.launchAgent,
|
||||
detectedAgent,
|
||||
resolvedAgent: detectedAgent ? null : titleResolvedAgent,
|
||||
isChatViewMode: isChatViewForLeaf
|
||||
})
|
||||
},
|
||||
[
|
||||
tabAgentTypeByLeaf,
|
||||
effectiveChatViewMode,
|
||||
chatLeafId,
|
||||
nativeChatEnabled,
|
||||
terminalTab?.launchAgent,
|
||||
titleResolvedAgent
|
||||
]
|
||||
)
|
||||
const toggleNativeChatForLeaf = useCallback(
|
||||
(leafId: string) => {
|
||||
if (!unifiedTabId) {
|
||||
@@ -2712,6 +2741,11 @@ export default function TerminalPane({
|
||||
const activePaneIsChatLeaf = Boolean(
|
||||
isChatViewMode && activePane?.leafId && activePane.leafId === chatLeafId
|
||||
)
|
||||
// Header toggle gates on the active leaf; the context-menu toggle gates on the
|
||||
// leaf the menu was opened over — so a split mixing supported/unsupported
|
||||
// agents shows the toggle only on the leaf that can actually render chat.
|
||||
const activePaneCanToggleChat = canToggleChatForLeaf(activePane?.leafId ?? null)
|
||||
const contextMenuCanToggleChat = canToggleChatForLeaf(contextMenuLeafId)
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
@@ -2842,7 +2876,7 @@ export default function TerminalPane({
|
||||
onClosePane={contextMenu.onClosePane}
|
||||
onClearScreen={contextMenu.onClearScreen}
|
||||
onForkAgentSession={() => void contextMenu.onForkAgentSession()}
|
||||
canToggleNativeChat={canToggleChat}
|
||||
canToggleNativeChat={contextMenuCanToggleChat}
|
||||
isNativeChatView={contextMenuIsChatView}
|
||||
onToggleNativeChat={handleContextMenuToggleNativeChat}
|
||||
onCopyAgentSessionContext={() => void contextMenu.onCopyAgentSessionContext()}
|
||||
@@ -2898,7 +2932,7 @@ export default function TerminalPane({
|
||||
hiddenStartupStyle={hiddenStartupStyle}
|
||||
managerRef={managerRef}
|
||||
paneTransportsRef={paneTransportsRef}
|
||||
canToggleNativeChat={canToggleChat}
|
||||
canToggleNativeChat={activePaneCanToggleChat}
|
||||
isChatViewMode={activePaneIsChatLeaf}
|
||||
onToggleNativeChat={handleToggleNativeChat}
|
||||
onSplitPane={splitTerminalPaneFromHeader}
|
||||
|
||||
@@ -12171,7 +12171,8 @@
|
||||
"stopDictation": "Stop dictation",
|
||||
"noSkills": "No matching skills",
|
||||
"localAttachmentUnsupported": "Local attachments are not available for remote sessions.",
|
||||
"removeAttachment": "Remove attachment"
|
||||
"removeAttachment": "Remove attachment",
|
||||
"pastedImageLabel": "Pasted image"
|
||||
},
|
||||
"tool": {
|
||||
"running": "Running…",
|
||||
|
||||
@@ -12171,7 +12171,8 @@
|
||||
"stopDictation": "Stop dictation",
|
||||
"noSkills": "No matching skills",
|
||||
"localAttachmentUnsupported": "Local attachments are not available for remote sessions.",
|
||||
"removeAttachment": "Remove attachment"
|
||||
"removeAttachment": "Remove attachment",
|
||||
"pastedImageLabel": "Pasted image"
|
||||
},
|
||||
"tool": {
|
||||
"running": "Running…",
|
||||
|
||||
@@ -12171,7 +12171,8 @@
|
||||
"stopDictation": "Stop dictation",
|
||||
"noSkills": "No matching skills",
|
||||
"localAttachmentUnsupported": "Local attachments are not available for remote sessions.",
|
||||
"removeAttachment": "Remove attachment"
|
||||
"removeAttachment": "Remove attachment",
|
||||
"pastedImageLabel": "Pasted image"
|
||||
},
|
||||
"tool": {
|
||||
"running": "Running…",
|
||||
|
||||
@@ -12171,7 +12171,8 @@
|
||||
"stopDictation": "Stop dictation",
|
||||
"noSkills": "No matching skills",
|
||||
"localAttachmentUnsupported": "Local attachments are not available for remote sessions.",
|
||||
"removeAttachment": "Remove attachment"
|
||||
"removeAttachment": "Remove attachment",
|
||||
"pastedImageLabel": "Pasted image"
|
||||
},
|
||||
"tool": {
|
||||
"running": "Running…",
|
||||
|
||||
@@ -12171,7 +12171,8 @@
|
||||
"stopDictation": "Stop dictation",
|
||||
"noSkills": "No matching skills",
|
||||
"localAttachmentUnsupported": "Local attachments are not available for remote sessions.",
|
||||
"removeAttachment": "Remove attachment"
|
||||
"removeAttachment": "Remove attachment",
|
||||
"pastedImageLabel": "Pasted image"
|
||||
},
|
||||
"tool": {
|
||||
"running": "Running…",
|
||||
|
||||
Reference in New Issue
Block a user