fix(mobile): label native-chat tool rows with a clean, expandable input summary (STA-3333) (#12498)

* fix(mobile): label tool rows with a clean summary, expand full input (STA-3333)

Mobile tool rows showed the raw input JSON (`{"file_path":…}`) as the row
label, and the expanded detail just repeated that same truncated string.

- `describeToolInput` labels a row with the target file path, else the
  primary argument (command/cmd/query/pattern/url/description), else the
  bounded JSON preview.
- Codex delivers tool arguments as a JSON string; normalize those into the
  object shape the helpers already understand, so labels, file links,
  run summaries and the expanded detail all work for Codex calls too.
- The expanded detail now renders the fully formatted input, capped at
  MAX_TOOL_RESULT_CHARS like desktop's tool detail (and like the result
  body), and a structured input makes the row expandable.

* fix(mobile): name search rows by their term and keep the filename in path labels (STA-3333)

Review follow-ups to the tool-row summary, all in the shared helper:

- A Grep/Glob row labelled itself with the directory it scanned and dropped
  the pattern entirely, because `toolFilePath` treats `path` as a file target.
  That path is a scan root, so it also rendered a tap-to-open link that asked
  the app to open a folder. `toolFilePath` now ignores the generic `path` key
  for search-shaped input, which lets the pattern win the label and drops the
  bogus link; an explicit `file_path` still wins.

- An overlong path was truncated from the head, cutting off the basename —
  the one part that tells two rows apart. Trim from the front instead, so
  the label reads `…/session/MobileNativeChatMessage.tsx`.

- The primary-argument chain used `??`, so a present-but-blank key selected
  itself and swallowed the keys ranked after it, dropping the label all the
  way back to raw JSON. Take the first key that actually yields a label.

Refs STA-3333.

* fix(mobile): don't offer an expander whose detail repeats the row (STA-3333)

An empty tool input formats back to the row label verbatim, so `{}` and `[]`
advertised an expander and then re-showed the label — the same repeat-the-JSON
problem this change set out to remove. Gate `isStructuredToolInput` on the
collection actually having contents; the lazy detail path is untouched.

Also pins the overlong-path test to the path itself: asserting only length<=80
plus a `…` passed just as well with path labelling deleted.

* fix(mobile): gate the tool detail panel on having detail (STA-3333)

The Tools toggle opens every row at once, bypassing the row's tap guard,
so a row with nothing to expand rendered its own label again underneath
itself — and the tap that would dismiss it is a no-op. Matches desktop.

* fix(mobile): keep a blank tool argument out of the run header (STA-3333)

Skipping a present-but-blank primary key let `briefToolArg` fall through
to the raw JSON preview, so a run header read `Bash {"command":""}` where
it used to read `Bash`. Also state the search-path trade-off honestly:
suppressing the link costs a file-scoped search its tap target.

* fix(mobile): only treat a blank primary key as a missing argument (STA-3333)

The previous guard tested key presence, so a populated but non-string
argument — a mixed argv like ['kill','-9',pid], or a structured query —
dropped out of the run header instead of falling back to the preview.

* test(mobile): pin the tool-row chevron to the detail panel (STA-3333)

The panel gate was covered but the chevron beside it was not: swapping
`showDetail` back to `expanded` on the icon alone left all 909 mobile
tests green, so the affordance lie this branch fixes could return
unnoticed — a down-chevron over no panel, on a row whose tap is guarded
off.

Asserts both icon counts on the fixture that test already renders. The
two halves now die for distinct reasons: the panel gate on the duplicate
label text, the chevron on the icon count.

* test(shared): pin the blank-search-key guard in the tool label (STA-3333)

Dropping `.trim()` from summarizePrimaryToolArg left all 32 tests green,
yet it leaks through isSearchToolInput: a whitespace-only `query` starts
counting as a search term, which suppresses `path`. One character takes
the row's label, its tap-to-open link and its run-header argument at
once, and puts the raw JSON label back — the bug this branch removes.

Asserts all three outputs on that shape. Kills only that mutant; the
isSearchToolInput mutant still dies on the existing search test.

* fix(native-chat): share tool input display semantics (STA-3333)

