mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-27 05:41:23 +00:00
fix(web): render Codex goal responses as cards (#1954)
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import type { HTMLAttributes } from 'react'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { I18nProvider } from '@/lib/i18n-context'
|
||||
import { HappySystemMessage } from './SystemMessage'
|
||||
|
||||
const { message } = vi.hoisted(() => ({
|
||||
message: {
|
||||
role: 'system', id: 'status-example',
|
||||
content: [] as { type: string; text: string }[],
|
||||
metadata: { custom: {} as Record<string, unknown> }
|
||||
}
|
||||
}))
|
||||
vi.mock('@assistant-ui/react', () => ({
|
||||
useAuiState: (selector: (state: { message: typeof message }) => unknown) => selector({ message }),
|
||||
MessagePrimitive: { Root: (props: HTMLAttributes<HTMLDivElement>) => <div {...props} /> }
|
||||
}))
|
||||
vi.mock('./MessageTimestamp', () => ({ MessageTimestamp: () => <span>12:00</span> }))
|
||||
|
||||
const goal = {
|
||||
threadId: 'thread-example-1', objective: 'Compare the options and validate the chosen approach.',
|
||||
status: 'active', tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0,
|
||||
createdAt: 1704067200, updatedAt: 1704067200
|
||||
}
|
||||
function show(text: string, eventType = 'message', kind = 'event') {
|
||||
message.content = [{ type: 'text', text }]
|
||||
message.metadata.custom = { kind, event: { type: eventType, message: text } }
|
||||
return render(<I18nProvider><HappySystemMessage /></I18nProvider>)
|
||||
}
|
||||
|
||||
beforeEach(() => { message.role = 'system' })
|
||||
|
||||
describe('slash-command goal status messages', () => {
|
||||
it('renders the actual event/message response as a goal snapshot card', () => {
|
||||
const raw = JSON.stringify({ goal })
|
||||
const { container } = show(raw)
|
||||
expect(screen.getByText('Goal')).toBeInTheDocument()
|
||||
expect(screen.getByText(goal.objective)).toBeInTheDocument()
|
||||
expect(screen.getByText('Active')).toBeInTheDocument()
|
||||
expect(screen.getByText('0 tokens')).toBeInTheDocument()
|
||||
expect(screen.getByText('No limit')).toBeInTheDocument()
|
||||
expect(screen.getByText('0.0s')).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-goal-status="active"]')).not.toBeNull()
|
||||
const details = screen.getByText('Raw JSON').closest('details')!
|
||||
expect(details.open).toBe(false)
|
||||
fireEvent.click(screen.getByText('Raw JSON'))
|
||||
expect(details.open).toBe(true)
|
||||
expect(details.textContent).toContain('thread-example-1')
|
||||
expect(details.textContent).toContain(raw)
|
||||
})
|
||||
|
||||
it('shows an explicitly empty goal', () => {
|
||||
show('{"goal":null}')
|
||||
expect(screen.getByText('No goal set')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each(['Goal cleared', '{broken', '{"objective":"ordinary data"}', JSON.stringify({ goal, error: 'denied' })])
|
||||
('preserves ordinary and malformed status text', (text) => {
|
||||
const { container } = show(text)
|
||||
expect(screen.getByText(text)).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-goal-status]')).toBeNull()
|
||||
})
|
||||
|
||||
it.each([['error', 'event'], ['message', 'other']])('only formats confirmed message events', (eventType, kind) => {
|
||||
const raw = JSON.stringify({ goal })
|
||||
const { container } = show(raw, eventType, kind)
|
||||
expect(screen.getByText(raw)).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-goal-status]')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not format ordinary assistant content', () => {
|
||||
message.role = 'assistant'
|
||||
const { container } = show(JSON.stringify({ goal }))
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,10 @@ import type { HappyChatMessageMetadata } from '@/lib/assistant-runtime'
|
||||
import { getConversationMessageAnchorId } from '@/chat/outline'
|
||||
import { MessageTimestamp } from '@/components/AssistantChat/messages/MessageTimestamp'
|
||||
import { MarkdownRenderer } from '@/components/MarkdownRenderer'
|
||||
import { CodeBlock } from '@/components/CodeBlock'
|
||||
import { parseGoalStatusMessage } from '@/components/ToolCard/goalTools'
|
||||
import { GoalSummary } from '@/components/ToolCard/views/GoalView'
|
||||
import { useTranslation } from '@/lib/use-translation'
|
||||
|
||||
function formatTokenDelta(event: AgentEvent | undefined): string | null {
|
||||
if (!event || event.type !== 'compact-summary') return null
|
||||
@@ -16,17 +20,17 @@ function formatTokenDelta(event: AgentEvent | undefined): string | null {
|
||||
}
|
||||
|
||||
export function HappySystemMessage() {
|
||||
const { t } = useTranslation()
|
||||
const role = useAuiState((s) => s.message.role)
|
||||
const messageId = useAuiState((s) => s.message.id)
|
||||
const text = useAuiState((s) => {
|
||||
if (s.message.role !== 'system') return ''
|
||||
return s.message.content[0]?.type === 'text' ? s.message.content[0].text : ''
|
||||
})
|
||||
const icon = useAuiState((s) => {
|
||||
const event = useAuiState((s) => {
|
||||
if (s.message.role !== 'system') return null
|
||||
const custom = s.message.metadata.custom as Partial<HappyChatMessageMetadata> | undefined
|
||||
const event = custom?.kind === 'event' ? custom.event : undefined
|
||||
return event ? getEventPresentation(event).icon : null
|
||||
return custom?.kind === 'event' ? custom.event : undefined
|
||||
})
|
||||
const compactSummary = useAuiState((s) => {
|
||||
if (s.message.role !== 'system') return undefined
|
||||
@@ -36,6 +40,27 @@ export function HappySystemMessage() {
|
||||
|
||||
if (role !== 'system') return null
|
||||
|
||||
const icon = event ? getEventPresentation(event).icon : null
|
||||
const goalMessage = event?.type === 'message' && typeof event.message === 'string' ? event.message : null
|
||||
const goal = goalMessage !== null ? parseGoalStatusMessage(goalMessage) : null
|
||||
if (goal && goalMessage !== null) {
|
||||
return (
|
||||
<MessagePrimitive.Root id={getConversationMessageAnchorId(messageId)} className="scroll-mt-4 py-1">
|
||||
<section aria-label={t('session.status.goal')} className="mx-auto max-w-[92%] rounded-[20px] bg-[var(--app-tool-card-bg)] p-3 text-left">
|
||||
<div className="mb-2 flex items-center gap-2 text-sm font-medium text-[var(--app-fg)]">
|
||||
<span>{t('session.status.goal')}</span>
|
||||
<MessageTimestamp className="text-[10px] font-normal text-[var(--app-hint)]" />
|
||||
</div>
|
||||
<GoalSummary result={goal} surface="inline" />
|
||||
<details className="mt-3 min-w-0 text-xs text-[var(--app-hint)]">
|
||||
<summary className="cursor-pointer py-1">{t('tool.goal.raw')}</summary>
|
||||
<CodeBlock code={goalMessage} language="json" />
|
||||
</details>
|
||||
</section>
|
||||
</MessagePrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
// Pi compaction summaries are real content, not status: render them as an
|
||||
// independent block (header with token delta + the summary markdown)
|
||||
// instead of the tiny centered status line used for other events.
|
||||
|
||||
@@ -436,7 +436,7 @@ function ToolCardInner(props: ToolCardProps) {
|
||||
const isCodexAgentCard = toolName === 'CodexAgent'
|
||||
const useCompactTerminalCard = shouldUseCompactTerminalToolCard(toolName, props.terminalToolDisplayMode)
|
||||
const showInline = shouldShowInlineToolCardBody(toolName, presentation.minimal, props.terminalToolDisplayMode)
|
||||
const CompactToolView = showInline ? getToolViewComponent(toolName) : null
|
||||
const CompactToolView = showInline ? getToolViewComponent(toolName, props.block.tool) : null
|
||||
const compactViewOwnsInteractions = toolName === 'CodexDiff'
|
||||
const ResultToolView = getToolResultViewComponent(toolName)
|
||||
const permission = props.block.tool.permission
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isGoalToolName, parseGoalToolResult } from './goalTools'
|
||||
|
||||
const goal = {
|
||||
threadId: 'thread-1',
|
||||
objective: 'Compare the options and validate the chosen approach.',
|
||||
status: 'active',
|
||||
tokenBudget: null,
|
||||
tokensUsed: 0,
|
||||
timeUsedSeconds: 0,
|
||||
createdAt: 1704067200,
|
||||
updatedAt: 1704067200
|
||||
}
|
||||
|
||||
describe('goal tool results', () => {
|
||||
it.each([
|
||||
{ goal },
|
||||
JSON.stringify({ goal }),
|
||||
{ output: JSON.stringify({ goal }) },
|
||||
{ result: { content: [{ type: 'text', text: JSON.stringify({ goal }) }] } },
|
||||
[{ type: 'text', text: JSON.stringify({ goal }) }],
|
||||
goal
|
||||
])('reads the goal snapshot from supported envelopes', (result) => {
|
||||
expect(parseGoalToolResult(result)).toEqual({ kind: 'goal', goal })
|
||||
})
|
||||
|
||||
it('keeps an explicit empty goal distinct from missing results', () => {
|
||||
expect(parseGoalToolResult({ goal: null })).toEqual({ kind: 'empty' })
|
||||
expect(parseGoalToolResult(undefined)).toBeNull()
|
||||
expect(parseGoalToolResult(null)).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
'{broken',
|
||||
'Output:\n' + JSON.stringify({ goal }),
|
||||
{ data: { goal } },
|
||||
{ goal: { status: 'active' } },
|
||||
{ goal: { objective: ' ', status: 'active' } },
|
||||
{ isError: true, content: [{ type: 'text', text: JSON.stringify({ goal }) }] },
|
||||
{ error: 'denied', goal },
|
||||
{ result: { result: { result: { result: { result: { goal } } } } } }
|
||||
])('leaves malformed, error and unrelated results to the generic renderer', (result) => {
|
||||
expect(parseGoalToolResult(result)).toBeNull()
|
||||
})
|
||||
|
||||
it('normalizes named snake_case fields and preserves zero and null', () => {
|
||||
expect(parseGoalToolResult({ goal: {
|
||||
objective: goal.objective, status: 'futureState', thread_id: 'thread-2',
|
||||
token_budget: null, tokens_used: 0, time_used_seconds: 0,
|
||||
created_at: 1704067200
|
||||
} })).toEqual({ kind: 'goal', goal: {
|
||||
objective: goal.objective, status: 'futureState', threadId: 'thread-2',
|
||||
tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1704067200
|
||||
} })
|
||||
})
|
||||
|
||||
it('does not invent missing counters or display invalid numeric fields', () => {
|
||||
expect(parseGoalToolResult({ goal: {
|
||||
objective: 'ship', status: 'active', tokensUsed: -1,
|
||||
tokenBudget: Infinity, timeUsedSeconds: NaN, updatedAt: -2
|
||||
} })).toEqual({ kind: 'goal', goal: { objective: 'ship', status: 'active' } })
|
||||
expect(parseGoalToolResult({ goal: { objective: 'ship', status: 'active' } }))
|
||||
.toEqual({ kind: 'goal', goal: { objective: 'ship', status: 'active' } })
|
||||
})
|
||||
|
||||
it('does not substitute snake_case values for explicit camelCase null', () => {
|
||||
expect(parseGoalToolResult({ goal: { ...goal, token_budget: 100 } }))
|
||||
.toEqual({ kind: 'goal', goal })
|
||||
})
|
||||
|
||||
it('stops at the nesting limit and handles circular objects', () => {
|
||||
const cycle: { result?: unknown } = {}
|
||||
cycle.result = cycle
|
||||
expect(parseGoalToolResult(cycle)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('goal tool names', () => {
|
||||
it.each(['create_goal', 'get_goal', 'update_goal', 'functions.create_goal', 'functions.get_goal', 'functions.update_goal'])
|
||||
('recognizes %s', (name) => expect(isGoalToolName(name)).toBe(true))
|
||||
|
||||
it.each(['mcp__other__create_goal', 'other.create_goal', 'recreate_goal', 'functions.functions.create_goal', 'Create_Goal', 'create_goal_extra'])
|
||||
('does not claim unrelated tool %s', (name) => expect(isGoalToolName(name)).toBe(false))
|
||||
})
|
||||
|
||||
|
||||
describe('goal status messages', () => {
|
||||
it('recognizes the complete slash-command response', async () => {
|
||||
const { parseGoalStatusMessage } = await import('./goalTools')
|
||||
expect(parseGoalStatusMessage(JSON.stringify({ goal }))).toEqual({ kind: 'goal', goal })
|
||||
expect(parseGoalStatusMessage('{"goal":null}')).toEqual({ kind: 'empty' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
JSON.stringify(goal),
|
||||
JSON.stringify({ goal, error: 'denied' }),
|
||||
JSON.stringify({ result: { goal } }),
|
||||
JSON.stringify({ goal, unrelated: true }),
|
||||
JSON.stringify({ goal: { objective: 'incomplete' } }),
|
||||
'```json\n' + JSON.stringify({ goal }) + '\n```',
|
||||
'Goal result: ' + JSON.stringify({ goal }),
|
||||
'{broken'
|
||||
])('leaves unrelated and malformed status messages unchanged', async (message) => {
|
||||
const { parseGoalStatusMessage } = await import('./goalTools')
|
||||
expect(parseGoalStatusMessage(message)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import { isObject } from '@hapi/protocol'
|
||||
import type { ChatToolCall } from '@/chat/types'
|
||||
|
||||
const GOAL_TOOL_NAMES = ['create_goal', 'get_goal', 'update_goal'] as const
|
||||
export type GoalToolName = typeof GOAL_TOOL_NAMES[number]
|
||||
|
||||
export function getGoalToolName(name: string): GoalToolName | null {
|
||||
const candidate = name.startsWith('functions.') ? name.slice('functions.'.length) : name
|
||||
return (GOAL_TOOL_NAMES as readonly string[]).includes(candidate) ? candidate as GoalToolName : null
|
||||
}
|
||||
|
||||
export function isGoalToolName(name: string): boolean {
|
||||
return getGoalToolName(name) !== null
|
||||
}
|
||||
|
||||
export type GoalSnapshot = {
|
||||
objective: string
|
||||
status: string
|
||||
threadId?: string
|
||||
tokenBudget?: number | null
|
||||
tokensUsed?: number
|
||||
timeUsedSeconds?: number
|
||||
createdAt?: number
|
||||
updatedAt?: number
|
||||
}
|
||||
|
||||
export type GoalResult = { kind: 'goal'; goal: GoalSnapshot } | { kind: 'empty' }
|
||||
|
||||
function readField(record: Record<string, unknown>, camel: string, snake: string): unknown {
|
||||
return Object.prototype.hasOwnProperty.call(record, camel) ? record[camel] : record[snake]
|
||||
}
|
||||
|
||||
function parseSnapshot(value: unknown): GoalSnapshot | null {
|
||||
if (!isObject(value) || typeof value.objective !== 'string' || !value.objective.trim()
|
||||
|| typeof value.status !== 'string' || !value.status.trim()) return null
|
||||
|
||||
const goal: GoalSnapshot = { objective: value.objective, status: value.status }
|
||||
const threadId = readField(value, 'threadId', 'thread_id')
|
||||
if (typeof threadId === 'string' && threadId.trim()) goal.threadId = threadId
|
||||
|
||||
const fields = [
|
||||
['tokenBudget', 'token_budget'], ['tokensUsed', 'tokens_used'],
|
||||
['timeUsedSeconds', 'time_used_seconds'], ['createdAt', 'created_at'], ['updatedAt', 'updated_at']
|
||||
] as const
|
||||
for (const [camel, snake] of fields) {
|
||||
const number = readField(value, camel, snake)
|
||||
if (camel === 'tokenBudget' && number === null) goal.tokenBudget = null
|
||||
else if (typeof number === 'number' && Number.isFinite(number) && number >= 0) goal[camel] = number
|
||||
}
|
||||
return goal
|
||||
}
|
||||
|
||||
/** Only unwrap documented result/text containers; arbitrary objects are not searched. */
|
||||
export function parseGoalToolResult(result: unknown, depth = 0): GoalResult | null {
|
||||
if (depth > 4) return null
|
||||
if (typeof result === 'string') {
|
||||
const text = result.trim()
|
||||
if (!text.startsWith('{') && !text.startsWith('[')) return null
|
||||
try {
|
||||
return parseGoalToolResult(JSON.parse(text) as unknown, depth)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
if (Array.isArray(result)) {
|
||||
if (result.length === 0 || !result.every((block) => isObject(block)
|
||||
&& block.type === 'text' && typeof block.text === 'string')) return null
|
||||
return parseGoalToolResult(result.map((block) => block.text).join('\n'), depth + 1)
|
||||
}
|
||||
if (!isObject(result) || result.isError === true || result.is_error === true
|
||||
|| (result.error !== undefined && result.error !== null)) return null
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(result, 'goal')) {
|
||||
if (result.goal === null) return { kind: 'empty' }
|
||||
const goal = parseSnapshot(result.goal)
|
||||
return goal ? { kind: 'goal', goal } : null
|
||||
}
|
||||
const goal = parseSnapshot(result)
|
||||
if (goal) return { kind: 'goal', goal }
|
||||
for (const key of ['result', 'output', 'content', 'text']) {
|
||||
if (Object.prototype.hasOwnProperty.call(result, key)) {
|
||||
return parseGoalToolResult(result[key], depth + 1)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The shared Codex /goal command emits a standalone {goal} status message. */
|
||||
export function parseGoalStatusMessage(message: string): GoalResult | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(message)
|
||||
if (!isObject(value) || Object.keys(value).length !== 1
|
||||
|| !Object.prototype.hasOwnProperty.call(value, 'goal')) return null
|
||||
return parseGoalToolResult(value)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getPendingGoalRequest(input: unknown): { kind: 'objective' | 'status'; text: string } | null {
|
||||
if (!isObject(input)) return null
|
||||
if (typeof input.objective === 'string' && input.objective.trim()) return { kind: 'objective', text: input.objective }
|
||||
return typeof input.status === 'string' && input.status.trim() ? { kind: 'status', text: input.status } : null
|
||||
}
|
||||
|
||||
export function canShowGoalPreview(tool: Pick<ChatToolCall, 'input' | 'result' | 'state'>): boolean {
|
||||
if (tool.state === 'error') return false
|
||||
if (tool.state === 'completed') return parseGoalToolResult(tool.result) !== null
|
||||
return getPendingGoalRequest(tool.input) !== null
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { ChecklistItem } from '@/components/ToolCard/checklist'
|
||||
import { extractTodoChecklist, extractUpdatePlanChecklist } from '@/components/ToolCard/checklist'
|
||||
import { basename, resolveDisplayPath } from '@/utils/path'
|
||||
import { getInputStringAny, truncate } from '@/lib/toolInputUtils'
|
||||
import { getGoalToolName } from '@/components/ToolCard/goalTools'
|
||||
import {
|
||||
getCodexAgentActivity,
|
||||
getCodexAgentPrompt,
|
||||
@@ -125,6 +126,18 @@ export const knownTools: Record<string, {
|
||||
subtitle?: (opts: ToolOpts) => string | null
|
||||
minimal?: boolean | ((opts: ToolOpts) => boolean)
|
||||
}> = {
|
||||
create_goal: {
|
||||
icon: () => <BulbIcon className={DEFAULT_ICON_CLASS} />,
|
||||
title: () => 'Create goal'
|
||||
},
|
||||
get_goal: {
|
||||
icon: () => <BulbIcon className={DEFAULT_ICON_CLASS} />,
|
||||
title: () => 'Get goal'
|
||||
},
|
||||
update_goal: {
|
||||
icon: () => <BulbIcon className={DEFAULT_ICON_CLASS} />,
|
||||
title: () => 'Update goal'
|
||||
},
|
||||
// agy transitional "Inside the task-NNN log…" narration → compact chip.
|
||||
// description carries the short "task-NNN log" label from normalizeAgent.
|
||||
AgyTaskLog: {
|
||||
@@ -664,12 +677,13 @@ export function getToolPresentation(
|
||||
}
|
||||
}
|
||||
|
||||
const known = knownTools[opts.toolName]
|
||||
const goalName = getGoalToolName(opts.toolName)
|
||||
const known = knownTools[goalName ?? opts.toolName]
|
||||
if (known) {
|
||||
const minimal = typeof known.minimal === 'function' ? known.minimal(opts) : (known.minimal ?? false)
|
||||
return {
|
||||
icon: known.icon(opts),
|
||||
title: known.title(opts),
|
||||
title: goalName && t ? t(`tool.goal.${goalName}`) : known.title(opts),
|
||||
subtitle: known.subtitle ? known.subtitle(opts) : null,
|
||||
minimal
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { ApiClient } from '@/api/client'
|
||||
import type { ToolCallBlock } from '@/chat/types'
|
||||
import { ToolCard } from '@/components/ToolCard/ToolCard'
|
||||
import { getToolResultViewComponent } from '@/components/ToolCard/views/_results'
|
||||
import { I18nProvider } from '@/lib/i18n-context'
|
||||
|
||||
const goal = {
|
||||
objective: 'Compare the options and validate the chosen approach.', status: 'active', threadId: 'thread-1',
|
||||
tokensUsed: 0, tokenBudget: null, timeUsedSeconds: 0,
|
||||
createdAt: 1704067200, updatedAt: 1704067200
|
||||
}
|
||||
|
||||
function goalBlock(result: unknown, state: ToolCallBlock['tool']['state'] = 'completed', name = 'create_goal', input: unknown = { objective: 'requested objective', status: 'complete' }): ToolCallBlock {
|
||||
return {
|
||||
kind: 'tool-call', id: 'goal-1', localId: null, createdAt: 1000, children: [],
|
||||
tool: {
|
||||
id: 'goal-1', name, state, input,
|
||||
result, description: null, createdAt: 1000, startedAt: 1000, completedAt: 1500,
|
||||
execStartedAt: null, execCompletedAt: null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderGoal(result: unknown, state: ToolCallBlock['tool']['state'] = 'completed', name = 'create_goal', input?: unknown) {
|
||||
return render(<I18nProvider><ToolCard
|
||||
api={{} as ApiClient} sessionId="session-1" metadata={null}
|
||||
terminalToolDisplayMode="detailed" disabled={false} onDone={() => {}} block={goalBlock(result, state, name, input)}
|
||||
/></I18nProvider>)
|
||||
}
|
||||
|
||||
describe('goal cards in ToolCard', () => {
|
||||
beforeEach(() => localStorage.setItem('hapi-lang', 'en'))
|
||||
|
||||
it.each(['create_goal', 'get_goal', 'update_goal', 'functions.create_goal', 'functions.get_goal', 'functions.update_goal'])('shows the snapshot once for %s', (name) => {
|
||||
renderGoal(JSON.stringify({ goal }), 'completed', name)
|
||||
expect(screen.getAllByText(goal.objective)).toHaveLength(1)
|
||||
expect(screen.getByText('Active')).toBeInTheDocument()
|
||||
expect(screen.getByText('0 tokens')).toBeInTheDocument()
|
||||
expect(screen.getByText('No limit')).toBeInTheDocument()
|
||||
expect(screen.getByText('0.0s')).toBeInTheDocument()
|
||||
expect(screen.queryByText('requested objective')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('thread-1')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows token budget consumption without hiding over-budget usage', () => {
|
||||
renderGoal({ goal: { ...goal, tokensUsed: 150, tokenBudget: 100 } })
|
||||
expect(screen.getByText('150 / 100 tokens')).toBeInTheDocument()
|
||||
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '100')
|
||||
expect(screen.getByRole('progressbar')).toHaveAccessibleName('Token budget used')
|
||||
})
|
||||
|
||||
it('shows no goal distinctly', () => {
|
||||
renderGoal({ goal: null })
|
||||
expect(screen.getByText('No goal set')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Active')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not infer successful goal state while pending', () => {
|
||||
renderGoal(undefined, 'pending')
|
||||
expect(screen.getByText('requested objective')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Complete')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['en', 'Requested status', 'Complete'],
|
||||
['zh-CN', '请求的状态', '已完成']
|
||||
])('labels status-only pending requests in %s without a successful state badge', (locale, label, status) => {
|
||||
localStorage.setItem('hapi-lang', locale)
|
||||
const { container } = renderGoal(undefined, 'pending', 'update_goal', { status: 'complete' })
|
||||
expect(screen.getByText(label)).toBeInTheDocument()
|
||||
expect(screen.getByText(status)).toBeInTheDocument()
|
||||
expect(screen.queryByText('complete')).not.toBeInTheDocument()
|
||||
expect(container.querySelector('[data-goal-status]')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps unknown requested statuses readable', () => {
|
||||
renderGoal(undefined, 'pending', 'update_goal', { status: 'futureState' })
|
||||
expect(screen.getByText('Requested status')).toBeInTheDocument()
|
||||
expect(screen.getByText('futureState')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['en', 0, '0.0s'], ['zh-CN', 0, '0.0s'],
|
||||
['en', 0.5, '0.5s'], ['zh-CN', 0.5, '0.5s'],
|
||||
['en', 76, '1m 16s'], ['zh-CN', 76, '1m 16s']
|
||||
])('uses the common duration format for %s at %s seconds', (locale, seconds, duration) => {
|
||||
localStorage.setItem('hapi-lang', locale)
|
||||
const { container } = renderGoal({ goal: { ...goal, timeUsedSeconds: seconds } })
|
||||
expect(within(container.querySelector('[data-goal-status]') as HTMLElement).getByText(duration)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each(['error', 'completed'] as const)('preserves the generic fallback for %s errors', (state) => {
|
||||
renderGoal('Permission denied', state)
|
||||
expect(screen.getByText('Permission denied')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Active')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render a successful-looking goal payload when the tool failed', () => {
|
||||
renderGoal({ goal }, 'error')
|
||||
expect(screen.queryByText('Active')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Result')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps unknown status readable and omits absent metrics', () => {
|
||||
renderGoal({ goal: { objective: goal.objective, status: 'futureState' } })
|
||||
expect(screen.getByText('futureState')).toBeInTheDocument()
|
||||
expect(screen.queryByText('0 tokens')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('0.0s')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows metadata and collapsed original JSON only in the detail dialog', () => {
|
||||
renderGoal({ goal })
|
||||
fireEvent.click(screen.getByRole('button', { expanded: false }))
|
||||
const dialog = screen.getByRole('dialog')
|
||||
expect(within(dialog).getByText('thread-1')).toBeInTheDocument()
|
||||
const raw = within(dialog).getByText('Raw JSON').closest('details')!
|
||||
expect(raw.open).toBe(false)
|
||||
fireEvent.click(within(dialog).getByText('Raw JSON'))
|
||||
expect(within(dialog).getByText('Raw JSON').closest('details')).toBe(raw)
|
||||
})
|
||||
|
||||
it('keeps metadata and raw output when used by a trace result without a surface', () => {
|
||||
const ResultView = getToolResultViewComponent('get_goal')
|
||||
render(<I18nProvider><ResultView block={goalBlock({ goal })} metadata={null} /></I18nProvider>)
|
||||
expect(screen.getByText('thread-1')).toBeInTheDocument()
|
||||
expect(screen.getByText('Raw JSON').closest('details')?.open).toBe(false)
|
||||
})
|
||||
|
||||
it('hides times that overflow millisecond conversion', () => {
|
||||
const { container } = renderGoal({ goal: { ...goal, timeUsedSeconds: Number.MAX_VALUE } })
|
||||
expect(container.textContent).not.toMatch(/Infinity|NaN/)
|
||||
expect(screen.getByText(goal.objective)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { safeStringify } from '@hapi/protocol'
|
||||
import { CodeBlock } from '@/components/CodeBlock'
|
||||
import { formatDuration } from '@/chat/presentation'
|
||||
import { useTranslation } from '@/lib/use-translation'
|
||||
import { getPendingGoalRequest, parseGoalToolResult, type GoalResult } from '../goalTools'
|
||||
import type { ToolViewProps } from './_all'
|
||||
|
||||
const STATUS_TONES: Record<string, string> = {
|
||||
active: 'bg-blue-500/10 text-blue-700 dark:text-blue-300',
|
||||
paused: 'bg-amber-500/10 text-amber-700 dark:text-amber-300',
|
||||
budgetLimited: 'bg-amber-500/10 text-amber-700 dark:text-amber-300',
|
||||
usageLimited: 'bg-amber-500/10 text-amber-700 dark:text-amber-300',
|
||||
blocked: 'bg-red-500/10 text-red-700 dark:text-red-300',
|
||||
complete: 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
|
||||
}
|
||||
|
||||
function formatGoalDate(seconds: number | undefined, locale: string): string | null {
|
||||
if (!seconds || seconds <= 0) return null
|
||||
const date = new Date(seconds * 1000)
|
||||
return Number.isFinite(date.getTime()) ? date.toLocaleString(locale) : null
|
||||
}
|
||||
|
||||
export function GoalSummary({ result, surface }: { result: GoalResult; surface?: 'inline' | 'dialog' }) {
|
||||
const { t, locale } = useTranslation()
|
||||
if (result.kind === 'empty') {
|
||||
return <div className="text-sm text-[var(--app-hint)]">{t('tool.goal.empty')}</div>
|
||||
}
|
||||
const { goal } = result
|
||||
const number = (value: number) => value.toLocaleString(locale)
|
||||
const used = goal.tokensUsed
|
||||
const budget = goal.tokenBudget
|
||||
const durationMs = goal.timeUsedSeconds !== undefined ? goal.timeUsedSeconds * 1000 : null
|
||||
const duration = durationMs !== null && Number.isFinite(durationMs)
|
||||
? formatDuration(durationMs)
|
||||
: null
|
||||
const percentage = used !== undefined && typeof budget === 'number' && budget > 0
|
||||
? Math.min(100, used / budget * 100) : null
|
||||
const tone = Object.prototype.hasOwnProperty.call(STATUS_TONES, goal.status) ? STATUS_TONES[goal.status] : null
|
||||
const metadata = [
|
||||
[t('tool.goal.thread'), goal.threadId],
|
||||
[t('tool.goal.created'), formatGoalDate(goal.createdAt, locale)],
|
||||
[t('tool.goal.updated'), formatGoalDate(goal.updatedAt, locale)]
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-2.5 text-sm" data-goal-status={goal.status}>
|
||||
<div className="flex min-w-0 items-start gap-2.5">
|
||||
<span className={`max-w-[45%] shrink-0 break-words rounded-full px-2 py-0.5 text-[11px] font-medium [overflow-wrap:anywhere] ${tone ?? 'bg-[var(--app-subtle-bg)] text-[var(--app-hint)]'}`}>
|
||||
{tone ? t(`session.status.goal.${goal.status}`) : goal.status}
|
||||
</span>
|
||||
<div className="min-w-0 whitespace-pre-wrap break-words [overflow-wrap:anywhere] text-[var(--app-fg)]">{goal.objective}</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs tabular-nums [overflow-wrap:anywhere] text-[var(--app-hint)]">
|
||||
{used !== undefined ? (
|
||||
<span>{t('tool.goal.tokens', { value: typeof budget === 'number' ? `${number(used)} / ${number(budget)}` : number(used) })}</span>
|
||||
) : typeof budget === 'number' ? (
|
||||
<span>{t('tool.goal.budget', { value: number(budget) })}</span>
|
||||
) : null}
|
||||
{budget === null ? <span>{t('tool.goal.unlimited')}</span> : null}
|
||||
{duration ? <span>{duration}</span> : null}
|
||||
</div>
|
||||
{percentage !== null ? (
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-[var(--app-subtle-bg)]"
|
||||
role="progressbar" aria-label={t('tool.goal.budgetUsed')} aria-valuemin={0} aria-valuemax={100} aria-valuenow={percentage}>
|
||||
<div className="h-full rounded-full bg-[var(--app-link)]" style={{ width: `${percentage}%` }} />
|
||||
</div>
|
||||
) : null}
|
||||
{surface === 'dialog' && metadata.some(([, value]) => value) ? (
|
||||
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 border-t border-[var(--app-border)] pt-2 text-xs">
|
||||
{metadata.filter(([, value]) => value).map(([label, value]) => (
|
||||
<div key={label} className="contents">
|
||||
<dt className="text-[var(--app-hint)]">{label}</dt>
|
||||
<dd className="break-all text-[var(--app-fg)]">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function GoalView({ block, surface }: ToolViewProps) {
|
||||
const { t } = useTranslation()
|
||||
const result = block.tool.state === 'completed' ? parseGoalToolResult(block.tool.result) : null
|
||||
if (!result) {
|
||||
const request = getPendingGoalRequest(block.tool.input)
|
||||
const isStatus = request?.kind === 'status'
|
||||
const text = isStatus && Object.prototype.hasOwnProperty.call(STATUS_TONES, request.text)
|
||||
? t(`session.status.goal.${request.text}`) : request?.text
|
||||
return <div className="whitespace-pre-wrap break-words text-sm text-[var(--app-fg)]">
|
||||
<span className="mb-1 block text-xs text-[var(--app-hint)]">{t(isStatus ? 'tool.goal.requestedStatus' : 'tool.goal.requested')}</span>
|
||||
{text}
|
||||
</div>
|
||||
}
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-3">
|
||||
<GoalSummary result={result} surface={surface} />
|
||||
{surface === 'dialog' ? (
|
||||
<details className="min-w-0 text-xs text-[var(--app-hint)]">
|
||||
<summary className="cursor-pointer py-1">{t('tool.goal.raw')}</summary>
|
||||
<CodeBlock code={typeof block.tool.result === 'string' ? block.tool.result : safeStringify(block.tool.result)} language="json" />
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentType } from 'react'
|
||||
import type { ToolCallBlock } from '@/chat/types'
|
||||
import type { ChatToolCall, ToolCallBlock } from '@/chat/types'
|
||||
import type { SessionMetadataSummary } from '@/types/api'
|
||||
import { CodexDiffCompactView, CodexDiffFullView } from '@/components/ToolCard/views/CodexDiffView'
|
||||
import { CodexPatchView } from '@/components/ToolCard/views/CodexPatchView'
|
||||
@@ -12,6 +12,8 @@ import { MultiEditFullView, MultiEditView } from '@/components/ToolCard/views/Mu
|
||||
import { TodoWriteView } from '@/components/ToolCard/views/TodoWriteView'
|
||||
import { UpdatePlanView } from '@/components/ToolCard/views/UpdatePlanView'
|
||||
import { WriteView } from '@/components/ToolCard/views/WriteView'
|
||||
import { GoalView } from '@/components/ToolCard/views/GoalView'
|
||||
import { canShowGoalPreview, isGoalToolName } from '@/components/ToolCard/goalTools'
|
||||
import { getInputStringAny } from '@/lib/toolInputUtils'
|
||||
import {
|
||||
getCodexAgentFieldRows,
|
||||
@@ -126,7 +128,8 @@ export const toolFullViewRegistry: Record<string, ToolViewComponent> = {
|
||||
request_user_input: RequestUserInputView
|
||||
}
|
||||
|
||||
export function getToolViewComponent(toolName: string): ToolViewComponent | null {
|
||||
export function getToolViewComponent(toolName: string, tool?: Pick<ChatToolCall, 'input' | 'result' | 'state'>): ToolViewComponent | null {
|
||||
if (isGoalToolName(toolName)) return tool && canShowGoalPreview(tool) ? GoalView : null
|
||||
return toolViewRegistry[toolName] ?? null
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import { MarkdownRenderer } from '@/components/MarkdownRenderer'
|
||||
import { ChecklistList, extractTodoChecklist } from '@/components/ToolCard/checklist'
|
||||
import { basename, resolveDisplayPath } from '@/utils/path'
|
||||
import { getInputStringAny } from '@/lib/toolInputUtils'
|
||||
import { isGoalToolName, parseGoalToolResult } from '@/components/ToolCard/goalTools'
|
||||
import { GoalView } from '@/components/ToolCard/views/GoalView'
|
||||
import {
|
||||
getCodexAgentActivity,
|
||||
getCodexAgentTargets,
|
||||
@@ -1070,7 +1072,14 @@ export const toolResultViewRegistry: Record<string, ToolViewComponent> = {
|
||||
exit_plan_mode: MarkdownResultView
|
||||
}
|
||||
|
||||
const GoalResultView: ToolViewComponent = (props) => {
|
||||
return props.block.tool.state === 'completed' && parseGoalToolResult(props.block.tool.result)
|
||||
? <GoalView {...props} surface={props.surface ?? 'dialog'} />
|
||||
: <GenericResultView {...props} />
|
||||
}
|
||||
|
||||
export function getToolResultViewComponent(toolName: string): ToolViewComponent {
|
||||
if (isGoalToolName(toolName)) return GoalResultView
|
||||
if (toolName.startsWith('mcp__')) {
|
||||
return GenericResultView
|
||||
}
|
||||
|
||||
@@ -1183,6 +1183,20 @@ export default {
|
||||
'session.action.syncCodexDisabledActive': 'Stop or archive the running session before syncing Codex history.',
|
||||
'codexSync.manual.success.noNewMessages': 'No new Codex messages.',
|
||||
'session.status.title': 'Session status',
|
||||
'tool.goal.create_goal': 'Create goal',
|
||||
'tool.goal.get_goal': 'Get goal',
|
||||
'tool.goal.update_goal': 'Update goal',
|
||||
'tool.goal.empty': 'No goal set',
|
||||
'tool.goal.tokens': '{value} tokens',
|
||||
'tool.goal.budget': 'Budget: {value} tokens',
|
||||
'tool.goal.unlimited': 'No limit',
|
||||
'tool.goal.budgetUsed': 'Token budget used',
|
||||
'tool.goal.thread': 'Thread',
|
||||
'tool.goal.created': 'Created',
|
||||
'tool.goal.updated': 'Updated',
|
||||
'tool.goal.raw': 'Raw JSON',
|
||||
'tool.goal.requested': 'Requested goal',
|
||||
'tool.goal.requestedStatus': 'Requested status',
|
||||
'session.status.goal': 'Goal',
|
||||
'session.status.tasks': 'Tasks',
|
||||
'session.status.subagents': 'Subagents',
|
||||
|
||||
@@ -1181,6 +1181,20 @@ export default {
|
||||
'session.action.syncCodexDisabledActive': '当前会话正在运行,停止或归档后才能同步 Codex 历史。',
|
||||
'codexSync.manual.success.noNewMessages': '没有新的 Codex 消息。',
|
||||
'session.status.title': '会话状态',
|
||||
'tool.goal.create_goal': '创建目标',
|
||||
'tool.goal.get_goal': '查看目标',
|
||||
'tool.goal.update_goal': '更新目标',
|
||||
'tool.goal.empty': '未设置目标',
|
||||
'tool.goal.tokens': '{value} token',
|
||||
'tool.goal.budget': '预算:{value} token',
|
||||
'tool.goal.unlimited': '无限制',
|
||||
'tool.goal.budgetUsed': 'Token 预算用量',
|
||||
'tool.goal.thread': '会话',
|
||||
'tool.goal.created': '创建时间',
|
||||
'tool.goal.updated': '更新时间',
|
||||
'tool.goal.raw': '原始 JSON',
|
||||
'tool.goal.requested': '请求的目标',
|
||||
'tool.goal.requestedStatus': '请求的状态',
|
||||
'session.status.goal': '目标',
|
||||
'session.status.tasks': '任务',
|
||||
'session.status.subagents': '子代理',
|
||||
|
||||
Reference in New Issue
Block a user