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
95 changes: 88 additions & 7 deletions ui-packages/web/src/features/conversation/composer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
import { ArrowUp, Paperclip, Square } from 'lucide-react'
import { type DragEvent, type RefObject, useLayoutEffect, useRef, useState } from 'react'
import {
type DragEvent,
type RefObject,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
} from 'react'
import type { ConversationDraft } from '../../../core/conversations'
import { DraftAttachmentTray } from '../conversation-attachments'
import { ConversationModelControl, type ModelControlProps } from '../model-control'
import type { ConversationPhase } from '../use-conversation'
import type { DraftAttachment } from '../use-draft-attachments'
import { QueuedMessages } from './queued-messages'
import {
commandOptionId,
isCommandInput,
matchCommands,
type SlashCommand,
SlashCommandMenu,
} from './slash-command-menu'
import styles from './style.module.scss'

type ComposerProps = {
Expand All @@ -29,6 +44,7 @@ type ComposerProps = {
onSend: () => void
onStop: () => void
availableFileIds: ReadonlySet<string>
commands: readonly SlashCommand[]
}

const resizeTextarea = (textarea: HTMLTextAreaElement) => {
Expand Down Expand Up @@ -57,9 +73,22 @@ export const ConversationComposer = ({
onSend,
onStop,
availableFileIds,
commands,
}: ComposerProps) => {
const pickerRef = useRef<HTMLInputElement>(null)
const [dragging, setDragging] = useState(false)
// A typed command stays here and never reaches the saved draft. A draft that is not empty was
// changed from outside (queued messages returned on stop), so it wins.
// Known glitch, left on purpose: the hidden command shows again once that draft is sent. It is
// never saved; fix it here if it starts to matter.
const [typedCommand, setTypedCommand] = useState('')
const [selected, setSelected] = useState(0)
const [dismissed, setDismissed] = useState(false)
const menuId = useId()
const command = draft ? '' : typedCommand
const value = draft || command
const matches = command ? matchCommands(command, commands) : []
const menuOpen = !dismissed && matches.length > 0
const running = phase === 'running' || phase === 'stopping'
const readyAttachments = attachments.filter(item => item.status === 'ready')
const hasUnavailable = readyAttachments.some(item => !availableFileIds.has(item.metadata.id))
Expand All @@ -68,7 +97,11 @@ export const ConversationComposer = ({
(phase === 'ready' || running) &&
!unsettled &&
!hasUnavailable &&
Boolean(draft.trim() || readyAttachments.length)
Boolean(value.trim() || readyAttachments.length)

useEffect(() => {
if (phase === 'switching') setTypedCommand('')
}, [phase])

useLayoutEffect(() => {
const textarea = inputRef.current
Expand All @@ -80,6 +113,45 @@ export const ConversationComposer = ({
return () => observer.disconnect()
}, [inputRef])

const changeText = (text: string) => {
setSelected(0)
setDismissed(false)
if (isCommandInput(text)) {
setTypedCommand(text)
if (draft) onDraftChange('')
return
}
setTypedCommand('')
onDraftChange(text)
}

const runCommand = (picked: SlashCommand) => {
setTypedCommand('')
picked.run()
}

// A command nothing matches, or one whose menu was closed, is sent as an ordinary message.
const submit = () => {
if (!canSend) return
if (command) {
setTypedCommand('')
onDraftChange(command)
}
onSend()
}

const handleMenuKey = (key: string) => {
const picked = matches[selected]
if (!picked) return false
if (key === 'ArrowDown') setSelected((selected + 1) % matches.length)
else if (key === 'ArrowUp') setSelected((selected - 1 + matches.length) % matches.length)
else if (key === 'Enter') runCommand(picked)
else if (key === 'Tab') setTypedCommand(`/${picked.name}`)
else if (key === 'Escape') setDismissed(true)
else return false
return true
}

const addDroppedFiles = (event: DragEvent<HTMLFieldSetElement>) => {
event.preventDefault()
setDragging(false)
Expand Down Expand Up @@ -115,15 +187,20 @@ export const ConversationComposer = ({
onRemove={onRemove}
availableFileIds={availableFileIds}
/>
{menuOpen && (
<SlashCommandMenu id={menuId} commands={matches} selected={selected} onRun={runCommand} />
)}
<textarea
ref={inputRef}
disabled={phase === 'loading' || phase === 'switching'}
aria-label="Your question"
placeholder="Ask about what you are reading"
value={draft}
placeholder="Ask about what you are reading, / for commands"
aria-controls={menuOpen ? menuId : undefined}
aria-activedescendant={menuOpen ? commandOptionId(menuId, selected) : undefined}
value={value}
onChange={event => {
resizeTextarea(event.currentTarget)
onDraftChange(event.target.value)
changeText(event.target.value)
}}
onPaste={event => {
const files = Array.from(event.clipboardData.files)
Expand All @@ -134,14 +211,18 @@ export const ConversationComposer = ({
rows={1}
onKeyDown={event => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return
if (menuOpen && !event.shiftKey && handleMenuKey(event.key)) {
event.preventDefault()
return
}
if (event.key === 'Escape' && running) {
event.preventDefault()
onStop()
return
}
if (event.key !== 'Enter' || event.shiftKey) return
event.preventDefault()
if (canSend) onSend()
submit()
}}
/>
<div className={styles.bottom}>
Expand Down Expand Up @@ -195,7 +276,7 @@ export const ConversationComposer = ({
aria-label={running ? 'Queue message' : 'Send question'}
title={running ? 'Queue message' : 'Send question'}
disabled={!canSend}
onClick={onSend}
onClick={submit}
>
<ArrowUp size={17} />
</button>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import styles from './style.module.scss'

export type SlashCommand = { name: string; description: string; run: () => void }

// A command is typed as one word; a space or a line break turns it back into a message.
export const isCommandInput = (text: string) => /^\/\S*$/.test(text)

export const matchCommands = (input: string, commands: readonly SlashCommand[]) =>
commands.filter(command => command.name.startsWith(input.slice(1)))

export const commandOptionId = (menuId: string, index: number) => `${menuId}-${index}`

export const SlashCommandMenu = ({
id,
commands,
selected,
onRun,
}: {
id: string
commands: readonly SlashCommand[]
selected: number
onRun: (command: SlashCommand) => void
}) => (
<div id={id} role="listbox" aria-label="Commands" className={styles.commandMenu}>
{commands.map((command, index) => (
<button
type="button"
key={command.name}
id={commandOptionId(id, index)}
role="option"
aria-selected={index === selected}
tabIndex={-1}
className={styles.commandOption}
// The textarea keeps focus and handles the keys.
onMouseDown={event => event.preventDefault()}
onClick={() => onRun(command)}
>
<span className={styles.commandName}>/{command.name}</span>
<span className={styles.commandDescription}>{command.description}</span>
</button>
))}
</div>
)
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,40 @@
flex-shrink: 0;
}

.commandMenu {
display: grid;
gap: 2px;
margin: 0 0 8px;
}
.commandOption {
display: flex;
align-items: baseline;
gap: 10px;
min-width: 0;
padding: 5px 8px;
border: 0;
border-radius: 5px;
background: transparent;
color: inherit;
font-size: 12px;
text-align: left;
cursor: pointer;
}
.commandOption[aria-selected="true"] {
background: color-mix(in oklch, var(--surface) 90%, var(--accent));
}
.commandName {
flex-shrink: 0;
font-weight: 550;
}
.commandDescription {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--muted);
}

@media (max-width: 599px) {
.composer textarea {
font-size: 16px;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'
import type { ConversationAttachment } from '../../core/agent/reader-message'
import { emptyConversationDraft } from '../../core/conversations'
import { getStoredConversation, saveStoredConversationDraft } from '../../data/conversation-store'
import {
countStoredConversations,
getStoredConversation,
saveStoredConversationDraft,
} from '../../data/conversation-store'
import { Workbench } from '../../shell/workbench'
import { modelConfig as config, isTitleRequest } from '../../test/model-config'
import { testProject } from '../../test/project'
Expand Down Expand Up @@ -566,6 +570,35 @@ describe('conversation', () => {
expect(await screen.findByText('Second answer')).toBeVisible()
})

it('starts a new conversation from /clear without saving the command anywhere', async () => {
const user = userEvent.setup({ delay: null })
vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {
if (url === '/api/agent/config') return Response.json(config)
if (isTitleRequest(init)) return Response.json({}, { status: 503 })
return complete('First answer')
})
open()
await waitFor(() => expect(question()).toBeEnabled())
await user.type(question(), 'First topic')
await user.click(send())
expect(await screen.findByText('First answer')).toBeVisible()
const previous = activeConversationId()

await user.type(question(), '/cl')
const menu = screen.getByRole('listbox', { name: 'Commands' })
expect(within(menu).getByRole('option', { name: /clear/ })).toBeVisible()
await user.keyboard('{Enter}')

await waitFor(() => {
expect(screen.queryByText('First answer')).not.toBeInTheDocument()
expect(question()).toHaveValue('')
})
expect((await getStoredConversation(previous))?.conversation.draft).toEqual(
emptyConversationDraft(),
)
expect(await countStoredConversations()).toBe(1)
})

it('names a conversation after its first reply and keeps a name the reader chose', async () => {
const user = userEvent.setup({ delay: null })
let titleRequests = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export const ConversationPanel = ({
draftAttachments,
} = conversation
const running = phase === 'running' || phase === 'stopping'
const commands = [
{ name: 'clear', description: 'Start a new conversation', run: () => void startNew() },
]
const switching = phase === 'switching'
const status =
phase === 'loading'
Expand Down Expand Up @@ -149,6 +152,7 @@ export const ConversationPanel = ({
onSend={send}
onStop={stop}
availableFileIds={availableFileIds}
commands={commands}
/>
</div>
</div>
Expand Down