mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(chat): group exploration tool calls
Collapse consecutive read, search and fetch tool calls in the chat transcript into one expandable summary line, matching the OpenCode TUI. Adds a groupToolCalls preference (default on) with a Settings toggle.
This commit is contained in:
1 parent
81dd00e89f
commit
02d2e89bca
8 files changed
+242
-10
No files matched your search
@@ -0,0 +1,54 @@
|
||||
import { memo, useState } from 'react'
|
||||
import { ChevronRight, Loader2 } from 'lucide-react'
|
||||
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useToolCallPermission } from '@/contexts/EventContext'
|
||||
import { explorationLabel, isExplorationComplete } from '@/lib/explorationGroups'
|
||||
import { MessagePart } from './MessagePart'
|
||||
|
||||
interface ExplorationGroupProps {
|
||||
parts: SessionMessageAssistantTool[]
|
||||
messageID: string
|
||||
directory?: string
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onChildSessionClick?: (sessionId: string) => void
|
||||
}
|
||||
|
||||
type MemberProps = Omit<ExplorationGroupProps, 'parts'> & { part: SessionMessageAssistantTool }
|
||||
|
||||
function PermissionBlockedMember(props: MemberProps) {
|
||||
const pendingPermission = useToolCallPermission(props.part.id, props.messageID)
|
||||
if (props.part.state.status !== 'running' || pendingPermission === null) return null
|
||||
return <MessagePart {...props} />
|
||||
}
|
||||
|
||||
/** Collapsed summary of consecutive read, search, and fetch tool calls, expandable to the individual calls. */
|
||||
export const ExplorationGroup = memo(function ExplorationGroup({ parts, ...memberProps }: ExplorationGroupProps) {
|
||||
const { preferences } = useSettings()
|
||||
const [expanded, setExpanded] = useState(preferences?.expandToolCalls ?? false)
|
||||
const completed = isExplorationComplete(parts)
|
||||
|
||||
return (
|
||||
<div className="my-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
aria-expanded={expanded}
|
||||
className="group flex w-full min-w-0 items-center gap-2 py-0.5 text-left text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{completed ? <span className="shrink-0">→</span> : <Loader2 className="w-3.5 h-3.5 shrink-0 animate-spin" />}
|
||||
<span className="truncate">{explorationLabel(parts)}</span>
|
||||
<ChevronRight className={`w-3.5 h-3.5 shrink-0 opacity-0 group-hover:opacity-100 transition-transform ${expanded ? 'rotate-90 opacity-100' : ''}`} />
|
||||
</button>
|
||||
{expanded ? (
|
||||
<div className="ml-1.5 border-l border-border pl-3">
|
||||
{parts.map((part) => (
|
||||
<MessagePart key={part.id} part={part} {...memberProps} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
parts.map((part) => <PermissionBlockedMember key={part.id} part={part} {...memberProps} />)
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -59,6 +59,7 @@ interface MockSettingsReturn {
|
||||
preferences: {
|
||||
simpleChatMode: boolean
|
||||
showReasoning: boolean
|
||||
groupToolCalls?: boolean
|
||||
} | undefined
|
||||
}
|
||||
|
||||
@@ -113,6 +114,14 @@ const subagentTool = (description: string, sessionID?: string): SessionMessageAs
|
||||
time: { created: Date.now(), completed: Date.now() + 100 },
|
||||
})
|
||||
|
||||
const readTool = (id: string, path: string): SessionMessageAssistantTool => ({
|
||||
type: 'tool',
|
||||
id,
|
||||
name: 'read',
|
||||
state: { status: 'completed', input: { path }, content: [{ type: 'text', text: 'contents' }], metadata: {} },
|
||||
time: { created: Date.now(), ran: Date.now(), completed: Date.now() + 100 },
|
||||
})
|
||||
|
||||
const textPart = (text: string): SessionMessageAssistant['content'][number] => ({ type: 'text', text })
|
||||
|
||||
const reasoningPart = (text: string): SessionMessageAssistant['content'][number] => ({ type: 'reasoning', text })
|
||||
@@ -141,6 +150,35 @@ describe('MessageThread', () => {
|
||||
useUIState.getState().setIsEditingMessage(false)
|
||||
})
|
||||
|
||||
it('collapses consecutive exploration tools into one expandable summary', () => {
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false })
|
||||
const messages = [
|
||||
assistantMessage('1', [readTool('r1', '/repo/a.ts'), readTool('r2', '/repo/b.ts'), shellTool('pnpm test')]),
|
||||
]
|
||||
|
||||
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
|
||||
|
||||
const summary = screen.getByRole('button', { name: /Explored: 2 reads/ })
|
||||
expect(screen.queryByText('/repo/a.ts')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('pnpm test')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(summary)
|
||||
|
||||
expect(summary).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByText('/repo/a.ts')).toBeInTheDocument()
|
||||
expect(screen.getByText('/repo/b.ts')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders exploration tools individually when grouping is disabled', () => {
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false, groupToolCalls: false })
|
||||
const messages = [assistantMessage('1', [readTool('r1', '/repo/a.ts'), readTool('r2', '/repo/b.ts')])]
|
||||
|
||||
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
|
||||
|
||||
expect(screen.queryByText(/Explored/)).not.toBeInTheDocument()
|
||||
expect(screen.getByText('/repo/a.ts')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders instruction updates as a single notice line without the instruction body', () => {
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false })
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ import { useSettings } from '@/hooks/useSettings'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { TTSButton } from '@/components/ui/tts-button'
|
||||
import { backgroundShellID, collectBackgroundParts, type ShellNoticeOutcome } from '@/lib/backgroundWork'
|
||||
import { groupExplorationParts, type AssistantContentItem } from '@/lib/explorationGroups'
|
||||
import { ExplorationGroup } from './ExplorationGroup'
|
||||
|
||||
function getMessageText(message: SessionMessageInfo): string {
|
||||
switch (message.type) {
|
||||
@@ -325,6 +327,7 @@ interface MessageRowProps {
|
||||
model?: string
|
||||
simpleChatMode: boolean
|
||||
showReasoning: boolean
|
||||
groupToolCalls: boolean
|
||||
shellOutcomes: ReadonlyMap<string, ShellNoticeOutcome>
|
||||
}
|
||||
|
||||
@@ -344,6 +347,7 @@ const MessageRow = memo(function MessageRow({
|
||||
model,
|
||||
simpleChatMode,
|
||||
showReasoning,
|
||||
groupToolCalls,
|
||||
shellOutcomes,
|
||||
}: MessageRowProps) {
|
||||
const messageTextContent = getMessageText(message)
|
||||
@@ -456,6 +460,9 @@ const MessageRow = memo(function MessageRow({
|
||||
)
|
||||
}
|
||||
|
||||
const contentItems: AssistantContentItem[] = groupToolCalls && !simpleChatMode
|
||||
? groupExplorationParts(message.content, showReasoning)
|
||||
: message.content.map((part) => ({ type: 'part', part }))
|
||||
const isFree = (message.cost ?? 0) === 0
|
||||
const totalTokens = message.tokens
|
||||
? message.tokens.input + message.tokens.output + message.tokens.reasoning + message.tokens.cache.read
|
||||
@@ -478,16 +485,26 @@ const MessageRow = memo(function MessageRow({
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{message.content.map((part, partIndex) => (
|
||||
<div key={`${message.id}-${part.type}-${partIndex}`}>
|
||||
<MessagePart
|
||||
part={part}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
shellOutcome={shellOutcomeFor(part)}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
/>
|
||||
{contentItems.map((item, itemIndex) => (
|
||||
<div key={`${message.id}-${item.type === 'exploration' ? `exploration-${item.parts[0].id}` : `${item.part.type}-${itemIndex}`}`}>
|
||||
{item.type === 'exploration' ? (
|
||||
<ExplorationGroup
|
||||
parts={item.parts}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
/>
|
||||
) : (
|
||||
<MessagePart
|
||||
part={item.part}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
shellOutcome={shellOutcomeFor(item.part)}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!simpleChatMode && message.snapshot?.files && (
|
||||
@@ -573,6 +590,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
const { preferences } = useSettings()
|
||||
const simpleChatMode = preferences?.simpleChatMode ?? false
|
||||
const showReasoning = preferences?.showReasoning ?? false
|
||||
const groupToolCalls = preferences?.groupToolCalls ?? true
|
||||
|
||||
const lastUserMessageId = useMemo(() => findLastUserMessageId(messages), [messages])
|
||||
|
||||
@@ -634,6 +652,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
model={model}
|
||||
simpleChatMode={simpleChatMode}
|
||||
showReasoning={showReasoning}
|
||||
groupToolCalls={groupToolCalls}
|
||||
shellOutcomes={shellOutcomes}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -143,6 +143,20 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between gap-4 py-3">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<Label htmlFor="groupToolCalls">Group exploration</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Collapse consecutive reads, searches, and fetches into one summary line
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="groupToolCalls"
|
||||
checked={preferences?.groupToolCalls ?? true}
|
||||
onCheckedChange={(checked) => updateSettings({ groupToolCalls: checked })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between gap-4 py-3">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<Label htmlFor="expandToolCalls">Expand tool calls</Label>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { SessionMessageAssistant, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
|
||||
import { explorationLabel, groupExplorationParts } from './explorationGroups'
|
||||
|
||||
const tool = (id: string, name: string, status: 'completed' | 'running' = 'completed'): SessionMessageAssistantTool =>
|
||||
status === 'completed'
|
||||
? { type: 'tool', id, name, state: { status, input: {}, content: [], metadata: {} }, time: { created: 0, ran: 0, completed: 1 } }
|
||||
: { type: 'tool', id, name, state: { status, input: {} }, time: { created: 0, ran: 0 } }
|
||||
|
||||
const text = (value: string): SessionMessageAssistant['content'][number] => ({ type: 'text', text: value })
|
||||
const reasoning = (value: string): SessionMessageAssistant['content'][number] => ({ type: 'reasoning', text: value })
|
||||
|
||||
describe('groupExplorationParts', () => {
|
||||
it('collapses consecutive exploration tools and breaks runs on visible non-exploration parts', () => {
|
||||
const items = groupExplorationParts(
|
||||
[tool('a', 'read'), tool('b', 'grep'), text('found it'), tool('c', 'read'), tool('d', 'shell'), tool('e', 'glob')],
|
||||
false,
|
||||
)
|
||||
expect(items.map((item) => (item.type === 'exploration' ? item.parts.map((part) => part.id) : item.part.type))).toEqual([
|
||||
['a', 'b'],
|
||||
'text',
|
||||
['c'],
|
||||
'tool',
|
||||
['e'],
|
||||
])
|
||||
})
|
||||
|
||||
it('does not let hidden reasoning or blank text split a run', () => {
|
||||
const items = groupExplorationParts([tool('a', 'read'), reasoning('thinking'), text(' '), tool('b', 'read')], false)
|
||||
expect(items).toHaveLength(1)
|
||||
expect(items[0]).toMatchObject({ type: 'exploration' })
|
||||
})
|
||||
|
||||
it('lets visible reasoning split a run', () => {
|
||||
expect(groupExplorationParts([tool('a', 'read'), reasoning('thinking'), tool('b', 'read')], true)).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('explorationLabel', () => {
|
||||
it('counts tools with TUI nouns and pluralization', () => {
|
||||
expect(explorationLabel([tool('a', 'read'), tool('b', 'read'), tool('c', 'grep'), tool('d', 'glob'), tool('e', 'webfetch')]))
|
||||
.toBe('Explored: 2 reads, 2 searches, 1 fetch')
|
||||
})
|
||||
|
||||
it('reports in-progress groups as exploring', () => {
|
||||
expect(explorationLabel([tool('a', 'read'), tool('b', 'read', 'running')])).toBe('Exploring: 2 reads')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { SessionMessageAssistant, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
|
||||
|
||||
type AssistantContentPart = SessionMessageAssistant['content'][number]
|
||||
|
||||
export type AssistantContentItem =
|
||||
| { type: 'part'; part: AssistantContentPart }
|
||||
| { type: 'exploration'; parts: SessionMessageAssistantTool[] }
|
||||
|
||||
const EXPLORATION_TOOLS = new Set(['read', 'glob', 'grep', 'webfetch', 'websearch'])
|
||||
|
||||
function isExplorationTool(part: AssistantContentPart): part is SessionMessageAssistantTool {
|
||||
return part.type === 'tool' && EXPLORATION_TOOLS.has(part.name.toLowerCase())
|
||||
}
|
||||
|
||||
function isInvisiblePart(part: AssistantContentPart, showReasoning: boolean): boolean {
|
||||
if (part.type === 'text') return part.text.trim().length === 0
|
||||
if (part.type === 'reasoning') return !showReasoning || part.text.trim().length === 0
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses consecutive read, search, and fetch tool calls into exploration groups, matching the
|
||||
* OpenCode TUI. Parts that render nothing are dropped so they do not split a run.
|
||||
*/
|
||||
export function groupExplorationParts(
|
||||
content: SessionMessageAssistant['content'],
|
||||
showReasoning: boolean,
|
||||
): AssistantContentItem[] {
|
||||
return content.reduce<AssistantContentItem[]>((items, part) => {
|
||||
if (isInvisiblePart(part, showReasoning)) return items
|
||||
const previous = items.at(-1)
|
||||
if (!isExplorationTool(part)) items.push({ type: 'part', part })
|
||||
else if (previous?.type === 'exploration') previous.parts.push(part)
|
||||
else items.push({ type: 'exploration', parts: [part] })
|
||||
return items
|
||||
}, [])
|
||||
}
|
||||
|
||||
/** Whether every tool in an exploration group has finished, successfully or not. */
|
||||
export function isExplorationComplete(parts: SessionMessageAssistantTool[]): boolean {
|
||||
return parts.every((part) => part.state.status === 'completed' || part.state.status === 'error')
|
||||
}
|
||||
|
||||
/** TUI-style summary such as `Explored: 5 reads, 2 searches`. */
|
||||
export function explorationLabel(parts: SessionMessageAssistantTool[]): string {
|
||||
const counts = new Map<string, number>()
|
||||
parts.forEach((part) => {
|
||||
const tool = part.name.toLowerCase()
|
||||
const noun = tool === 'grep' || tool === 'glob' || tool === 'websearch' ? 'search' : tool === 'webfetch' ? 'fetch' : tool
|
||||
counts.set(noun, (counts.get(noun) ?? 0) + 1)
|
||||
})
|
||||
const names = [...counts].map(([noun, count]) =>
|
||||
`${count} ${count === 1 ? noun : noun === 'search' || noun === 'fetch' ? `${noun}es` : `${noun}s`}`,
|
||||
)
|
||||
return `${isExplorationComplete(parts) ? 'Explored' : 'Exploring'}: ${names.join(', ')}`
|
||||
}
|
||||
@@ -55,6 +55,7 @@ export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({
|
||||
autoScroll: true,
|
||||
expandDiffs: true,
|
||||
expandToolCalls: true,
|
||||
groupToolCalls: true,
|
||||
showReasoning: true,
|
||||
simpleChatMode: true,
|
||||
leaderKey: true,
|
||||
|
||||
@@ -173,6 +173,7 @@ export const UserPreferencesSchema = z.object({
|
||||
autoScroll: z.boolean(),
|
||||
expandDiffs: z.boolean(),
|
||||
expandToolCalls: z.boolean(),
|
||||
groupToolCalls: z.boolean(),
|
||||
showReasoning: z.boolean(),
|
||||
simpleChatMode: z.boolean(),
|
||||
leaderKey: z.string().optional(),
|
||||
@@ -228,6 +229,7 @@ export const DEFAULT_USER_PREFERENCES = {
|
||||
autoScroll: true,
|
||||
expandDiffs: true,
|
||||
expandToolCalls: false,
|
||||
groupToolCalls: true,
|
||||
showReasoning: false,
|
||||
simpleChatMode: false,
|
||||
leaderKey: DEFAULT_LEADER_KEY,
|
||||
|
||||
Reference in new issue
Block a user