mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-20 03:47:06 +00:00
fix(codex,web): preserve late command result identity and timing (#2239)
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { normalizeDecryptedMessage } from './normalize'
|
||||
import { reduceChatBlocks } from './reducer'
|
||||
import { toolDurationMs } from '@/components/ToolCard/toolDuration'
|
||||
import { getToolTimingDetails } from '@/components/ToolCard/ToolCard'
|
||||
import { getToolGroupTiming } from '@/components/ToolCard/ToolGroupCard'
|
||||
import { reconcileChatBlocks } from './reconcile'
|
||||
import type { ToolCallBlock } from './types'
|
||||
import type { DecryptedMessage } from '@/types/api'
|
||||
|
||||
function message(data: unknown, createdAt = 20_000): DecryptedMessage {
|
||||
return { id: `m-${createdAt}`, seq: createdAt, localId: null, createdAt,
|
||||
content: { role: 'agent', content: { type: 'codex', data } } }
|
||||
}
|
||||
|
||||
function reduce(messages: DecryptedMessage[]) {
|
||||
const normalized = messages.map(normalizeDecryptedMessage).filter(value => value !== null)
|
||||
const block = reduceChatBlocks(normalized, null).blocks.find(block => block.kind === 'tool-call')
|
||||
if (!block || block.kind !== 'tool-call') throw new Error('missing command card')
|
||||
return block.tool
|
||||
}
|
||||
|
||||
const command = 'bun run vite --host 127.0.0.1 --port 3422'
|
||||
const result = (output: Record<string, unknown>, extra = {}) => message({
|
||||
type: 'tool-call-result', callId: 'command', output: { type: 'exec_command_end', command, ...output }, ...extra
|
||||
})
|
||||
|
||||
describe('late Codex command results', () => {
|
||||
it.each([{ status: 'failed' }, { exit_code: -1 }, { status: 'cancelled' }, { status: 'declined' }, { error: 'terminated' }])(
|
||||
'preserves native failure without a top-level flag: %j', output => {
|
||||
expect(reduce([result(output)]).state).toBe('error')
|
||||
})
|
||||
|
||||
it('recovers identity and native duration without inventing a start timestamp', () => {
|
||||
const tool = reduce([result({ exit_code: -1, duration_ms: 16_636_720, cwd: '/repo/web' })])
|
||||
expect(tool).toMatchObject({ name: 'CodexBash', input: { command, cwd: '/repo/web' }, startedAt: null })
|
||||
expect(toolDurationMs(tool)).toBe(16_636_720)
|
||||
expect(getToolTimingDetails(tool, 25_000)).toEqual({ startedAt: null, completedAt: 20_000, durationMs: 16_636_720 })
|
||||
})
|
||||
|
||||
it.each([undefined, -1, NaN, Infinity, '100'])('does not manufacture duration from an invalid native value: %s', duration_ms => {
|
||||
const tool = reduce([result({ status: 'completed', exit_code: 0, duration_ms })])
|
||||
expect(tool.state).toBe('completed')
|
||||
expect(toolDurationMs(tool)).toBeNull()
|
||||
expect(getToolTimingDetails(tool, 25_000).startedAt).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves a genuine zero native duration and explicit error flag', () => {
|
||||
const tool = reduce([result({ exit_code: 0, duration_ms: 0 }, { is_error: true })])
|
||||
expect(tool.state).toBe('error')
|
||||
expect(toolDurationMs(tool)).toBe(0)
|
||||
})
|
||||
|
||||
it.each([false, true])('pairs a start loaded later and preserves native duration (result first: %s)', reverse => {
|
||||
const start = message({ type: 'tool-call', name: 'CodexBash', callId: 'command', input: { command, cwd: '/original' } }, 10_000)
|
||||
const end = result({ exit_code: 0, duration_ms: 8_000 })
|
||||
const tool = reduce(reverse ? [end, start] : [start, end])
|
||||
expect(tool).toMatchObject({ name: 'CodexBash', startedAt: 10_000, completedAt: 20_000, state: 'completed' })
|
||||
expect(tool.input).toMatchObject({ cwd: '/original' })
|
||||
expect(toolDurationMs(tool)).toBe(8_000)
|
||||
})
|
||||
|
||||
it('does not interpret unrelated tool output as a Codex command result', () => {
|
||||
const tool = reduce([message({ type: 'tool-call-result', callId: 'other', output: { status: 'failed', exit_code: -1, command, duration_ms: 100 } })])
|
||||
expect(tool.name).toBe('Tool')
|
||||
expect(tool.state).toBe('completed')
|
||||
})
|
||||
|
||||
it('does not manufacture an aggregate start or duration for a group with an unknown start', () => {
|
||||
const tool = reduce([result({ exit_code: -1, duration_ms: 10_000 })])
|
||||
const block: ToolCallBlock = { kind: 'tool-call', id: 'command', localId: null, createdAt: 20_000, tool, children: [] }
|
||||
expect(getToolGroupTiming([block], 25_000)).toEqual({ startedAt: null, completedAt: 20_000, durationMs: null, running: false })
|
||||
})
|
||||
|
||||
it('reconciles native timing updates without retaining a stale card', () => {
|
||||
const tool = reduce([result({ exit_code: 0, duration_ms: 100 })])
|
||||
const before: ToolCallBlock = { kind: 'tool-call', id: 'command', localId: null, createdAt: 20_000, tool, children: [] }
|
||||
const after = { ...before, tool: { ...tool, executionDurationMs: 200 } }
|
||||
const reconciled = reconcileChatBlocks([after], new Map([[before.id, before]]))
|
||||
expect(reconciled.blocks[0]).toBe(after)
|
||||
})
|
||||
})
|
||||
@@ -1265,6 +1265,18 @@ export function normalizeAgentRecord(
|
||||
|
||||
if (data.type === 'tool-call-result' && typeof data.callId === 'string') {
|
||||
const uuid = asString(data.id) ?? messageId
|
||||
const command = isObject(data.output) && data.output.type === 'exec_command_end' ? data.output : null
|
||||
const commandFailed = command !== null && (
|
||||
['failed', 'cancelled', 'canceled', 'declined', 'interrupted'].includes(String(command.status))
|
||||
|| (typeof command.exit_code === 'number' && command.exit_code !== 0)
|
||||
|| Boolean(command.error)
|
||||
)
|
||||
const duration = command?.duration_ms
|
||||
const commandExecution = command ? {
|
||||
input: Object.fromEntries(['command', 'cwd', 'command_actions', 'command_source']
|
||||
.filter(key => command[key] !== undefined).map(key => [key, command[key]])),
|
||||
...(typeof duration === 'number' && Number.isFinite(duration) && duration >= 0 ? { durationMs: duration } : {})
|
||||
} : undefined
|
||||
return {
|
||||
id: messageId,
|
||||
localId,
|
||||
@@ -1275,7 +1287,8 @@ export function normalizeAgentRecord(
|
||||
type: 'tool-result',
|
||||
tool_use_id: data.callId,
|
||||
content: data.output,
|
||||
is_error: Boolean(data.is_error),
|
||||
is_error: Boolean(data.is_error) || commandFailed,
|
||||
...(commandExecution ? { commandExecution } : {}),
|
||||
uuid,
|
||||
parentUUID: null
|
||||
}],
|
||||
|
||||
@@ -217,6 +217,8 @@ function areToolCallsEqual(left: ToolCallBlock, right: ToolCallBlock, childrenSa
|
||||
&& left.tool.description === right.tool.description
|
||||
&& left.tool.createdAt === right.tool.createdAt
|
||||
&& left.tool.startedAt === right.tool.startedAt
|
||||
&& left.tool.startUnavailable === right.tool.startUnavailable
|
||||
&& left.tool.executionDurationMs === right.tool.executionDurationMs
|
||||
&& left.tool.completedAt === right.tool.completedAt
|
||||
&& left.tool.execStartedAt === right.tool.execStartedAt
|
||||
&& left.tool.execCompletedAt === right.tool.execCompletedAt
|
||||
|
||||
@@ -1045,6 +1045,7 @@ export function reduceTimeline(
|
||||
// null exec timestamp is a no-op, leaving exec start unset so
|
||||
// toolDurationMs falls back to hub times on both sides.
|
||||
setEarliestStartedAt(block, msg.createdAt)
|
||||
if (block.tool.startUnavailable) block.tool = { ...block.tool, startUnavailable: false }
|
||||
setEarliestExecStartedAt(block, msg.agentTimestamp ?? null)
|
||||
|
||||
if (isSubagentToolName(c.name) && !context.consumedGroupIds.has(msg.id)) {
|
||||
@@ -1099,6 +1100,7 @@ export function reduceTimeline(
|
||||
return permissionFromResult ?? permissionEntry?.permission
|
||||
})()
|
||||
|
||||
const existing = toolBlocksById.get(c.tool_use_id)
|
||||
const block = ensureToolBlock(blocks, toolBlocksById, c.tool_use_id, {
|
||||
createdAt: msg.createdAt,
|
||||
invokedAt: msg.invokedAt,
|
||||
@@ -1106,8 +1108,8 @@ export function reduceTimeline(
|
||||
model: msg.model,
|
||||
localId: msg.localId,
|
||||
meta: msg.meta,
|
||||
name: permissionEntry?.toolName ?? 'Tool',
|
||||
input: permissionEntry?.input ?? null,
|
||||
name: permissionEntry?.toolName ?? (c.commandExecution ? 'CodexBash' : 'Tool'),
|
||||
input: existing?.tool.input ?? permissionEntry?.input ?? c.commandExecution?.input ?? null,
|
||||
description: null,
|
||||
permission
|
||||
// NOTE: no agentTimestamp seed here. execStartedAt must
|
||||
@@ -1121,6 +1123,10 @@ export function reduceTimeline(
|
||||
|
||||
block.tool = {
|
||||
...block.tool,
|
||||
...(c.commandExecution ? {
|
||||
executionDurationMs: c.commandExecution.durationMs ?? block.tool.executionDurationMs,
|
||||
...(!existing ? { startedAt: null, startUnavailable: true } : {})
|
||||
} : {}),
|
||||
result: c.content,
|
||||
completedAt: msg.createdAt,
|
||||
// Only a real Claude timestamp — never the hub receive
|
||||
|
||||
@@ -80,6 +80,7 @@ export type ToolResult = {
|
||||
tool_use_id: string
|
||||
content: unknown
|
||||
is_error: boolean
|
||||
commandExecution?: { input: Record<string, unknown>; durationMs?: number }
|
||||
uuid: string
|
||||
parentUUID: string | null
|
||||
permissions?: ToolResultPermission
|
||||
@@ -198,6 +199,10 @@ export type ChatToolCall = {
|
||||
createdAt: number
|
||||
startedAt: number | null
|
||||
completedAt: number | null
|
||||
/** Native command duration, independent of message delivery timing. */
|
||||
executionDurationMs?: number
|
||||
/** A result-only command has no observed invocation timestamp. */
|
||||
startUnavailable?: boolean
|
||||
/**
|
||||
* Execution-machine timestamps (from `NormalizedMessage.agentTimestamp`)
|
||||
* for the tool_use/tool_result entries, when available. Kept separate
|
||||
|
||||
@@ -77,7 +77,7 @@ export function getToolTimingDetails(tool: ChatToolCall, now: number): {
|
||||
|
||||
const active = tool.state === 'running'
|
||||
const hasExecPair = tool.execStartedAt != null && tool.execCompletedAt != null
|
||||
const startedAt = active || !hasExecPair
|
||||
const startedAt = tool.startUnavailable ? null : active || !hasExecPair
|
||||
? (tool.startedAt ?? tool.createdAt)
|
||||
: tool.execStartedAt
|
||||
const completedAt = active
|
||||
|
||||
@@ -25,7 +25,8 @@ export function getToolGroupTiming(tools: ToolCallBlock[], now: number): {
|
||||
.filter((tool) => tool.tool.state !== 'pending')
|
||||
.map((tool) => tool.tool.startedAt ?? tool.tool.createdAt)
|
||||
.filter((value): value is number => Number.isFinite(value))
|
||||
const startedAt = startedValues.length > 0 ? Math.min(...startedValues) : null
|
||||
const startedAt = !tools.some(tool => tool.tool.startUnavailable) && startedValues.length > 0
|
||||
? Math.min(...startedValues) : null
|
||||
const running = tools.some((tool) => tool.tool.state === 'running')
|
||||
const allFinished = tools.length > 0 && tools.every((tool) => tool.tool.state === 'completed' || tool.tool.state === 'error')
|
||||
const completedValues = allFinished
|
||||
|
||||
@@ -2,7 +2,9 @@ import type { ChatToolCall } from '@/chat/types'
|
||||
|
||||
/**
|
||||
* Wall-clock duration of a tool call in milliseconds, or null when it cannot be
|
||||
* derived. Uses the Claude entry's own execution-machine timestamps
|
||||
* derived. A validated native command duration takes precedence over delivery
|
||||
* timing. Result-only commands without one have unknown duration. Otherwise uses
|
||||
* the Claude entry's own execution-machine timestamps
|
||||
* (`execStartedAt`/`execCompletedAt`) — which reflect the true tool execution
|
||||
* time without the hub receive/queue overhead — but only when *both* are
|
||||
* present. This both-or-neither rule is deliberate: mixing one real Claude
|
||||
@@ -19,6 +21,8 @@ export function toolDurationMs(tool: ChatToolCall): number | null {
|
||||
const useExec = tool.execStartedAt != null && tool.execCompletedAt != null
|
||||
const end = useExec ? tool.execCompletedAt : tool.completedAt
|
||||
if (end == null) return null
|
||||
if (tool.executionDurationMs != null) return tool.executionDurationMs
|
||||
if (tool.startUnavailable) return null
|
||||
const start = useExec ? tool.execStartedAt : (tool.startedAt ?? tool.createdAt)
|
||||
if (start == null) return null
|
||||
const duration = end - start
|
||||
|
||||
Reference in New Issue
Block a user