Build the tool row label, file target, detail eligibility and bounded detail from one normalized input model. Mobile no longer reparses JSON-string input across independent helpers or repeats an already-complete plain label, and desktop now uses the same clean row summary instead of retaining raw JSON.\n\nKeep full detail formatting lazy for collapsed rows and share the 4000-character detail cap across both renderers. Tests pin desktop adoption, mobile disclosure parity, one-pass JSON parsing and the shared bound.
This commit is contained in:
Brennan Benson
2026-08-04 19:34:59 -07:00
committed by GitHub
parent c3ddc0d5df
commit c511e51442
10 changed files with 527 additions and 59 deletions
@@ -1,7 +1,8 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
import { MAX_TOOL_DETAIL_LENGTH } from './mobile-native-chat-tool-summary'
vi.mock('react-native', async () => {
const React = await import('react')
@@ -30,7 +31,11 @@ function userMessage(blocks: NativeChatMessage['blocks']): NativeChatMessage {
return { id: 'u1', role: 'user', blocks, timestamp: null, source: 'transcript' }
}
describe('MobileNativeChatMessage image-ref rendering', () => {
function toolMessage(blocks: NativeChatMessage['blocks']): NativeChatMessage {
return { id: 'a1', role: 'assistant', blocks, timestamp: null, source: 'transcript' }
}
describe('MobileNativeChatMessage', () => {
let renderer: ReactTestRenderer | null = null
beforeEach(() => {
@@ -41,7 +46,10 @@ describe('MobileNativeChatMessage image-ref rendering', () => {
renderer = null
})
function render(message: NativeChatMessage): ReactTestRenderer {
function render(
message: NativeChatMessage,
props: { toolsExpanded?: boolean } = {}
): ReactTestRenderer {
const original = console.error
const spy = vi.spyOn(console, 'error').mockImplementation((...a) => {
if (typeof a[0] === 'string' && a[0].includes('react-test-renderer is deprecated')) {
@@ -51,7 +59,7 @@ describe('MobileNativeChatMessage image-ref rendering', () => {
})
try {
act(() => {
renderer = create(createElement(MobileNativeChatMessage, { message }))
renderer = create(createElement(MobileNativeChatMessage, { message, ...props }))
})
} finally {
spy.mockRestore()
@@ -59,6 +67,9 @@ describe('MobileNativeChatMessage image-ref rendering', () => {
return renderer!
}
const textIn = (node: ReactTestInstance): string[] =>
node.findAllByType('Text' as never).map((text) => String(text.children.join('')))
it('renders a loadable preview URI as an image thumbnail', () => {
const tree = render(userMessage([{ type: 'image-ref', url: 'file:///a.jpg', alt: 'a photo' }]))
const image = tree.root.findByType('Image' as never)
@@ -84,4 +95,75 @@ describe('MobileNativeChatMessage image-ref rendering', () => {
.map((node) => String(node.children.join('')))
expect(texts.some((text) => text.includes('/tmp/host.png'))).toBe(true)
})
it('labels a tool row with the target path instead of raw input JSON', () => {
const tree = render(
toolMessage([{ type: 'tool-call', name: 'Read', input: { file_path: 'src/index.ts' } }]),
{ toolsExpanded: true }
)
const texts = textIn(tree.root)
expect(texts).toContain('src/index.ts')
expect(texts.some((text) => text.includes('"file_path":"src/index.ts"'))).toBe(false)
})
it('bounds expanded diff-less tool input before native text layout', () => {
const tree = render(
toolMessage([
{ type: 'tool-call', name: 'CustomTool', input: { payload: 'x'.repeat(100_000) } }
]),
{ toolsExpanded: true }
)
const detail = textIn(tree.root).find((text) => text.startsWith('{\n'))
expect(detail).toHaveLength(MAX_TOOL_DETAIL_LENGTH + 1)
expect(detail?.endsWith('…')).toBe(true)
})
it('expands formatted detail for a collapsed JSON-string tool input', () => {
const tree = render(
toolMessage([
{
type: 'tool-call',
name: 'CustomTool',
input: '{"cmd":"git status","description":"Inspect changes"}'
}
])
)
const pressableWith = (label: string): ReactTestInstance =>
tree.root.findAllByType('Pressable' as never).find((node) => textIn(node).includes(label))!
act(() => pressableWith('1×').props.onPress())
// The row label is the command, and the detail stays closed until tapped.
expect(textIn(tree.root)).toContain('git status')
expect(textIn(tree.root).some((text) => text.startsWith('{\n'))).toBe(false)
act(() => pressableWith('CustomTool').props.onPress())
expect(textIn(tree.root)).toContain(
'{\n "cmd": "git status",\n "description": "Inspect changes"\n}'
)
})
it('does not echo the row label as detail when a row has nothing to expand', () => {
// The Tools toggle opens every row at once, bypassing the tap guard — a row
// whose formatted input is its own label would echo itself in a panel that
// no tap can dismiss.
const tree = render(toolMessage([{ type: 'tool-call', name: 'ListTodos', input: '{}' }]), {
toolsExpanded: true
})
expect(textIn(tree.root).filter((text) => text === '{}')).toHaveLength(1)
// The chevron has to agree with the panel, or the row claims to be open over
// nothing and the tap that would close it is guarded off. Only the run header
// is open here; the row itself stays collapsed.
expect(tree.root.findAllByType('ChevronDown' as never)).toHaveLength(1)
expect(tree.root.findAllByType('SquareChevronRight' as never)).toHaveLength(1)
})
it('does not expand a plain input that already fits in the row label', () => {
const input = 'x'.repeat(60)
const tree = render(toolMessage([{ type: 'tool-call', name: 'CustomTool', input }]), {
toolsExpanded: true
})
expect(textIn(tree.root).filter((text) => text === input)).toHaveLength(1)
expect(tree.root.findAllByType('ChevronDown' as never)).toHaveLength(1)
expect(tree.root.findAllByType('SquareChevronRight' as never)).toHaveLength(1)
})
})
+17 -17
View File
@@ -14,12 +14,12 @@ import {
} from './mobile-native-chat-blocks'
import { diffFromText, diffFromToolCall, type DiffLine } from './mobile-native-chat-diff'
import { isRenderableImageUri } from './mobile-native-chat-image-preview'
import { MAX_TOOL_RESULT_CHARS, styles, TEXT_SIZE } from './mobile-native-chat-message-styles'
import { styles, TEXT_SIZE } from './mobile-native-chat-message-styles'
import { nativeChatMessageText } from './mobile-native-chat-message-text'
import {
summarizeToolInput,
createToolInputDisplay,
summarizeToolRun,
toolFilePath
truncateToolDetail
} from './mobile-native-chat-tool-summary'
const MAX_VISIBLE_TOOL_PAIRS = 6
@@ -63,11 +63,7 @@ function ResultBody({
}
return (
<View style={[styles.toolResult, isError && styles.toolResultError]}>
<Text style={styles.mono}>
{output.length > MAX_TOOL_RESULT_CHARS
? `${output.slice(0, MAX_TOOL_RESULT_CHARS)}…`
: output}
</Text>
<Text style={styles.mono}>{truncateToolDetail(output)}</Text>
</View>
)
}
@@ -88,17 +84,21 @@ function ToolLine({
const [expanded, setExpanded] = useState(defaultExpanded)
const { call, result } = pair
const name = call ? call.name : 'Result'
const preview = call
? summarizeToolInput(call.input)
: (result?.output.split('\n')[0]?.slice(0, 80) ?? '')
const inputDisplay = call ? createToolInputDisplay(call.input) : null
const preview = inputDisplay?.label ?? result?.output.split('\n')[0]?.slice(0, 80) ?? ''
// Why: collapsed tool rows are the common path; defer bounded diff parsing
// until the user asks to reveal the detail.
// and detail formatting until the user asks to reveal the detail.
const callDiff = expanded && call ? diffFromToolCall(call.name, call.input, diffLineLimit) : null
const resultDiff = expanded && result ? diffFromText(result.output, diffLineLimit) : null
const hasDetail = callDiff !== null || result !== undefined || preview.length > 40
const callDetail = expanded && inputDisplay && !callDiff ? inputDisplay.formatDetail() : undefined
const hasDetail = callDiff !== null || result !== undefined || inputDisplay?.hasDetail === true
// The group toggle opens every line at once, bypassing the tap guard, so the
// panel has to consult it too — else a detail-less row echoes its own label
// under itself and no tap can dismiss it.
const showDetail = hasDetail && expanded
// A tool that targets a file (Read/Edit/Write…) renders its preview as a
// tappable link that opens the file, independent of the line's expand tap.
const filePath = call ? toolFilePath(call.input) : null
const filePath = inputDisplay?.filePath ?? null
const openable = filePath !== null && onOpenFile !== undefined
return (
<View>
@@ -107,7 +107,7 @@ function ToolLine({
onPress={() => hasDetail && setExpanded((v) => !v)}
hitSlop={6}
>
{expanded ? (
{showDetail ? (
<ChevronDown size={15} color={colors.textMuted} strokeWidth={2} />
) : (
<SquareChevronRight size={15} color={colors.textMuted} strokeWidth={2} />
@@ -124,10 +124,10 @@ function ToolLine({
</Text>
) : null}
</Pressable>
{expanded ? (
{showDetail ? (
<View style={styles.toolDetail}>
{callDiff ? <DiffView lines={callDiff} /> : null}
{!callDiff && call && preview ? <Text style={styles.mono}>{preview}</Text> : null}
{callDetail ? <Text style={styles.mono}>{callDetail}</Text> : null}
{result ? (
<ResultBody output={result.output} isError={result.isError} diff={resultDiff} />
) : null}
@@ -3,7 +3,6 @@ import { colors, radii, spacing, typography } from '../theme/mobile-theme'
export const TEXT_SIZE = 17
export const MONO_SIZE = 12
export const MAX_TOOL_RESULT_CHARS = 4000
export const styles = StyleSheet.create({
row: {
@@ -1,5 +1,10 @@
import { describe, expect, it, vi } from 'vitest'
import { briefToolArg, summarizeToolInput, toolFilePath } from './mobile-native-chat-tool-summary'
import {
briefToolArg,
describeToolInput,
summarizeToolInput,
toolFilePath
} from './mobile-native-chat-tool-summary'
describe('summarizeToolInput', () => {
it('passes short strings through, collapsing whitespace', () => {
@@ -53,6 +58,13 @@ describe('toolFilePath', () => {
})
})
describe('describeToolInput', () => {
it('is re-exported and labels rows with the path or primary argument', () => {
expect(describeToolInput({ file_path: 'src/a.ts', offset: 3 })).toBe('src/a.ts')
expect(describeToolInput('{"cmd":"git status"}')).toBe('git status')
})
})
describe('briefToolArg', () => {
it('takes the basename of a forward-slash path', () => {
expect(briefToolArg({ path: 'src/session/app.ts' })).toBe('app.ts')
@@ -1,7 +1,13 @@
export {
briefToolArg,
countToolCalls,
createToolInputDisplay,
describeToolInput,
formatToolInput,
isStructuredToolInput,
MAX_TOOL_DETAIL_LENGTH,
summarizeToolInput,
summarizeToolRun,
toolFilePath
toolFilePath,
truncateToolDetail
} from '../../../src/shared/native-chat-tool-summary'
@@ -0,0 +1,27 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it } from 'vitest'
import type { NativeChatBlock } from '../../../../shared/native-chat-types'
import { NativeChatToolRun } from './NativeChatToolRun'
afterEach(cleanup)
describe('NativeChatToolRun', () => {
it('uses the shared clean label for a desktop tool row', () => {
const blocks: NativeChatBlock[] = [
{
type: 'tool-call',
name: 'Read',
input: '{"file_path":"src/index.ts","offset":10}'
}
]
render(<NativeChatToolRun blocks={blocks} expandSignal />)
expect(screen.getByTitle('src/index.ts')).toHaveTextContent('src/index.ts')
expect(screen.queryByTitle('{"file_path":"src/index.ts","offset":10}')).toBeNull()
})
})
@@ -10,14 +10,12 @@ import {
import { diffFromText, diffFromToolCall, type DiffLine } from './native-chat-diff'
import {
countToolCalls,
formatToolInput,
summarizeToolInput,
summarizeToolRun
createToolInputDisplay,
summarizeToolRun,
truncateToolDetail
} from './native-chat-tool-summary'
import { NativeChatDiffView } from './NativeChatDiffView'
const MAX_TOOL_RESULT_CHARS = 4000
/** A single inline tool line — `▸ ToolName preview` — that expands in place to
* show the call's diff/input or the result's body. Tool calls read as flat
* lines in the conversation rather than boxed blocks (mobile parity). Lines only
@@ -30,27 +28,26 @@ function ToolLine({ block }: { block: NativeChatBlock }): React.JSX.Element | nu
let preview: string
let diff: DiffLine[] | null = null
let body: { output: string; isError?: boolean } | null = null
// Full, formatted input shown when a diff-less tool call is expanded.
let detail: string | null = null
let inputHasDetail = false
if (isToolCallBlock(block)) {
name = block.name
preview = summarizeToolInput(block.input)
diff = diffFromToolCall(block.name, block.input)
detail = diff ? null : formatToolInput(block.input)
const inputDisplay = createToolInputDisplay(block.input)
preview = inputDisplay.label
inputHasDetail = inputDisplay.hasDetail
diff = expanded ? diffFromToolCall(block.name, block.input) : null
detail = expanded && !diff ? inputDisplay.formatDetail() : null
} else if (isToolResultBlock(block)) {
name = translate('components.native-chat.tool.result', 'Result')
preview = block.output.split('\n')[0]?.slice(0, 80) ?? ''
diff = diffFromText(block.output)
diff = expanded ? diffFromText(block.output) : null
body = { output: block.output, isError: block.isError }
} else {
return null
}
// Only offer expansion when there's more than the inline preview already shows —
// avoids re-rendering the same truncated string in a box below it.
const detailAddsInfo = detail !== null && detail.replace(/\s+/g, ' ').trim() !== preview
const hasDetail = diff !== null || body !== null || detailAddsInfo
const hasDetail = diff !== null || body !== null || inputHasDetail
return (
<div>
@@ -94,16 +91,12 @@ function ToolLine({ block }: { block: NativeChatBlock }): React.JSX.Element | nu
body.isError ? 'text-destructive' : 'text-foreground/80'
)}
>
{body.output.length > MAX_TOOL_RESULT_CHARS
? `${body.output.slice(0, MAX_TOOL_RESULT_CHARS)}…`
: body.output}
{truncateToolDetail(body.output)}
</pre>
) : null}
{!diff && !body && detail ? (
<pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-accent p-2 font-mono text-[11px] text-foreground/80 scrollbar-sleek">
{detail.length > MAX_TOOL_RESULT_CHARS
? `${detail.slice(0, MAX_TOOL_RESULT_CHARS)}…`
: detail}
{detail}
</pre>
) : null}
</div>
@@ -1,8 +1,10 @@
export {
briefToolArg,
countToolCalls,
createToolInputDisplay,
formatToolInput,
summarizeToolInput,
summarizeToolRun,
toolFilePath
toolFilePath,
truncateToolDetail
} from '../../../../shared/native-chat-tool-summary'
+192 -2
View File
@@ -1,6 +1,178 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import type { NativeChatBlock } from './native-chat-types'
import { briefToolArg, summarizeToolInput, summarizeToolRun } from './native-chat-tool-summary'
import {
briefToolArg,
createToolInputDisplay,
describeToolInput,
formatToolInput,
isStructuredToolInput,
MAX_TOOL_DETAIL_LENGTH,
summarizeToolInput,
summarizeToolRun,
toolFilePath,
truncateToolDetail
} from './native-chat-tool-summary'
describe('createToolInputDisplay', () => {
it('builds the shared row model from one JSON-string parse', () => {
const parse = vi.spyOn(JSON, 'parse')
const display = createToolInputDisplay(
'{"file_path":"src/index.ts","description":"Read the entry point"}'
)
expect(display.label).toBe('src/index.ts')
expect(display.filePath).toBe('src/index.ts')
expect(display.hasDetail).toBe(true)
expect(display.formatDetail()).toBe(
'{\n "file_path": "src/index.ts",\n "description": "Read the entry point"\n}'
)
expect(parse).toHaveBeenCalledTimes(1)
parse.mockRestore()
})
it('only offers detail when the formatted input adds information', () => {
expect(createToolInputDisplay('x'.repeat(60)).hasDetail).toBe(false)
expect(createToolInputDisplay('x'.repeat(100)).hasDetail).toBe(true)
expect(createToolInputDisplay('{}').hasDetail).toBe(false)
expect(createToolInputDisplay('{"command":"ls"}').hasDetail).toBe(true)
})
it('bounds tool detail through the shared desktop and mobile cap', () => {
const detail = truncateToolDetail('x'.repeat(MAX_TOOL_DETAIL_LENGTH + 1))
expect(detail).toHaveLength(MAX_TOOL_DETAIL_LENGTH + 1)
expect(detail.endsWith('…')).toBe(true)
})
})
describe('describeToolInput', () => {
it('labels a file-target call with its path, not raw JSON', () => {
expect(describeToolInput({ file_path: '/repo/src/app/Main.tsx', offset: 10 })).toBe(
'/repo/src/app/Main.tsx'
)
expect(describeToolInput({ path: 'src/index.ts' })).toBe('src/index.ts')
expect(describeToolInput({ file_path: 'C:\\Users\\me\\project\\app.tsx' })).toBe(
'C:\\Users\\me\\project\\app.tsx'
)
})
it('labels a command-shaped call with its primary argument', () => {
expect(describeToolInput({ command: 'pnpm test', description: 'Run tests' })).toBe('pnpm test')
expect(describeToolInput({ pattern: 'foo.*bar', glob: '*.ts' })).toBe('foo.*bar')
expect(describeToolInput({ url: 'https://example.com', description: 'Fetch it' })).toBe(
'https://example.com'
)
expect(describeToolInput({ description: 'Only prose' })).toBe('Only prose')
})
it('falls back to the bounded JSON preview for other shapes', () => {
expect(describeToolInput({ todos: [{ id: 1 }] })).toBe(
summarizeToolInput({ todos: [{ id: 1 }] })
)
expect(describeToolInput({ command: ' ' })).toBe(summarizeToolInput({ command: ' ' }))
expect(describeToolInput('raw string input')).toBe('raw string input')
expect(describeToolInput(null)).toBe('')
})
it('truncates an overlong path like any other preview', () => {
const path = `/very/${'long/'.repeat(30)}file.ts`
const label = describeToolInput({ file_path: path })
expect(label.length).toBeLessThanOrEqual(80)
expect(label).toContain('…')
// A bounded JSON preview also satisfies the two assertions above, so pin the
// label to the path itself or this passes with path-labelling deleted.
expect(label).not.toContain('file_path')
expect(label.endsWith('/file.ts')).toBe(true)
})
it('keeps the filename when trimming an overlong path', () => {
// Head-truncating an absolute path drops the basename — the one part that
// tells two rows apart — so the trim has to come off the front.
const path = `/Users/me/orca/workspaces/orca/sta-3333/src/shared/${'nested/'.repeat(4)}app.tsx`
const label = describeToolInput({ file_path: path, offset: 10 })
expect(label.length).toBeLessThanOrEqual(80)
expect(label.startsWith('…')).toBe(true)
expect(label.endsWith('/app.tsx')).toBe(true)
})
it('distinguishes two long paths that share a deep prefix', () => {
const base = '/Users/me/orca/workspaces/orca/sta-3333-tool-summary/src/session/native'
const a = describeToolInput({ file_path: `${base}/MobileNativeChatMessage.tsx` })
const b = describeToolInput({ file_path: `${base}/MobileNativeChatComposer.tsx` })
expect(a).not.toBe(b)
})
it('names a search call by its pattern, not the directory it scanned', () => {
// `path` on a Grep/Glob is the scan root; labelling with it loses the term.
expect(describeToolInput({ pattern: 'summarizeToolInput', path: 'src/shared' })).toBe(
'summarizeToolInput'
)
expect(describeToolInput({ pattern: '**/*.tsx', path: 'mobile/src' })).toBe('**/*.tsx')
expect(describeToolInput({ query: 'auth flow', path: 'src' })).toBe('auth flow')
// ...and offers no open-file link, since that path is a folder.
expect(toolFilePath({ pattern: 'x', path: 'src/shared' })).toBeNull()
expect(briefToolArg({ pattern: 'x', path: 'src/shared' })).toBe('x')
})
it('still treats an explicit file target as one alongside a search term', () => {
expect(toolFilePath({ pattern: 'x', file_path: 'src/a.ts' })).toBe('src/a.ts')
expect(toolFilePath({ path: 'src/c.ts' })).toBe('src/c.ts')
})
it('does not count a blank search key as a search', () => {
// A whitespace-only `query` is no search term, but treating it as one
// suppresses `path` — costing the row its label, its link and its header
// argument all at once, and putting raw JSON back in the label.
expect(toolFilePath({ query: ' ', path: 'src/a.ts' })).toBe('src/a.ts')
expect(describeToolInput({ query: ' ', path: 'src/a.ts' })).toBe('src/a.ts')
expect(briefToolArg({ query: ' ', path: 'src/a.ts' })).toBe('a.ts')
})
it('skips a present-but-blank key instead of falling through to raw JSON', () => {
expect(describeToolInput({ command: '', query: 'needle' })).toBe('needle')
expect(describeToolInput({ command: ' ', url: 'https://example.com' })).toBe(
'https://example.com'
)
expect(briefToolArg({ cmd: '', query: 'needle' })).toBe('needle')
})
})
describe('Codex JSON-string tool arguments', () => {
it('normalizes them for labels, details, file links and run summaries', () => {
expect(describeToolInput('{"cmd":"git status --short"}')).toBe('git status --short')
expect(formatToolInput('{"cmd":"git status --short"}')).toBe(
'{\n "cmd": "git status --short"\n}'
)
expect(toolFilePath('{"file_path":"src/index.ts"}')).toBe('src/index.ts')
expect(briefToolArg('{"file_path":"src/app/index.ts"}')).toBe('index.ts')
expect(briefToolArg('{"cmd":"git status --short"}')).toBe('git status --short')
expect(isStructuredToolInput('{"cmd":"ls"}')).toBe(true)
})
it('joins an argv-array command into one label', () => {
expect(describeToolInput('{"command":["bash","-lc","make"]}')).toBe('bash -lc make')
expect(briefToolArg({ command: ['bash', '-lc', 'make'] })).toBe('bash -lc make')
})
it('leaves prose and malformed JSON as plain strings', () => {
expect(describeToolInput('{ not json')).toBe('{ not json')
expect(formatToolInput('just prose')).toBe('just prose')
expect(toolFilePath('{"file_path":')).toBeNull()
expect(isStructuredToolInput('just prose')).toBe(false)
// A JSON scalar is not an argument object — keep the literal text.
expect(formatToolInput('"quoted"')).toBe('"quoted"')
})
})
describe('isStructuredToolInput', () => {
it('does not offer an expander whose detail would repeat the row label', () => {
// `{}` formats back to `{}` — the label itself.
expect(isStructuredToolInput({})).toBe(false)
expect(isStructuredToolInput([])).toBe(false)
expect(isStructuredToolInput('{}')).toBe(false)
expect(isStructuredToolInput({ command: 'ls' })).toBe(true)
expect(isStructuredToolInput([1])).toBe(true)
})
})
describe('summarizeToolInput bounded preview', () => {
it('collapses depth beyond the bound instead of serializing the whole tree', () => {
@@ -33,6 +205,24 @@ describe('briefToolArg', () => {
it('falls back to the command preview when no path is present', () => {
expect(briefToolArg({ command: 'git status --short' })).toBe('git status --short')
})
it('keeps a blank primary argument out of the run header', () => {
// Skipping a blank key must not fall through to raw JSON — the row would
// read `Bash {"command":""}` where it used to read `Bash`.
expect(briefToolArg({ command: '' })).toBe('')
expect(briefToolArg({ cmd: ' ' })).toBe('')
expect(briefToolArg({ cmd: '', file_path: '' })).toBe('')
const blocks: NativeChatBlock[] = [{ type: 'tool-call', name: 'Bash', input: { command: '' } }]
expect(summarizeToolRun(blocks)).toBe('Bash')
})
it('still previews a primary argument that is populated but not a string', () => {
// Only a *blank* key means "no argument" — a mixed argv or a structured
// query is unrenderable as a label, not absent, so it keeps the preview.
expect(briefToolArg({ command: ['kill', '-9', 1234] })).toBe('{"command":["kill","-9",1234')
expect(briefToolArg({ command: 42 })).toBe('{"command":42}')
expect(briefToolArg({ query: { text: 'auth flow' } })).toBe('{"query":{"text":"auth flow"')
})
})
describe('summarizeToolRun', () => {
+169 -12
View File
@@ -5,6 +5,16 @@ const MAX_PREVIEW_STRING_INPUT = 160
const MAX_PREVIEW_COLLECTION_ITEMS = 8
const MAX_PREVIEW_DEPTH = 2
const MAX_TOOL_RUN_SUMMARY_PARTS = 3
const PRIMARY_ARG_KEYS = ['command', 'cmd', 'query', 'pattern', 'url', 'description'] as const
const BRIEF_ARG_KEYS = ['command', 'cmd', 'query', 'pattern'] as const
export const MAX_TOOL_DETAIL_LENGTH = 4000
export type ToolInputDisplay = {
label: string
filePath: string | null
hasDetail: boolean
formatDetail: () => string
}
export function summarizeToolInput(input: unknown): string {
const collapsed = toRawPreview(input).replace(/\s+/g, ' ').trim()
@@ -13,10 +23,55 @@ export function summarizeToolInput(input: unknown): string {
: `${collapsed.slice(0, MAX_PREVIEW_LENGTH - 1)}…`
}
/** Full, pretty-printed tool-call input for the expanded detail view. Strings
* pass through as-is; objects/arrays print as indented JSON so a diff-less call
* (e.g. a question payload) reads cleanly instead of one long minified line. */
/** Build the renderer-independent row model from one normalization pass. Detail
* formatting stays lazy because collapsed mobile rows never render it. */
export function createToolInputDisplay(input: unknown): ToolInputDisplay {
const normalized = normalizeToolInput(input)
const filePath = normalizedToolFilePath(normalized)
const label = describeNormalizedToolInput(normalized, filePath)
return {
label,
filePath,
hasDetail: normalizedToolInputHasDetail(normalized, label),
formatDetail: () => truncateToolDetail(formatNormalizedToolInput(normalized))
}
}
export function truncateToolDetail(text: string): string {
return text.length > MAX_TOOL_DETAIL_LENGTH ? `${text.slice(0, MAX_TOOL_DETAIL_LENGTH)}…` : text
}
/** Human label for a tool line: the target file path, else the primary string
* argument (command/query/…), else the bounded JSON preview. Keeps raw
* `{"file_path":…}` JSON out of the tappable row label. */
export function describeToolInput(input: unknown): string {
const normalized = normalizeToolInput(input)
return describeNormalizedToolInput(normalized, normalizedToolFilePath(normalized))
}
function describeNormalizedToolInput(input: unknown, path: string | null): string {
if (path) {
return summarizeToolPath(path)
}
if (input && typeof input === 'object') {
// Concrete target/action first; prose `description` only as a last resort.
const primary = firstPrimaryToolArg(input as Record<string, unknown>, PRIMARY_ARG_KEYS)
if (primary) {
return primary
}
}
return summarizeToolInput(input)
}
/** Full, pretty-printed tool-call input for the expanded detail view. Structured
* JSON strings and objects/arrays print as indented JSON so a diff-less call
* (e.g. a question payload) reads cleanly instead of one long minified line;
* other strings pass through as-is. */
export function formatToolInput(input: unknown): string {
return formatNormalizedToolInput(normalizeToolInput(input))
}
function formatNormalizedToolInput(input: unknown): string {
if (input === null || input === undefined) {
return ''
}
@@ -33,29 +88,131 @@ export function formatToolInput(input: unknown): string {
}
}
/** Whether the expanded detail would show structured JSON rather than repeating
* the row label — i.e. whether expanding the row is worth offering. */
export function isStructuredToolInput(input: unknown): boolean {
return isStructuredNormalizedToolInput(normalizeToolInput(input))
}
function isStructuredNormalizedToolInput(input: unknown): boolean {
if (input === null || typeof input !== 'object') {
return false
}
// An empty object formats back to the row label verbatim, so offering the
// expander would promise detail and then repeat the row.
return Array.isArray(input) ? input.length > 0 : Object.keys(input).length > 0
}
function normalizedToolInputHasDetail(input: unknown, label: string): boolean {
if (isStructuredNormalizedToolInput(input)) {
return true
}
return typeof input === 'string' && input.replace(/\s+/g, ' ').trim() !== label
}
export function toolFilePath(input: unknown): string | null {
return normalizedToolFilePath(normalizeToolInput(input))
}
function normalizedToolFilePath(input: unknown): string | null {
if (!input || typeof input !== 'object') {
return null
}
const value = input as Record<string, unknown>
const path = value.file_path ?? value.filePath ?? value.path ?? value.notebook_path
// A search call's `path` is usually the directory it scanned, so taking it as a
// target would label the row with the scan root and link to a folder. Costs the
// link on a file-scoped search; a dead link on every other search is worse.
const directory = isSearchToolInput(value) ? undefined : value.path
const path = value.file_path ?? value.filePath ?? directory ?? value.notebook_path
return typeof path === 'string' && path.length > 0 ? path : null
}
export function briefToolArg(input: unknown): string {
if (input && typeof input === 'object') {
const value = input as Record<string, unknown>
const path = value.file_path ?? value.filePath ?? value.path ?? value.notebook_path
if (typeof path === 'string' && path.length > 0) {
const normalized = normalizeToolInput(input)
if (normalized && typeof normalized === 'object') {
const path = toolFilePath(normalized)
if (path) {
const parts = path.split(/[\\/]/).filter(Boolean)
return parts.at(-1) ?? path
}
const command = value.command ?? value.cmd ?? value.query ?? value.pattern
if (typeof command === 'string') {
return summarizeToolInput(command).slice(0, 28)
const value = normalized as Record<string, unknown>
const command = firstPrimaryToolArg(value, BRIEF_ARG_KEYS)
if (command) {
return command.slice(0, 28)
}
// A blank primary key means the call has no brief argument; falling through
// would stand its raw JSON in for one in the run header. Reaching here with a
// string key means it was blank — a structured one still earns the preview.
if (BRIEF_ARG_KEYS.some((key) => typeof value[key] === 'string')) {
return ''
}
}
return summarizeToolInput(input).slice(0, 28)
return summarizeToolInput(normalized).slice(0, 28)
}
/** Codex delivers tool arguments as a JSON string. Parse those into the object
* shape every helper below already understands; leave prose strings alone. */
function normalizeToolInput(input: unknown): unknown {
if (typeof input !== 'string') {
return input
}
const first = input.trimStart()[0]
if (first !== '{' && first !== '[') {
return input
}
try {
const parsed: unknown = JSON.parse(input)
return parsed !== null && typeof parsed === 'object' ? parsed : input
} catch {
return input
}
}
/** A search call is named by what it looked for, so its `path` is a scan root
* rather than a file target. */
function isSearchToolInput(value: Record<string, unknown>): boolean {
return (
summarizePrimaryToolArg(value.query) !== null || summarizePrimaryToolArg(value.pattern) !== null
)
}
/** The first key that yields a label — a present-but-blank key must not swallow
* the keys ranked after it. */
function firstPrimaryToolArg(
value: Record<string, unknown>,
keys: readonly string[]
): string | null {
for (const key of keys) {
const summary = summarizePrimaryToolArg(value[key])
if (summary) {
return summary
}
}
return null
}
/** A path is identified by its tail, so trim from the front: head-truncating an
* absolute path drops the filename, the one part that tells two rows apart. */
function summarizeToolPath(path: string): string {
const collapsed = path.replace(/\s+/g, ' ').trim()
if (collapsed.length <= MAX_PREVIEW_LENGTH) {
return collapsed
}
const tail = collapsed.slice(collapsed.length - (MAX_PREVIEW_LENGTH - 1))
// Start at a segment boundary so the label doesn't open mid-name.
const boundary = tail.search(/[\\/]/)
return `…${boundary > 0 ? tail.slice(boundary) : tail}`
}
/** A label-worthy primary argument: a non-blank string, or an argv array. */
function summarizePrimaryToolArg(input: unknown): string | null {
if (typeof input === 'string' && input.trim()) {
return summarizeToolInput(input)
}
if (Array.isArray(input) && input.length > 0 && input.every((part) => typeof part === 'string')) {
return summarizeToolInput(input.join(' '))
}
return null
}
export function summarizeToolRun(blocks: readonly NativeChatBlock[]): string {