fix(commands): run multi-line and Enter commands, restore focus, refresh forks

- Match command arguments across newlines so a multi-line /btw or custom
  command runs instead of being sent as plain text.
- Run a typed command on plain Enter once its name is complete, while
  Enter stays a new line for regular text and Shift+Enter for commands.
- Focus the prompt when a session opens on a pointer device, and return
  focus to the previously focused element when a dialog closes, except a
  text field on touch so the keyboard stays closed.
- Invalidate the session list on session.forked so a forked session shows
  in the sidebar without waiting for the next event.
- Correct the Quick Start keyboard shortcuts.
This commit is contained in:
Chris Scott committed 2026-10-02 10:45:20 -04:00
1 parent 7e93eb4c34
commit 7102715068
10 files changed
+330 -17

No files matched your search

+4 -3
View File
@@ -80,7 +80,7 @@ If you already used standalone OpenCode in those repositories, existing chats ap
1. Select your repository from the sidebar
2. Click **New Session** or type `/new`
3. Type your message
4. Press **Enter** to send
4. Press **Cmd+Enter** (`Ctrl+Enter` on other platforms) to send, or **Enter** on mobile
### Useful Commands
@@ -105,7 +105,7 @@ If you already used standalone OpenCode in those repositories, existing chats ap
| `/skills` | Load a skill |
| `/connect` | Connect a provider |
Built-in commands use only the command text. Attached files and images are kept in the composer for your next message.
Press **Enter** to run a command once its name is complete; use **Shift+Enter** to continue its text on a new line. Built-in commands use only the command text. Attached files and images are kept in the composer for your next message.
### File Mentions
@@ -129,7 +129,8 @@ Now that you're set up, explore more features:
| Shortcut | Action |
|----------|--------|
| `Enter` | Send message |
| `Cmd+Enter` / `Ctrl+Enter` | Send message |
| `Enter` | Run a slash command, such as `/btw <question>`; otherwise a new line on desktop, send on mobile |
| `Shift+Enter` | New line |
The app uses a configurable leader key system (`Cmd+O` on Mac, `Ctrl+O` on other platforms) for additional shortcuts. Customize in Settings > Keyboard Shortcuts.
@@ -1,11 +1,11 @@
import { createRef } from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput, type PromptInputHandle } from './PromptInput'
import { useUIState } from '@/stores/uiStateStore'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
import { createCommandActionsMock } from '@/test/test-utils'
import { createCommandActionsMock, stubMatchMedia } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
runCommand: vi.fn(),
@@ -187,6 +187,39 @@ describe('PromptInput command submission', () => {
useUIState.getState().clearPendingPromptFile()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('focuses the prompt on open with a fine pointer', async () => {
stubMatchMedia(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
expect(input).toHaveFocus()
})
it('does not focus the prompt on open on touch devices', async () => {
stubMatchMedia(false)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
expect(input).not.toHaveFocus()
})
it('does not take focus from an element that already has it', async () => {
stubMatchMedia(true)
const other = document.createElement('button')
document.body.appendChild(other)
other.focus()
renderComponent()
await screen.findByPlaceholderText('Send a message...')
expect(other).toHaveFocus()
other.remove()
})
it('sends parsed command attachments and offsets to runCommand without injecting the selected agent', async () => {
const { container } = renderComponent()
@@ -226,6 +259,53 @@ describe('PromptInput command submission', () => {
expect(call.skills).toEqual([])
})
it('runs a command whose arguments span multiple lines', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/review first line\nsecond line' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled())
expect(mocks.runCommand.mock.calls[0][0]).toMatchObject({
name: 'review',
text: 'first line\nsecond line',
})
})
it('submits on plain Enter when the prompt is a known command', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/btw first line\nsecond line' } })
fireEvent.keyDown(input, { key: 'Enter' })
await waitFor(() => expect(defaultProps.commandActions.askSideQuestion).toHaveBeenCalledWith('first line\nsecond line'))
})
it('does not submit a known command on Shift+Enter', async () => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/btw hi' } })
fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled()
expect(input).toHaveValue('/btw hi')
})
it.each(['hello there', '/bt hi', '/unknown hi'])('does not submit %j on plain Enter', async (value) => {
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(input).toHaveValue(value)
expect(mocks.runCommand).not.toHaveBeenCalled()
expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled()
})
it('preserves the submitted command text when the command submission fails', async () => {
mocks.runCommand.mockRejectedValueOnce(new Error('command failed'))
renderComponent()
@@ -14,6 +14,7 @@ import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useUIState } from '@/stores/uiStateStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { useMobile } from '@/hooks/useMobile'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
import { usePermissions } from '@/contexts/EventContext'
import { ArrowDown, Upload, X, Mic, MicOff } from 'lucide-react'
@@ -40,6 +41,11 @@ import { isBuiltinCommand, type CommandActions, type PageCommandActions } from '
const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"]
function parseCommandPrompt(value: string): { name: string; args?: string } | null {
const match = value.match(/^\/([a-zA-Z0-9_-]+)(?:\s+([\s\S]*))?$/)
return match ? { name: match[1], args: match[2] } : null
}
const revokeBlobUrls = (attachments: ImageAttachment[]) => {
attachments.forEach((attachment) => {
@@ -133,6 +139,14 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const textareaRef = useRef<HTMLTextAreaElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const voiceButtonContainerRef = useRef<HTMLDivElement | null>(null)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
useEffect(() => {
if (!hasFinePointer) return
const activeElement = document.activeElement
if (activeElement && activeElement !== document.body) return
textareaRef.current?.focus()
}, [hasFinePointer, sessionID])
const resetVoiceGestureState = useCallback(() => {
voiceGestureStartYRef.current = null
@@ -215,6 +229,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending
const interruptSession = useInterruptSession()
const { filterCommands } = useCommands({ directory })
const isExactCommandPrompt = (value: string) => {
const commandPrompt = parseCommandPrompt(value)
if (!commandPrompt) return false
const [command] = filterCommands(commandPrompt.name)
return command?.name.toLowerCase() === commandPrompt.name.toLowerCase()
}
const { files: searchResults } = useFileSearch(
mentionQuery,
@@ -330,13 +350,12 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/)
if (commandMatch) {
const [, commandName, commandArgs] = commandMatch
const command = filterCommands(commandName)[0]
const commandPrompt = parseCommandPrompt(prompt)
if (commandPrompt) {
const command = filterCommands(commandPrompt.name)[0]
if (command) {
const parsed = parsePromptToInput(commandArgs?.trim() || '', attachedFiles, agentNames, imageAttachments)
const parsed = parsePromptToInput(commandPrompt.args?.trim() || '', attachedFiles, agentNames, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
@@ -961,7 +980,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}
}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey || (isMobile && !e.shiftKey))) {
if (e.key === 'Enter' && !e.nativeEvent.isComposing && (e.metaKey || e.ctrlKey || (!e.shiftKey && (isMobile || isExactCommandPrompt(prompt))))) {
e.preventDefault()
if (isMobile) {
textareaRef.current?.blur()
@@ -1,5 +1,7 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { useState } from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
import { SessionMessagePickerDialog } from './SessionMessagePickerDialog'
@@ -25,7 +27,48 @@ const renderPicker = (
/>,
)
function FocusHost() {
const [open, setOpen] = useState(false)
return (
<>
<textarea aria-label="prompt" />
<button type="button" onClick={() => setOpen(true)}>open</button>
{open && (
<SessionMessagePickerDialog
open
onOpenChange={(next) => {
if (!next) setOpen(false)
}}
title="Fork session"
messages={[]}
onSelect={vi.fn()}
/>
)}
</>
)
}
describe('SessionMessagePickerDialog', () => {
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('focuses its search on open and returns focus to the previous element on Escape', async () => {
stubMatchMedia(true)
render(<FocusHost />)
const prompt = screen.getByLabelText('prompt')
prompt.focus()
fireEvent.click(screen.getByText('open'))
const search = await screen.findByPlaceholderText('Search messages')
await waitFor(() => expect(search).toHaveFocus())
fireEvent.keyDown(search, { key: 'Escape' })
await waitFor(() => expect(prompt).toHaveFocus())
})
it('lists only user messages, newest first', () => {
renderPicker({
messages: [
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { stubMatchMedia } from '@/test/test-utils'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { useState } from 'react'
import { SideQuestionDialog } from './SideQuestionDialog'
const mocks = vi.hoisted(() => ({
@@ -22,11 +24,50 @@ const renderDialog = (props: Partial<React.ComponentProps<typeof SideQuestionDia
/>,
)
function FocusHost() {
const [open, setOpen] = useState(false)
return (
<>
<textarea aria-label="prompt" />
<button type="button" onClick={() => setOpen(true)}>open</button>
{open && (
<SideQuestionDialog
open
sessionID="ses_1"
onOpenChange={(next) => {
if (!next) setOpen(false)
}}
/>
)}
</>
)
}
describe('SideQuestionDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('focuses its input on open and returns focus to the previous element on Escape', async () => {
stubMatchMedia(true)
render(<FocusHost />)
const prompt = screen.getByLabelText('prompt')
prompt.focus()
fireEvent.click(screen.getByText('open'))
const input = await screen.findByPlaceholderText('Ask a side question')
await waitFor(() => expect(input).toHaveFocus())
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() => expect(prompt).toHaveFocus())
})
it('asks a non-empty initial question once on mount and renders the answer', async () => {
mocks.askSideQuestion.mockResolvedValue('**42**')
+75 -1
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, act } from "@testing-library/react";
import { useState } from "react";
import { render, screen, act, fireEvent, waitFor } from "@testing-library/react";
import { stubMatchMedia } from "@/test/test-utils";
import {
Dialog,
DialogContent,
@@ -398,6 +400,78 @@ describe("DialogHeader", () => {
});
});
function ReturnFocusHost({ onCloseAutoFocus }: { onCloseAutoFocus?: (event: Event) => void }) {
const [open, setOpen] = useState(false)
return (
<>
<textarea aria-label="prompt" />
<button type="button" onClick={() => setOpen(true)}>open</button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent onCloseAutoFocus={onCloseAutoFocus}>
<DialogTitle>Focus Dialog</DialogTitle>
<input aria-label="dialog input" autoFocus />
</DialogContent>
</Dialog>
</>
)
}
async function openAndEscape(returnTarget: HTMLElement) {
returnTarget.focus()
fireEvent.click(screen.getByText('open'))
const input = await screen.findByLabelText('dialog input')
await waitFor(() => expect(input).toHaveFocus())
fireEvent.keyDown(input, { key: 'Escape' })
await waitFor(() => expect(screen.queryByLabelText('dialog input')).not.toBeInTheDocument())
await act(() => new Promise((resolve) => setTimeout(resolve, 0)))
}
describe('Dialog return focus', () => {
afterEach(() => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('returns focus to the element focused before opening when there is no trigger', async () => {
stubMatchMedia(true)
render(<ReturnFocusHost />)
const prompt = screen.getByLabelText('prompt')
await openAndEscape(prompt)
expect(prompt).toHaveFocus()
})
it('does not refocus a text field on touch devices, so the keyboard stays closed', async () => {
stubMatchMedia(false)
render(<ReturnFocusHost />)
const prompt = screen.getByLabelText('prompt')
await openAndEscape(prompt)
expect(prompt).not.toHaveFocus()
})
it('refocuses a non-text element on touch devices', async () => {
stubMatchMedia(false)
render(<ReturnFocusHost />)
const opener = screen.getByText('open')
await openAndEscape(opener)
expect(opener).toHaveFocus()
})
it('lets a caller onCloseAutoFocus that prevents default take over', async () => {
stubMatchMedia(true)
render(<ReturnFocusHost onCloseAutoFocus={(event) => event.preventDefault()} />)
const prompt = screen.getByLabelText('prompt')
await openAndEscape(prompt)
expect(prompt).not.toHaveFocus()
})
})
function stubVisualViewport(height: number) {
const listeners = new Set<() => void>()
Object.defineProperty(window, 'visualViewport', {
+34 -2
View File
@@ -5,13 +5,37 @@ import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import { useSwipeBack } from '@/hooks/useMobile'
import { useVisualViewport } from '@/hooks/useVisualViewport'
import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
const DialogOpenContext = React.createContext<boolean>(true)
const DialogReturnFocusContext = React.createContext<HTMLElement | null>(null)
function getFocusedElement(): HTMLElement | null {
return typeof document !== 'undefined' && document.activeElement instanceof HTMLElement
? document.activeElement
: null
}
function canRestoreFocus(element: HTMLElement): boolean {
if (!element.isConnected || element === document.body) return false
if (!element.matches('input, textarea, [contenteditable="true"]')) return true
return typeof window.matchMedia === 'function' && window.matchMedia(FINE_POINTER_MEDIA_QUERY).matches
}
function Dialog({ open, ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
const [openState, setOpenState] = React.useState(() => ({
open,
returnFocus: open ? getFocusedElement() : null,
}))
if (openState.open !== open) {
setOpenState({ open, returnFocus: open ? getFocusedElement() : openState.returnFocus })
}
return (
<DialogOpenContext.Provider value={open ?? true}>
<DialogPrimitive.Root open={open} {...props} />
<DialogReturnFocusContext.Provider value={openState.returnFocus}>
<DialogPrimitive.Root open={open} {...props} />
</DialogReturnFocusContext.Provider>
</DialogOpenContext.Provider>
)
}
@@ -53,9 +77,16 @@ interface DialogContentProps
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, ...props }, ref) => {
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, ...props }, ref) => {
const isMobileFullscreenMode = fullscreen || mobileFullscreen
const isDialogOpen = React.useContext(DialogOpenContext)
const returnFocus = React.useContext(DialogReturnFocusContext)
const handleCloseAutoFocus = (event: Event) => {
onCloseAutoFocus?.(event)
if (event.defaultPrevented || !returnFocus || !canRestoreFocus(returnFocus)) return
event.preventDefault()
returnFocus.focus()
}
const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false)
const shouldEnableMobileSwipe = mobileSwipeToClose !== false && isMobile && isDialogOpen
const shouldAnimateSwipe = shouldEnableMobileSwipe && isMobileFullscreenMode
@@ -118,6 +149,7 @@ const DialogContent = React.forwardRef<
)}
style={Object.keys(mergedStyle).length > 0 ? mergedStyle : undefined}
{...props}
onCloseAutoFocus={handleCloseAutoFocus}
>
{children}
{shouldEnableMobileSwipe && (
@@ -1433,6 +1433,26 @@ describe('EventProvider permissions and forms', () => {
expect(invalidateQueries).toHaveBeenCalledTimes(1)
})
it('invalidates the session list when a session is forked', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
render(<Harness />, { wrapper: createWrapper(queryClient) })
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
act(() => {
onEvent({ type: 'session.forked', data: { sessionID: 'session-fork', parentID: 'session-9' }, directory: '/repo' })
})
await waitFor(() => {
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true)
})
})
it('invalidates only the session list for the event directory', async () => {
const queryClient = createTestQueryClient()
queryClient.setQueryData(['opencode', 'sessions', '/repo-a'], { pages: [], pageParams: [] })
+1
View File
@@ -509,6 +509,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
break
}
case 'session.created':
case 'session.forked':
case 'session.renamed':
case 'session.moved':
case 'session.metadata.updated':
+2
View File
@@ -2,6 +2,8 @@ import { useEffect, useState } from 'react'
export const DESKTOP_MEDIA_QUERY = '(min-width: 640px)'
export const FINE_POINTER_MEDIA_QUERY = '(hover: hover) and (pointer: fine)'
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState<boolean>(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {