Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions server/coding-cli/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,8 @@ export function isSystemContext(text: string): boolean {
if (/^<(environment_context|system_context|system|context|INSTRUCTIONS|user_instructions|permissions|collaboration_mode|skills_instructions)[>\s]/i.test(trimmed)) return true
// Instruction file headers: "# AGENTS.md instructions for...", "# System", "# Instructions"
if (/^#\s*(AGENTS|Instructions?|System)/i.test(trimmed)) return true
// Claude Code injects invoked skills as user-role context with the skill path first.
if (/^Base directory for this skill:\s+/i.test(trimmed)) return true
// Bracketed agent mode instructions: [SUGGESTION MODE: ...], [REVIEW MODE: ...]
if (/^\[[A-Z][A-Z_ ]*:/.test(trimmed)) return true
// IDE context format: "# Context from my IDE setup:"
Expand Down
110 changes: 80 additions & 30 deletions server/fresh-agent/adapters/claude/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
import type { QuestionDefinition, SdkSessionState } from '../../../sdk-bridge-types.js'
import type { SdkSessionStatus } from '../../../sdk-bridge-types.js'
import type { ContentBlock } from '../../../../shared/ws-protocol.js'
import { extractUserAuthoredText, isSystemContext } from '../../../coding-cli/utils.js'
import {
FreshAgentSnapshotSchema,
FreshAgentTurnBodySchema,
Expand Down Expand Up @@ -107,9 +108,63 @@ function blockSummary(blocks: ContentBlock[]): string {
return ''
}

function itemSummary(items: FreshAgentNormalizedItem[]): string {
const textItem = items.find((item): item is Extract<FreshAgentNormalizedItem, { kind: 'text' }> => (
item.kind === 'text' && item.text.trim().length > 0
))
if (textItem) return textItem.text.trim().slice(0, 140)

const thinkingItem = items.find((item): item is Extract<FreshAgentNormalizedItem, { kind: 'thinking' }> => (
item.kind === 'thinking' && item.text.trim().length > 0
))
if (thinkingItem) return thinkingItem.text.trim().slice(0, 140)

const toolItem = items.find((item): item is Extract<FreshAgentNormalizedItem, { kind: 'tool_use' }> => (
item.kind === 'tool_use'
))
if (toolItem) return toolItem.name.slice(0, 140)

return ''
}

function normalizeClaudeItem(
role: FreshAgentNormalizedTurn['role'],
turnId: string,
block: ContentBlock,
index: number,
): FreshAgentNormalizedItem | null {
const id = `${turnId}:item:${index}`
switch (block.type) {
case 'text': {
const text = role === 'user' ? extractUserAuthoredText(block.text) : block.text
return text ? { id, kind: 'text', text } : null
}
case 'thinking':
return { id, kind: 'thinking', text: block.thinking }
case 'tool_use':
return { id, kind: 'tool_use', toolUseId: block.id, name: block.name, input: block.input }
case 'tool_result':
return {
id,
kind: 'tool_result',
toolUseId: block.tool_use_id,
content: block.content,
isError: Boolean(block.is_error),
}
}
}

export function normalizeClaudeTurn(
input: Pick<ClaudeFreshAgentHistoryTurn, 'turnId' | 'messageId' | 'ordinal' | 'source' | 'message'>,
): FreshAgentNormalizedTurn {
): FreshAgentNormalizedTurn | null {
const items = input.message.content
.map((block, index) => normalizeClaudeItem(input.message.role, input.turnId, block, index))
.filter((item): item is FreshAgentNormalizedItem => item !== null)

if (input.message.role === 'user' && items.length === 0) {
return null
}

return {
id: input.turnId,
turnId: input.turnId,
Expand All @@ -119,29 +174,15 @@ export function normalizeClaudeTurn(
role: input.message.role,
...(input.message.timestamp ? { timestamp: input.message.timestamp } : {}),
...(input.message.model ? { model: input.message.model } : {}),
summary: blockSummary(input.message.content),
items: input.message.content.map((block, index) => {
const id = `${input.turnId}:item:${index}`
switch (block.type) {
case 'text':
return { id, kind: 'text', text: block.text }
case 'thinking':
return { id, kind: 'thinking', text: block.thinking }
case 'tool_use':
return { id, kind: 'tool_use', toolUseId: block.id, name: block.name, input: block.input }
case 'tool_result':
return {
id,
kind: 'tool_result',
toolUseId: block.tool_use_id,
content: block.content,
isError: Boolean(block.is_error),
}
}
}),
summary: itemSummary(items) || blockSummary(input.message.content),
items,
}
}

function isSyntheticUserTimelineItem(item: Pick<ClaudeFreshAgentHistoryPage['items'][number], 'role' | 'summary'>): boolean {
return item.role === 'user' && isSystemContext(item.summary)
}

function normalizePendingApprovals(liveSession?: SdkSessionState): FreshAgentPendingApproval[] {
if (!liveSession) return []
return Array.from(liveSession.pendingPermissions.entries()).map(([requestId, approval]) => ({
Expand Down Expand Up @@ -169,7 +210,9 @@ export function normalizeClaudeThreadSnapshot(input: {
status: SdkSessionStatus
}): FreshAgentClaudeSnapshot {
const sessionId = input.liveSession?.sessionId ?? input.resolved.liveSessionId ?? input.threadId
const turns = input.resolved.turns.map((turn) => normalizeClaudeTurn(turn))
const turns = input.resolved.turns
.map((turn) => normalizeClaudeTurn(turn))
.filter((turn): turn is FreshAgentNormalizedTurn => turn !== null)
const inputTokens = input.liveSession?.totalInputTokens ?? 0
const outputTokens = input.liveSession?.totalOutputTokens ?? 0
return FreshAgentSnapshotSchema.parse({
Expand All @@ -178,7 +221,7 @@ export function normalizeClaudeThreadSnapshot(input: {
threadId: input.threadId,
sessionId,
revision: input.resolved.revision,
latestTurnId: input.resolved.latestTurnId,
latestTurnId: turns.at(-1)?.turnId ?? null,
status: input.status,
capabilities: {
send: true,
Expand Down Expand Up @@ -216,13 +259,22 @@ export function normalizeClaudeTurnPage(input: {
threadId: string
page: ClaudeFreshAgentHistoryPage
}): FreshAgentClaudeTurnPage {
const items = input.page.items.filter((item) => !isSyntheticUserTimelineItem(item))
const bodies = input.page.bodies
? Object.fromEntries(
Object.entries(input.page.bodies)
.map(([turnId, turn]) => [turnId, normalizeClaudeTurn(turn)] as const)
.filter((entry): entry is readonly [string, FreshAgentNormalizedTurn] => entry[1] !== null),
)
: undefined

return FreshAgentTurnPageSchema.parse({
sessionType: 'freshclaude',
provider: 'claude',
threadId: input.threadId,
revision: input.page.revision,
nextCursor: input.page.nextCursor,
turns: input.page.items.map((item) => ({
turns: items.map((item) => ({
id: item.turnId,
turnId: item.turnId,
messageId: item.messageId,
Expand All @@ -233,11 +285,7 @@ export function normalizeClaudeTurnPage(input: {
summary: item.summary,
items: [],
})),
...(input.page.bodies ? {
bodies: Object.fromEntries(
Object.entries(input.page.bodies).map(([turnId, turn]) => [turnId, normalizeClaudeTurn(turn)]),
),
} : {}),
...(bodies ? { bodies } : {}),
}) as FreshAgentClaudeTurnPage
}

Expand All @@ -246,8 +294,10 @@ export function normalizeClaudeTurnBody(input: {
revision: number
threadId: string
}) {
const turn = normalizeClaudeTurn(input.turn)
if (!turn) return null
return FreshAgentTurnBodySchema.parse({
...normalizeClaudeTurn(input.turn),
...turn,
sessionType: 'freshclaude',
provider: 'claude',
threadId: input.threadId,
Expand Down
36 changes: 35 additions & 1 deletion src/components/fresh-agent/FreshAgentTranscript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,40 @@ function buildBlocks(
return blocks
}

function isSyntheticToolResultTurn(turn: FreshAgentTurn): boolean {
return turn.role === 'user'
&& turn.items.length > 0
&& turn.items.every((item) => item.kind === 'tool_result')
}

function appendTurnItems(previous: FreshAgentTurn, next: FreshAgentTurn): FreshAgentTurn {
return {
...previous,
id: `${previous.id}:${next.id}`,
summary: [previous.summary, next.summary].filter(Boolean).join('\n\n'),
items: [...previous.items, ...next.items],
model: next.model ?? previous.model,
timestamp: next.timestamp ?? previous.timestamp,
}
}

function coalesceSyntheticToolResultTurns(turns: FreshAgentTurn[]): FreshAgentTurn[] {
const coalesced: FreshAgentTurn[] = []
for (const turn of turns) {
const previous = coalesced[coalesced.length - 1]
if (isSyntheticToolResultTurn(turn)) {
if (previous?.role === 'assistant') {
coalesced[coalesced.length - 1] = appendTurnItems(previous, turn)
} else {
coalesced.push({ ...turn, role: 'tool' })
}
continue
}
coalesced.push(turn)
}
return coalesced
}

function filterTurnsForDisplay(
turns: FreshAgentTurn[],
options: TranscriptDisplayOptions,
Expand Down Expand Up @@ -596,7 +630,7 @@ export const FreshAgentTranscript = forwardRef<FreshAgentTranscriptHandle, Fresh
showThinking,
}), [showThinking])
const displayTurns = useMemo(() => (
filterTurnsForDisplay(turns, displayOptions, isStreaming)
filterTurnsForDisplay(coalesceSyntheticToolResultTurns(turns), displayOptions, isStreaming)
), [displayOptions, turns, isStreaming])
const liveActivityBlockId = useMemo(
() => selectLiveActivityBlockId(displayTurns, isStreaming, displayOptions),
Expand Down
123 changes: 123 additions & 0 deletions test/unit/client/components/fresh-agent/FreshAgentTranscript.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,129 @@ describe('FreshAgentTranscript', () => {
expect(screen.getAllByLabelText('complete').length).toBeGreaterThanOrEqual(1)
})

it('folds Claude user-role tool results into the assistant activity instead of attributing them to You', () => {
const { container } = render(
<FreshAgentTranscript
agentLabel="Freshclaude"
turns={[
{
id: 'turn-user-1',
role: 'user',
summary: 'request',
items: [{ id: 'item-user-1', kind: 'text', text: 'Check the plan file' }],
},
{
id: 'turn-agent-tool',
role: 'assistant',
summary: 'reading',
items: [
{ id: 'item-agent-1', kind: 'text', text: 'Let me check that.' },
{
id: 'tool-read-1',
kind: 'tool_use',
toolUseId: 'call-read-1',
name: 'Read',
input: { file_path: 'docs/plan.md' },
},
],
},
{
id: 'turn-tool-result',
role: 'user',
summary: 'Tool result',
items: [
{ id: 'result-read-1', kind: 'tool_result', toolUseId: 'call-read-1', content: '# Plan', isError: false },
],
},
{
id: 'turn-agent-final',
role: 'assistant',
summary: 'done',
items: [{ id: 'item-agent-2', kind: 'text', text: 'Plan file checked.' }],
},
]}
/>,
)

const visibleHeaders = Array.from(container.querySelectorAll('.fresh-agent-turn-header'))
.map((node) => node.textContent?.trim())
.filter(Boolean)
expect(visibleHeaders).toEqual(['You', 'Freshclaude'])
expect(container.querySelectorAll('[data-turn-role="user"] .fresh-agent-activity-strip')).toHaveLength(0)
expect(screen.getByRole('region', { name: 'Activity strip' })).toHaveTextContent('1 tool used')

fireEvent.click(screen.getByRole('button', { name: 'Toggle activity details' }))
expect(screen.getByText('docs/plan.md')).toBeInTheDocument()
expect(container.querySelector('[data-tool-output]')).toHaveTextContent('# Plan')
})

it('coalesces adjacent Claude tool-use/result exchanges without rendering synthetic You turns', () => {
const { container } = render(
<FreshAgentTranscript
agentLabel="Freshclaude"
turns={[
{
id: 'turn-user-1',
role: 'user',
summary: 'request',
items: [{ id: 'item-user-1', kind: 'text', text: 'Read both files' }],
},
{
id: 'turn-agent-read-1',
role: 'assistant',
summary: 'Read',
items: [{
id: 'tool-read-1',
kind: 'tool_use',
toolUseId: 'call-read-1',
name: 'Read',
input: { file_path: 'src/one.ts' },
}],
},
{
id: 'turn-tool-result-1',
role: 'user',
summary: 'Tool result',
items: [{ id: 'result-read-1', kind: 'tool_result', toolUseId: 'call-read-1', content: 'one', isError: false }],
},
{
id: 'turn-agent-read-2',
role: 'assistant',
summary: 'Read',
items: [{
id: 'tool-read-2',
kind: 'tool_use',
toolUseId: 'call-read-2',
name: 'Read',
input: { file_path: 'src/two.ts' },
}],
},
{
id: 'turn-tool-result-2',
role: 'user',
summary: 'Tool result',
items: [{ id: 'result-read-2', kind: 'tool_result', toolUseId: 'call-read-2', content: 'two', isError: false }],
},
{
id: 'turn-agent-final',
role: 'assistant',
summary: 'done',
items: [{ id: 'item-agent-final', kind: 'text', text: 'Both files are checked.' }],
},
]}
/>,
)

const visibleHeaders = Array.from(container.querySelectorAll('.fresh-agent-turn-header'))
.map((node) => node.textContent?.trim())
.filter(Boolean)
expect(visibleHeaders).toEqual(['You', 'Freshclaude'])
expect(container.querySelectorAll('[data-turn-role="user"] .fresh-agent-activity-strip')).toHaveLength(0)
const strips = screen.getAllByRole('region', { name: 'Activity strip' })
expect(strips).toHaveLength(2)
expect(strips.every((strip) => strip.textContent?.includes('1 tool used'))).toBe(true)
})

it('shows the speaker label once for consecutive turns from the same role', () => {
const { container } = render(
<FreshAgentTranscript
Expand Down
20 changes: 20 additions & 0 deletions test/unit/server/coding-cli/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ describe('isSystemContext()', () => {
expect(isSystemContext('# agents.md instructions')).toBe(true)
expect(isSystemContext('# INSTRUCTIONS')).toBe(true)
})

it('detects Claude Code skill instruction payloads', () => {
expect(isSystemContext([
'Base directory for this skill: /home/dan/.claude/skills/fresheyes',
'',
'# Fresh Eyes - Independent Code Review',
'',
'Invoke an independent model to perform a code review.',
].join('\n'))).toBe(true)
})
})

describe('bracketed agent modes', () => {
Expand Down Expand Up @@ -219,4 +229,14 @@ describe('extractUserAuthoredText()', () => {
it('does not treat plain AGENTS instruction text as a user request', () => {
expect(extractUserAuthoredText('# AGENTS.md instructions\n\nFollow these rules...')).toBeUndefined()
})

it('does not treat Claude Code skill instruction payloads as user requests', () => {
expect(extractUserAuthoredText([
'Base directory for this skill: /home/dan/.claude/skills/fresheyes',
'',
'# Fresh Eyes - Independent Code Review',
'',
'Invoke an independent model to perform a code review.',
].join('\n'))).toBeUndefined()
})
})
Loading
Loading