mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(commands): align built-in slash commands with OpenCode v2
Replace the split built-in command name list and switch with one typed registry, so a registered command without a handler is a compile error. Remove the broken themes/share/unshare/editor entries and the hardcoded init; server and custom commands now win on a name clash and built-ins dispatch by registry identity. Add /copy, /btw, /rename, /fork (message picker), /timeline, /model, /agent, /variants, /mcp, /skills, /settings and /connect. Open the model picker through state so /model and the select-model shortcut work while a response is running, load full session history in the fork picker, and keep attachments when a built-in command is submitted. Extract shared clipboard and primary-agent helpers, reuse CopyButton in the manager token settings, and update the Quick Start and chat docs.
This commit is contained in:
1 parent
7cac8baade
commit
7e93eb4c34
35 files changed
+2291
-767
No files matched your search
@@ -0,0 +1,98 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import { SessionMessagePickerDialog } from './SessionMessagePickerDialog'
|
||||
|
||||
function userMessage(id: string, text: string, created = 1000): SessionMessageInfo {
|
||||
return { id, type: 'user', text, time: { created } } as SessionMessageInfo
|
||||
}
|
||||
|
||||
function assistantMessage(id: string, text: string): SessionMessageInfo {
|
||||
return { id, type: 'assistant', text, time: { created: 1000 } } as unknown as SessionMessageInfo
|
||||
}
|
||||
|
||||
const renderPicker = (
|
||||
props: Partial<React.ComponentProps<typeof SessionMessagePickerDialog>> = {},
|
||||
) =>
|
||||
render(
|
||||
<SessionMessagePickerDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
title="Fork session"
|
||||
messages={[]}
|
||||
onSelect={vi.fn()}
|
||||
{...props}
|
||||
/>,
|
||||
)
|
||||
|
||||
describe('SessionMessagePickerDialog', () => {
|
||||
it('lists only user messages, newest first', () => {
|
||||
renderPicker({
|
||||
messages: [
|
||||
userMessage('old', 'older prompt', 1000),
|
||||
assistantMessage('assistant', 'reply'),
|
||||
userMessage('new', 'newer prompt', 2000),
|
||||
],
|
||||
})
|
||||
|
||||
const older = screen.getByText('older prompt')
|
||||
const newer = screen.getByText('newer prompt')
|
||||
|
||||
expect(screen.queryByText('reply')).not.toBeInTheDocument()
|
||||
expect(
|
||||
newer.compareDocumentPosition(older) & Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy()
|
||||
})
|
||||
|
||||
it('narrows the rows with the search query', () => {
|
||||
renderPicker({
|
||||
messages: [userMessage('a', 'alpha prompt'), userMessage('b', 'beta prompt')],
|
||||
})
|
||||
|
||||
expect(screen.getByText('alpha prompt')).toBeInTheDocument()
|
||||
expect(screen.getByText('beta prompt')).toBeInTheDocument()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Search messages'), {
|
||||
target: { value: 'beta' },
|
||||
})
|
||||
|
||||
expect(screen.queryByText('alpha prompt')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('beta prompt')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onSelect with the message id when a row is clicked', () => {
|
||||
const onSelect = vi.fn()
|
||||
renderPicker({ messages: [userMessage('msg-1', 'hello')], onSelect })
|
||||
|
||||
fireEvent.click(screen.getByText('hello'))
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith('msg-1')
|
||||
})
|
||||
|
||||
it('calls onSelect with undefined from the leading row', () => {
|
||||
const onSelect = vi.fn()
|
||||
renderPicker({
|
||||
messages: [userMessage('msg-1', 'hello')],
|
||||
leadingOptionLabel: 'Entire conversation',
|
||||
onSelect,
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('Entire conversation'))
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(undefined)
|
||||
})
|
||||
|
||||
it('shows an empty state when no messages match', () => {
|
||||
renderPicker({ messages: [assistantMessage('a', 'reply')] })
|
||||
|
||||
expect(screen.getByText('No messages')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a loading state instead of the rows while loading', () => {
|
||||
renderPicker({ messages: [userMessage('msg-1', 'hello')], loading: true })
|
||||
|
||||
expect(screen.getByText('Loading messages…')).toBeInTheDocument()
|
||||
expect(screen.queryByText('hello')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('No messages')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
const MESSAGE_PREVIEW_MAX_LENGTH = 200
|
||||
|
||||
interface SessionMessagePickerDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: string
|
||||
messages: SessionMessageInfo[]
|
||||
leadingOptionLabel?: string
|
||||
loading?: boolean
|
||||
onSelect: (messageID: string | undefined) => void
|
||||
}
|
||||
|
||||
function messagePreview(text: string): string {
|
||||
const singleLine = text.replace(/\s+/g, ' ').trim()
|
||||
return singleLine.length > MESSAGE_PREVIEW_MAX_LENGTH
|
||||
? singleLine.slice(0, MESSAGE_PREVIEW_MAX_LENGTH)
|
||||
: singleLine
|
||||
}
|
||||
|
||||
export function SessionMessagePickerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
messages,
|
||||
leadingOptionLabel,
|
||||
loading = false,
|
||||
onSelect,
|
||||
}: SessionMessagePickerDialogProps) {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setQuery('')
|
||||
}, [open])
|
||||
|
||||
const items = useMemo(() => {
|
||||
const userMessages = messages.filter(
|
||||
(message): message is Extract<SessionMessageInfo, { type: 'user' }> =>
|
||||
message.type === 'user' && message.text.trim().length > 0,
|
||||
)
|
||||
const normalizedQuery = query.trim().toLowerCase()
|
||||
const filtered = normalizedQuery
|
||||
? userMessages.filter((message) => message.text.toLowerCase().includes(normalizedQuery))
|
||||
: userMessages
|
||||
return [...filtered].reverse()
|
||||
}, [messages, query])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Search messages"
|
||||
autoFocus
|
||||
className="mt-4"
|
||||
/>
|
||||
<div className="flex flex-col gap-1 max-h-[60vh] overflow-y-auto mt-4">
|
||||
{leadingOptionLabel && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(undefined)}
|
||||
className="w-full rounded-md border border-border px-3 py-2 text-left text-sm hover:bg-accent"
|
||||
>
|
||||
{leadingOptionLabel}
|
||||
</button>
|
||||
)}
|
||||
{loading ? (
|
||||
<span className="px-3 py-2 text-sm text-muted-foreground">Loading messages…</span>
|
||||
) : (
|
||||
<>
|
||||
{items.map((message) => (
|
||||
<button
|
||||
key={message.id}
|
||||
type="button"
|
||||
onClick={() => onSelect(message.id)}
|
||||
className="w-full rounded-md border border-border px-3 py-2 text-left hover:bg-accent"
|
||||
>
|
||||
<span className="block text-sm truncate">{messagePreview(message.text)}</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{new Date(message.time.created).toLocaleTimeString([], { timeStyle: 'short' })}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{items.length === 0 && (
|
||||
<span className="px-3 py-2 text-sm text-muted-foreground">No messages</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { SideQuestionDialog } from './SideQuestionDialog'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
askSideQuestion: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/api/opencode')>()),
|
||||
askSideQuestion: mocks.askSideQuestion,
|
||||
}))
|
||||
|
||||
const renderDialog = (props: Partial<React.ComponentProps<typeof SideQuestionDialog>> = {}) =>
|
||||
render(
|
||||
<SideQuestionDialog
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
sessionID="ses_1"
|
||||
initialQuestion=""
|
||||
{...props}
|
||||
/>,
|
||||
)
|
||||
|
||||
describe('SideQuestionDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('asks a non-empty initial question once on mount and renders the answer', async () => {
|
||||
mocks.askSideQuestion.mockResolvedValue('**42**')
|
||||
|
||||
renderDialog({ initialQuestion: 'what is the answer?' })
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(1))
|
||||
expect(mocks.askSideQuestion).toHaveBeenCalledWith(
|
||||
'ses_1',
|
||||
'what is the answer?',
|
||||
expect.any(AbortSignal),
|
||||
)
|
||||
expect(await screen.findByText('42')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('asks nothing until the user types and submits when the initial question is empty', async () => {
|
||||
mocks.askSideQuestion.mockResolvedValue('because')
|
||||
|
||||
renderDialog()
|
||||
|
||||
expect(mocks.askSideQuestion).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: 'why?' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.askSideQuestion).toHaveBeenCalledWith('ses_1', 'why?', expect.any(AbortSignal)),
|
||||
)
|
||||
expect(await screen.findByText('because')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Retry on failure and asks again when clicked', async () => {
|
||||
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
|
||||
|
||||
renderDialog({ initialQuestion: 'why?' })
|
||||
|
||||
await screen.findByText('Failed to get an answer')
|
||||
|
||||
mocks.askSideQuestion.mockResolvedValueOnce('retried answer')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith('ses_1', 'why?', expect.any(AbortSignal))
|
||||
expect(await screen.findByText('retried answer')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('retries the failed question even when the draft was edited to another value', async () => {
|
||||
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
|
||||
|
||||
renderDialog({ initialQuestion: 'question A' })
|
||||
|
||||
await screen.findByText('Failed to get an answer')
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: 'question B' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
|
||||
'ses_1',
|
||||
'question A',
|
||||
expect.any(AbortSignal),
|
||||
)
|
||||
})
|
||||
|
||||
it('retries the failed question even when the draft was cleared', async () => {
|
||||
mocks.askSideQuestion.mockRejectedValueOnce(new Error('nope'))
|
||||
|
||||
renderDialog({ initialQuestion: 'question A' })
|
||||
|
||||
await screen.findByText('Failed to get an answer')
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: '' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
|
||||
'ses_1',
|
||||
'question A',
|
||||
expect.any(AbortSignal),
|
||||
)
|
||||
})
|
||||
|
||||
it('cancels the pending request when a replacement question is submitted', async () => {
|
||||
let resolveA: (value: string) => void = () => {}
|
||||
let resolveB: (value: string) => void = () => {}
|
||||
let signalA: AbortSignal | undefined
|
||||
let signalB: AbortSignal | undefined
|
||||
|
||||
mocks.askSideQuestion
|
||||
.mockImplementationOnce((_sessionID: string, _question: string, signal?: AbortSignal) => {
|
||||
signalA = signal
|
||||
return new Promise<string>((resolve) => {
|
||||
resolveA = resolve
|
||||
})
|
||||
})
|
||||
.mockImplementationOnce((_sessionID: string, _question: string, signal?: AbortSignal) => {
|
||||
signalB = signal
|
||||
return new Promise<string>((resolve) => {
|
||||
resolveB = resolve
|
||||
})
|
||||
})
|
||||
|
||||
renderDialog({ initialQuestion: 'question A' })
|
||||
|
||||
await waitFor(() => expect(signalA).toBeDefined())
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('Ask a side question'), {
|
||||
target: { value: 'question B' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
|
||||
|
||||
await waitFor(() => expect(mocks.askSideQuestion).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.askSideQuestion).toHaveBeenLastCalledWith(
|
||||
'ses_1',
|
||||
'question B',
|
||||
expect.any(AbortSignal),
|
||||
)
|
||||
expect(signalB).toBeDefined()
|
||||
expect(signalA?.aborted).toBe(true)
|
||||
|
||||
resolveB('answer B')
|
||||
expect(await screen.findByText('answer B')).toBeInTheDocument()
|
||||
|
||||
resolveA('answer A')
|
||||
await waitFor(() => expect(screen.queryByText('answer A')).not.toBeInTheDocument())
|
||||
expect(screen.getByText('answer B')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('aborts the in-flight request when unmounted', async () => {
|
||||
let capturedSignal: AbortSignal | undefined
|
||||
mocks.askSideQuestion.mockImplementation(
|
||||
(_sessionID: string, _question: string, signal?: AbortSignal) => {
|
||||
capturedSignal = signal
|
||||
return new Promise<string>(() => {})
|
||||
},
|
||||
)
|
||||
|
||||
const { unmount } = renderDialog({ initialQuestion: 'why?' })
|
||||
|
||||
await waitFor(() => expect(capturedSignal).toBeDefined())
|
||||
expect(capturedSignal?.aborted).toBe(false)
|
||||
|
||||
unmount()
|
||||
|
||||
expect(capturedSignal?.aborted).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { TextPart } from '@/components/message/TextPart'
|
||||
import { askSideQuestion } from '@/api/opencode'
|
||||
|
||||
interface SideQuestionDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
sessionID: string
|
||||
initialQuestion?: string
|
||||
}
|
||||
|
||||
export function SideQuestionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
sessionID,
|
||||
initialQuestion = '',
|
||||
}: SideQuestionDialogProps) {
|
||||
const [question, setQuestion] = useState(initialQuestion)
|
||||
const [answer, setAnswer] = useState('')
|
||||
const [error, setError] = useState(false)
|
||||
const [pending, setPending] = useState(false)
|
||||
const controllerRef = useRef<AbortController | null>(null)
|
||||
const requestRef = useRef(0)
|
||||
const lastQuestionRef = useRef('')
|
||||
|
||||
const ask = useCallback(async (value: string) => {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return
|
||||
lastQuestionRef.current = trimmed
|
||||
|
||||
controllerRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
controllerRef.current = controller
|
||||
const requestId = ++requestRef.current
|
||||
|
||||
setPending(true)
|
||||
setError(false)
|
||||
setAnswer('')
|
||||
|
||||
try {
|
||||
const result = await askSideQuestion(sessionID, trimmed, controller.signal)
|
||||
if (requestRef.current !== requestId || controller.signal.aborted) return
|
||||
setAnswer(result)
|
||||
setPending(false)
|
||||
} catch {
|
||||
if (requestRef.current !== requestId || controller.signal.aborted) return
|
||||
setError(true)
|
||||
setPending(false)
|
||||
}
|
||||
}, [sessionID])
|
||||
|
||||
useEffect(() => {
|
||||
if (initialQuestion.trim()) {
|
||||
void ask(initialQuestion)
|
||||
}
|
||||
return () => {
|
||||
controllerRef.current?.abort()
|
||||
}
|
||||
}, [ask, initialQuestion])
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
void ask(question)
|
||||
}
|
||||
|
||||
const handleRetry = () => {
|
||||
void ask(lastQuestionRef.current)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogTitle>Side question</DialogTitle>
|
||||
<form onSubmit={handleSubmit} className="flex items-center gap-2 mt-4">
|
||||
<Input
|
||||
value={question}
|
||||
onChange={(event) => setQuestion(event.target.value)}
|
||||
placeholder="Ask a side question"
|
||||
autoFocus
|
||||
/>
|
||||
<Button type="submit" disabled={!question.trim()}>
|
||||
Ask
|
||||
</Button>
|
||||
</form>
|
||||
{pending && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span>Thinking...</span>
|
||||
</div>
|
||||
)}
|
||||
{error && !pending && (
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-destructive">Failed to get an answer</span>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleRetry}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{answer && !pending && (
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1 max-h-[50vh] overflow-y-auto">
|
||||
<TextPart text={answer} />
|
||||
</div>
|
||||
<CopyButton content={answer} title="Copy answer" />
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user