Skip to content

The agent that grows with you

feat(desktop): show detailed transcript timestamps

Nick Moralesa896322b467b
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
index 139377f11ed..50ce3d7ac31 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts
@@ -219,17 +219,18 @@ interface GatewayEventDeps {
compactedTurnRef: MutableRefObject<Set<string>>
lastCwdInfoSessionRef: MutableRefObject<string | null>
nativeSubagentSessionsRef: MutableRefObject<Set<string>>
- appendAssistantDelta: (sessionId: string, delta: string) => void
- appendReasoningDelta: (sessionId: string, delta: string, replace?: boolean) => void
+ appendAssistantDelta: (sessionId: string, delta: string, occurredAt?: number) => void
+ appendReasoningDelta: (sessionId: string, delta: string, replace?: boolean, occurredAt?: number) => void
completeAssistantMessage: (
sessionId: string,
text: string,
responsePreviewed?: boolean,
- failure?: { error: string; partial: boolean }
+ failure?: { error: string; partial: boolean },
+ occurredAt?: number
) => void
- failAssistantMessage: (sessionId: string, errorMessage: string) => void
+ failAssistantMessage: (sessionId: string, errorMessage: string, occurredAt?: number) => void
flushQueuedDeltas: (sessionId?: string) => void
- finalizeInterimAssistantMessage: (sessionId: string, text: string) => void
+ finalizeInterimAssistantMessage: (sessionId: string, text: string, occurredAt?: number) => void
queryClient: QueryClient
refreshHermesConfig: () => Promise<void>
sessionInterrupted: (sessionId: string) => boolean
@@ -243,7 +244,8 @@ interface GatewayEventDeps {
sessionId: string,
payload: GatewayEventPayload | undefined,
phase: 'running' | 'complete',
- sourceEventType?: string
+ sourceEventType?: string,
+ occurredAt?: number
) => void
}
@@ -309,6 +311,12 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
return useCallback(
(event: RpcEvent) => {
const payload = event.payload as GatewayEventPayload | undefined
+
+ const occurredAt =
+ typeof payload?.timestamp === 'number' && Number.isFinite(payload.timestamp)
+ ? payload.timestamp
+ : Date.now() / 1000
+
const explicitSid = event.session_id || ''
const route = resolveGatewayEventSessionId({
@@ -601,7 +609,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
// finalizeInterruptedMessages un-pends kept text and drops
// empty placeholders; on the normal path message.complete
// already settled everything and this is a no-op.
- messages: finalizeInterruptedMessages(state.messages, state.streamId),
+ messages: finalizeInterruptedMessages(state.messages, state.streamId, occurredAt),
pendingBranchGroup: null,
streamId: null,
turnStartedAt: null
@@ -694,7 +702,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
}
} else if (event.type === 'message.delta') {
if (sessionId) {
- appendAssistantDelta(sessionId, coerceGatewayText(payload?.text))
+ appendAssistantDelta(sessionId, coerceGatewayText(payload?.text), occurredAt)
}
} else if (event.type === 'message.interim') {
// The agent emitted interim assistant commentary (text alongside tool
@@ -706,7 +714,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
const text = coerceGatewayText(payload?.text)
if (text) {
- finalizeInterimAssistantMessage(sessionId, text)
+ finalizeInterimAssistantMessage(sessionId, text, occurredAt)
}
}
} else if (event.type === 'thinking.delta') {
@@ -722,7 +730,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
}
} else if (event.type === 'reasoning.delta') {
if (sessionId) {
- appendReasoningDelta(sessionId, coerceThinkingText(payload?.text))
+ appendReasoningDelta(sessionId, coerceThinkingText(payload?.text), false, occurredAt)
}
if (isActiveEvent) {
@@ -730,7 +738,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
}
} else if (event.type === 'reasoning.available') {
if (sessionId) {
- appendReasoningDelta(sessionId, coerceThinkingText(payload?.text), true)
+ appendReasoningDelta(sessionId, coerceThinkingText(payload?.text), true, occurredAt)
}
if (isActiveEvent) {
@@ -752,7 +760,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
if (idx === undefined || idx <= 1) {
// First reference: clear any stale reasoning left over from
// before this turn's references start, same as before.
- appendReasoningDelta(sessionId, text, true)
+ appendReasoningDelta(sessionId, text, true, occurredAt)
} else {
// Later references must accumulate, not replace — otherwise
// each new reference wipes out the ones already shown (#64658).
@@ -764,7 +772,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
// already-complete text, with no concurrent token stream for the
// reference-gathering phase, so there is no in-flight delta to
// collide with in the shared queue bucket.
- appendReasoningDelta(sessionId, text, false)
+ appendReasoningDelta(sessionId, text, false, occurredAt)
flushQueuedDeltas(sessionId)
}
}
@@ -791,7 +799,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
? `◇ MoA refs ${payload.refs_done}/${payload.refs_total} — ${label}\n`
: `◇ MoA refs ${payload.refs_done}/${payload.refs_total}\n`
- appendReasoningDelta(sessionId, line, payload.refs_done <= 1)
+ appendReasoningDelta(sessionId, line, payload.refs_done <= 1, occurredAt)
flushQueuedDeltas(sessionId)
}
@@ -803,7 +811,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
// aggregator acting). Append a one-line marker; the first
// moa.reference that follows replaces the whole block.
if (sessionId && payload?.phase === 'aggregator') {
- appendReasoningDelta(sessionId, '◇ MoA aggregating…\n', false)
+ appendReasoningDelta(sessionId, '◇ MoA aggregating…\n', false, occurredAt)
flushQueuedDeltas(sessionId)
}
@@ -845,7 +853,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
}
: undefined
- completeAssistantMessage(sessionId, finalText, payload?.response_previewed, failure)
+ completeAssistantMessage(sessionId, finalText, payload?.response_previewed, failure, occurredAt)
// Structured billing wall forwarded by the gateway (out of credits /
// payment required) — cache it + raise a billing-specific toast.
@@ -917,7 +925,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
}
flushQueuedDeltas(sessionId)
- upsertToolCall(sessionId, toTodoPayload(payload) ?? payload, 'running', event.type)
+ upsertToolCall(sessionId, toTodoPayload(payload) ?? payload, 'running', event.type, occurredAt)
if (isActiveEvent) {
setPetActivity({ reasoning: false, toolRunning: true })
@@ -925,7 +933,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
} else if (event.type === 'tool.complete') {
if (sessionId) {
flushQueuedDeltas(sessionId)
- upsertToolCall(sessionId, toTodoPayload(payload) ?? payload, 'complete', event.type)
+ upsertToolCall(sessionId, toTodoPayload(payload) ?? payload, 'complete', event.type, occurredAt)
if (isActiveEvent) {
setPetActivity({ toolRunning: false })
@@ -1041,7 +1049,9 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
name: 'clarify',
tool_id: requestId
},
- 'running'
+ 'running',
+ event.type,
+ occurredAt
)
// The transcript only renders the active session, so a background
@@ -1331,8 +1341,8 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
{
id: `review-summary-${Date.now()}`,
role: 'system',
- parts: [textPart(`review:${text}`)],
- timestamp: Math.floor(Date.now() / 1000)
+ parts: [textPart(`review:${text}`, occurredAt)],
+ timestamp: occurredAt
}
]
}))
@@ -1414,7 +1424,7 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) {
if (sessionId) {
flushQueuedDeltas(sessionId)
- failAssistantMessage(sessionId, errorMessage)
+ failAssistantMessage(sessionId, errorMessage, occurredAt)
}
if (isActiveEvent) {
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
index 745c95db59d..ccf60aa9169 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
@@ -9,6 +9,7 @@ import {
type ChatMessage,
type ChatMessagePart,
chatMessageText,
+ completeOpenTimelineParts,
type GatewayEventPayload,
mergeFinalAssistantText,
reasoningPart,
@@ -52,9 +53,10 @@ interface MessageStreamOptions {
) => ClientSessionState
}
-interface QueuedStreamDeltas {
- assistant: string
- reasoning: string
+interface QueuedStreamDelta {
+ occurredAt: number
+ text: string
+ type: 'assistant' | 'reasoning'
}
// Date.now() alone can collide when an interim seal and the next segment's
@@ -88,7 +90,8 @@ export function useMessageStream({
seed: () => ChatMessagePart[],
opts: {
pending?: (message: ChatMessage) => boolean
- } = {}
+ } = {},
+ occurredAt = Date.now() / 1000
) => {
const apply = () => {
updateSessionState(sessionId, state => {
@@ -112,6 +115,7 @@ export function useMessageStream({
id: streamId,
role: 'assistant',
parts: seed(),
+ timestamp: occurredAt,
pending: true,
branchGroupId: groupId
}
@@ -183,7 +187,7 @@ export function useMessageStream({
[]
)
- const queuedDeltasRef = useRef<Map<string, QueuedStreamDeltas>>(new Map())
+ const queuedDeltasRef = useRef<Map<string, QueuedStreamDelta[]>>(new Map())
const flushHandleRef = useRef<number | null>(null)
const lastFlushAtRef = useRef<number>(0)
// What the previous flush cost on the main thread — drives the adaptive
@@ -213,21 +217,16 @@ export function useMessageStream({
queue.delete(id)
- if (queued.assistant) {
- mutateStream(
- id,
- parts => dedupeGeneratedImageEchoesInParts(appendAssistantTextPart(parts, queued.assistant)),
- () => [assistantTextPart(queued.assistant)]
+ const applyQueued = (parts: ChatMessagePart[]) =>
+ queued.reduce(
+ (next, delta) =>
+ delta.type === 'assistant'
+ ? dedupeGeneratedImageEchoesInParts(appendAssistantTextPart(next, delta.text, delta.occurredAt))
+ : appendReasoningPart(next, delta.text, delta.occurredAt),
+ parts
)
- }
- if (queued.reasoning) {
- mutateStream(
- id,
- parts => appendReasoningPart(parts, queued.reasoning),
- () => [reasoningPart(queued.reasoning)]
- )
- }
+ mutateStream(id, applyQueued, () => applyQueued([]), {}, queued[0]?.occurredAt)
}
},
[mutateStream]
@@ -330,13 +329,20 @@ export function useMessageStream({
}, [flushQueuedDeltas])
const queueDelta = useCallback(
- (sessionId: string, key: keyof QueuedStreamDeltas, delta: string) => {
+ (sessionId: string, key: 'assistant' | 'reasoning', delta: string, occurredAt = Date.now() / 1000) => {
if (!delta) {
return
}
- const queued = queuedDeltasRef.current.get(sessionId) ?? { assistant: '', reasoning: '' }
- queued[key] += delta
+ const queued = queuedDeltasRef.current.get(sessionId) ?? []
+ const tail = queued.at(-1)
+
+ if (tail?.type === key) {
+ tail.text += delta
+ } else {
+ queued.push({ occurredAt, text: delta, type: key })
+ }
+
queuedDeltasRef.current.set(sessionId, queued)
scheduleDeltaFlush()
},
@@ -391,24 +397,24 @@ export function useMessageStream({
}, [flushQueuedDeltas])
const appendAssistantDelta = useCallback(
- (sessionId: string, delta: string) => {
+ (sessionId: string, delta: string, occurredAt?: number) => {
if (!delta) {
return
}
- queueDelta(sessionId, 'assistant', delta)
+ queueDelta(sessionId, 'assistant', delta, occurredAt)
},
[queueDelta]
)
const appendReasoningDelta = useCallback(
- (sessionId: string, delta: string, replace = false) => {
+ (sessionId: string, delta: string, replace = false, occurredAt = Date.now() / 1000) => {
if (!delta) {
return
}
if (!replace) {
- queueDelta(sessionId, 'reasoning', delta)
+ queueDelta(sessionId, 'reasoning', delta, occurredAt)
return
}
@@ -423,12 +429,14 @@ export function useMessageStream({
}
if (replace) {
- return [...parts.filter(part => part.type !== 'reasoning'), reasoningPart(delta)]
+ return [...parts.filter(part => part.type !== 'reasoning'), reasoningPart(delta, occurredAt)]
}
- return appendReasoningPart(parts, delta)
+ return appendReasoningPart(parts, delta, occurredAt)
},
- () => [reasoningPart(delta)]
+ () => [reasoningPart(delta, occurredAt)],
+ {},
+ occurredAt
)
},
[flushQueuedDeltas, mutateStream, queueDelta]
@@ -439,7 +447,8 @@ export function useMessageStream({
sessionId: string,
payload: GatewayEventPayload | undefined,
phase: 'running' | 'complete',
- sourceEventType?: string
+ sourceEventType?: string,
+ occurredAt = Date.now() / 1000
) => {
// Text deltas flush on a timer but tool events apply now; flush first so
// a tool part can't jump ahead of the text that preceded it.
@@ -472,16 +481,17 @@ export function useMessageStream({
mutateStream(
sessionId,
- parts => dedupeGeneratedImageEchoesInParts(upsertToolPart(parts, payload, phase)),
- () => upsertToolPart([], payload, phase),
- { pending: m => phase !== 'complete' || (m.pending ?? false) }
+ parts => dedupeGeneratedImageEchoesInParts(upsertToolPart(parts, payload, phase, occurredAt)),
+ () => upsertToolPart([], payload, phase, occurredAt),
+ { pending: m => phase !== 'complete' || (m.pending ?? false) },
+ occurredAt
)
},
[flushQueuedDeltas, mutateStream, sessionInterrupted]
)
const finalizeInterimAssistantMessage = useCallback(
- (sessionId: string, text: string) => {
+ (sessionId: string, text: string, occurredAt = Date.now() / 1000) => {
updateSessionState(sessionId, state => {
if (state.interrupted) {
return state
@@ -498,7 +508,7 @@ export function useMessageStream({
const replaceTextPart = (parts: ChatMessagePart[]) => {
const visibleText = stripGeneratedImageEchoes(authoritativeText, generatedImageEchoSources(parts)).trim()
- return mergeFinalAssistantText(parts, visibleText)
+ return mergeFinalAssistantText(parts, visibleText, occurredAt)
}
let nextMessages = state.messages
@@ -507,7 +517,15 @@ export function useMessageStream({
// Seal the streaming bubble in place, marked interim so it renders
// without an action footer (see ChatMessage.interim).
nextMessages = nextMessages.map(m =>
- m.id === streamId ? { ...m, parts: replaceTextPart(m.parts), pending: false, interim: true } : m
+ m.id === streamId
+ ? {
+ ...m,
+ parts: completeOpenTimelineParts(replaceTextPart(m.parts), occurredAt),
+ completedAt: occurredAt,
+ pending: false,
+ interim: true
+ }
+ : m
)
} else {
// No streaming bubble — create a standalone interim message
@@ -516,7 +534,9 @@ export function useMessageStream({
{
id: nextStreamMessageId('assistant-interim'),
role: 'assistant' as const,
- parts: [assistantTextPart(authoritativeText)],
+ parts: [{ ...assistantTextPart(authoritativeText, occurredAt), completedAt: occurredAt }],
+ timestamp: occurredAt,
+ completedAt: occurredAt,
pending: false,
interim: true,
branchGroupId: state.pendingBranchGroup ?? undefined
@@ -537,7 +557,13 @@ export function useMessageStream({
)
const completeAssistantMessage = useCallback(
- (sessionId: string, text: string, responsePreviewed?: boolean, failure?: { error: string; partial: boolean }) => {
+ (
+ sessionId: string,
+ text: string,
+ responsePreviewed?: boolean,
+ failure?: { error: string; partial: boolean },
+ occurredAt = Date.now() / 1000
+ ) => {
let shouldHydrate = false
const completedState = updateSessionState(sessionId, state => {
@@ -571,21 +597,27 @@ export function useMessageStream({
const replaceTextPart = (parts: ChatMessagePart[]) => {
const visibleFinalText = stripGeneratedImageEchoes(finalText, generatedImageEchoSources(parts)).trim()
- return mergeFinalAssistantText(parts, visibleFinalText)
+ return mergeFinalAssistantText(parts, visibleFinalText, occurredAt)
}
// Settling the final response onto a bubble makes it the turn's real
// reply — clear `interim` so it regains the action footer.
const completeMessage = (message: ChatMessage): ChatMessage => {
- const settled = { ...message, pending: false, interim: false }
+ const settled = {
+ ...message,
+ completedAt: occurredAt,
+ parts: completeOpenTimelineParts(message.parts, occurredAt),
+ pending: false,
+ interim: false
+ }
if (completionError && !keepFailedPartialText) {
- return { ...settled, error: completionError, parts: message.parts.filter(part => part.type !== 'text') }
+ return { ...settled, error: completionError, parts: settled.parts.filter(part => part.type !== 'text') }
}
return {
...settled,
- parts: replaceTextPart(message.parts),
+ parts: completeOpenTimelineParts(replaceTextPart(settled.parts), occurredAt),
...(completionError ? { error: completionError } : {})
}
}
@@ -593,7 +625,12 @@ export function useMessageStream({
const newAssistantFromCompletion = (): ChatMessage => ({
id: `assistant-${Date.now()}`,
role: 'assistant',
- parts: completionError && !keepFailedPartialText ? [] : [assistantTextPart(finalText)],
+ parts:
+ completionError && !keepFailedPartialText
+ ? []
+ : [{ ...assistantTextPart(finalText, occurredAt), completedAt: occurredAt }],
+ timestamp: occurredAt,
+ completedAt: occurredAt,
branchGroupId: state.pendingBranchGroup ?? undefined,
...(completionError && { error: completionError })
})
@@ -733,7 +770,7 @@ export function useMessageStream({
)
const failAssistantMessage = useCallback(
- (sessionId: string, errorMessage: string) => {
+ (sessionId: string, errorMessage: string, occurredAt = Date.now() / 1000) => {
updateSessionState(sessionId, state => {
const streamId = state.streamId ?? `assistant-error-${Date.now()}`
const groupId = state.pendingBranchGroup ?? undefined
@@ -745,7 +782,9 @@ export function useMessageStream({
message.id === streamId
? {
...message,
+ completedAt: occurredAt,
error,
+ parts: completeOpenTimelineParts(message.parts, occurredAt),
pending: false
}
: message
@@ -756,6 +795,8 @@ export function useMessageStream({
id: streamId,
role: 'assistant' as const,
parts: [],
+ timestamp: occurredAt,
+ completedAt: occurredAt,
error,
pending: false,
branchGroupId: groupId
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx
index 162340a0c00..52973d7fdeb 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx
@@ -95,7 +95,7 @@ describe('turn end without message.complete (session.info running=false)', () =>
expect(tail?.role).toBe('assistant')
expect(tail?.pending).toBe(false)
- expect(tail?.parts).toEqual([{ type: 'text', text: 'partial answer' }])
+ expect(tail?.parts).toMatchObject([{ type: 'text', text: 'partial answer' }])
expect(state?.streamId).toBeNull()
expect(state?.busy).toBe(false)
})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx
index 840416a18e2..d14f0f4fe93 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx
@@ -86,7 +86,7 @@ describe('stream delta delivery', () => {
await vi.advanceTimersByTimeAsync(STREAM_DELTA_FLUSH_MS)
})
- expect(states.get(SID)?.messages.at(-1)?.parts).toEqual([{ type: 'text', text: 'first and the rest' }])
+ expect(states.get(SID)?.messages.at(-1)?.parts).toMatchObject([{ type: 'text', text: 'first and the rest' }])
// The flush must not have depended on a frame: this mock parks every rAF
// callback, yet the text arrived. runFlush still registers its
// adaptive-floor measurement callback here; that one is allowed to wait
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsx
new file mode 100644
index 00000000000..cfeccbc0c5f
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsx
@@ -0,0 +1,126 @@
+import { QueryClient } from '@tanstack/react-query'
+import { act, cleanup, render, waitFor } from '@testing-library/react'
+import { useEffect, useRef } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { ClientSessionState } from '@/app/types'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import type { RpcEvent } from '@/types/hermes'
+
+import { useMessageStream } from './index'
+
+const SID = 'timeline-session'
+
+let handleEvent: ((event: RpcEvent) => void) | null = null
+let states: Map<string, ClientSessionState>
+
+function Harness() {
+ const activeSessionIdRef = useRef<string | null>(SID)
+ const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())
+ const queryClientRef = useRef(new QueryClient())
+
+ const stream = useMessageStream({
+ activeSessionIdRef,
+ hydrateFromStoredSession: vi.fn(async () => undefined),
+ queryClient: queryClientRef.current,
+ refreshHermesConfig: vi.fn(async () => undefined),
+ refreshSessions: vi.fn(async () => undefined),
+ sessionStateByRuntimeIdRef,
+ updateSessionState: (sessionId, updater) => {
+ const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()
+ const next = updater(current)
+ sessionStateByRuntimeIdRef.current.set(sessionId, next)
+ states.set(sessionId, next)
+
+ return next
+ }
+ })
+
+ useEffect(() => {
+ handleEvent = stream.handleGatewayEvent
+ }, [stream.handleGatewayEvent])
+
+ return null
+}
+
+const event = (type: string, timestamp: number, payload: Record<string, unknown> = {}) =>
+ act(() => handleEvent?.({ payload: { ...payload, timestamp }, session_id: SID, type }))
+
+describe('live transcript timeline events', () => {
+ beforeEach(async () => {
+ handleEvent = null
+ states = new Map()
+ render(<Harness />)
+ await waitFor(() => expect(handleEvent).not.toBeNull())
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('records commentary, tool, resumed text, and turn-stop boundaries', () => {
+ event('message.start', 100)
+ event('message.delta', 101.125, { text: 'Let me inspect it.' })
+ event('message.interim', 101.75, { already_streamed: true, text: 'Let me inspect it.' })
+ event('tool.start', 102.25, { args: { path: 'README.md' }, name: 'read_file', tool_id: 'call-1' })
+ event('tool.complete', 104.5, { name: 'read_file', result: { content: 'ok' }, tool_id: 'call-1' })
+ event('message.delta', 105.625, { text: 'The file looks good.' })
+ event('message.complete', 106.875, { text: 'The file looks good.' })
+
+ const assistants = states.get(SID)?.messages.filter(message => message.role === 'assistant') ?? []
+
+ expect(assistants).toHaveLength(2)
+ expect([assistants[0].timestamp, assistants[0].completedAt]).toEqual([101.125, 101.75])
+ expect(assistants[0].parts.map(part => [part.timestamp, part.completedAt])).toEqual([[101.125, 101.75]])
+
+ expect([assistants[1].timestamp, assistants[1].completedAt]).toEqual([102.25, 106.875])
+ expect(assistants[1].parts.map(part => part.type)).toEqual(['tool-call', 'text'])
+ expect(assistants[1].parts.map(part => [part.timestamp, part.completedAt])).toEqual([
+ [102.25, 104.5],
+ [105.625, 106.875]
+ ])
+ })
+
+ it('preserves cross-channel delta order inside one flush window', () => {
+ event('message.start', 200)
+ event('reasoning.delta', 201.125, { text: 'Thinking first.' })
+ event('message.delta', 202.25, { text: 'Then speaking.' })
+ event('tool.start', 203.5, { args: {}, name: 'terminal', tool_id: 'call-2' })
+
+ const assistant = states.get(SID)?.messages.find(message => message.role === 'assistant')
+
+ expect(assistant?.parts.map(part => part.type)).toEqual(['reasoning', 'text', 'tool-call'])
+ expect(assistant?.parts.map(part => part.timestamp)).toEqual([201.125, 202.25, 203.5])
+ })
+
+ it('uses the gateway event time for an error boundary', () => {
+ event('message.start', 300)
+ event('error', 301.875, { error: 'provider failed' })
+
+ const assistant = states.get(SID)?.messages.find(message => message.role === 'assistant')
+
+ expect(assistant?.error).toBeTruthy()
+ expect([assistant?.timestamp, assistant?.completedAt]).toEqual([301.875, 301.875])
+ })
+
+ it('uses the gateway event time for a review summary system row', () => {
+ event('review.summary', 401.625, { text: 'Review saved.' })
+
+ const system = states.get(SID)?.messages.find(message => message.role === 'system')
+
+ expect(system?.timestamp).toBe(401.625)
+ expect(system?.parts[0].timestamp).toBe(401.625)
+ })
+
+ it('uses session.info time when it is the only stop boundary', () => {
+ event('message.start', 500)
+ event('tool.start', 501, { args: {}, name: 'terminal', tool_id: 'call-3' })
+ event('session.info', 502.75, { running: false })
+
+ const assistant = states.get(SID)?.messages.find(message => message.role === 'assistant')
+
+ expect(assistant?.completedAt).toBe(502.75)
+ expect(assistant?.parts[0].completedAt).toBe(502.75)
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts
index 2b8f99ff293..de69b180847 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts
@@ -2,7 +2,13 @@ import { describe, expect, it } from 'vitest'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
-import { appendMidTurnUserMessage, rebindSurvivorRowIds, survivorRowIdsFrom, truncateSubmitParams } from './rewind'
+import {
+ appendMidTurnUserMessage,
+ finalizeInterruptedMessages,
+ rebindSurvivorRowIds,
+ survivorRowIdsFrom,
+ truncateSubmitParams
+} from './rewind'
const row = (id: string, role: ChatMessage['role'], text: string, extra: Partial<ChatMessage> = {}): ChatMessage => ({
id,
@@ -204,3 +210,54 @@ describe('rebindSurvivorRowIds', () => {
expect(rebindSurvivorRowIds(messages, [7])[0]).toBe(messages[0])
})
})
+
+describe('finalizeInterruptedMessages', () => {
+ it('records when a stopped assistant turn and its active part ended', () => {
+ const [message] = finalizeInterruptedMessages(
+ [
+ {
+ id: 'assistant-live',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'partial answer', timestamp: 10 }],
+ pending: true,
+ timestamp: 10
+ }
+ ],
+ 'assistant-live',
+ 11.25
+ )
+
+ expect(message.completedAt).toBe(11.25)
+ expect(message.parts[0].completedAt).toBe(11.25)
+ expect(message.pending).toBe(false)
+ })
+
+ it('keeps and closes a tool-only assistant turn when it is stopped', () => {
+ const [message] = finalizeInterruptedMessages(
+ [
+ {
+ id: 'assistant-tool',
+ role: 'assistant',
+ parts: [
+ {
+ args: {} as never,
+ argsText: '{}',
+ timestamp: 10,
+ toolCallId: 'call-1',
+ toolName: 'terminal',
+ type: 'tool-call'
+ }
+ ],
+ pending: true,
+ timestamp: 10
+ }
+ ],
+ 'assistant-tool',
+ 11.25
+ )
+
+ expect(message.parts).toHaveLength(1)
+ expect(message.parts[0].completedAt).toBe(11.25)
+ expect(message.completedAt).toBe(11.25)
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
index fcf83c4ba71..890071624ee 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
@@ -13,7 +13,13 @@ import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
import type { ClientSessionState } from '@/app/types'
import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'
-import { branchGroupForUser, type ChatMessage, chatMessageText, textPart } from '@/lib/chat-messages'
+import {
+ branchGroupForUser,
+ type ChatMessage,
+ chatMessageText,
+ completeOpenTimelineParts,
+ textPart
+} from '@/lib/chat-messages'
import {
appendText,
@@ -203,10 +209,30 @@ export async function runRewindSubmit(
}
/** Cancel/stop finalize: drop empty pending/stream placeholders, un-pend the rest. */
-export function finalizeInterruptedMessages(messages: ChatMessage[], streamId?: null | string): ChatMessage[] {
+export function finalizeInterruptedMessages(
+ messages: ChatMessage[],
+ streamId?: null | string,
+ occurredAt = Date.now() / 1000
+): ChatMessage[] {
return messages
- .filter(message => !((message.pending || message.id === streamId) && !chatMessageText(message).trim()))
- .map(message => (message.pending || message.id === streamId ? { ...message, pending: false } : message))
+ .filter(
+ message =>
+ !(
+ (message.pending || message.id === streamId) &&
+ message.parts.length === 0 &&
+ !chatMessageText(message).trim()
+ )
+ )
+ .map(message =>
+ message.pending || message.id === streamId
+ ? {
+ ...message,
+ completedAt: occurredAt,
+ parts: completeOpenTimelineParts(message.parts, occurredAt),
+ pending: false
+ }
+ : message
+ )
}
/**
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index e0f86e64961..bbc11910b84 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@ -319,11 +319,15 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// hands us the invocation to render instead. Everything else shows what
// was typed.
const bubbleText = options?.displayText ?? visibleText
+ // Keep the user-send boundary stable when later ref resolution rewrites
+ // the optimistic bubble in place.
+ const submittedAt = Date.now() / 1000
const buildUserMessage = (): ChatMessage => ({
id: optimisticId,
role: 'user',
parts: [textPart(bubbleText || (attachmentRefs.length ? '' : attachments.map(a => a.label).join(', ')))],
+ timestamp: submittedAt,
attachmentRefs
})
@@ -737,6 +741,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
}
const message = inlineErrorMessage(err, copy.promptFailed)
+ const occurredAt = Date.now() / 1000
updateSessionState(
sessionId,
@@ -749,7 +754,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
role: 'assistant',
parts: [],
error: message || copy.promptFailed,
- branchGroupId: state.pendingBranchGroup ?? undefined
+ branchGroupId: state.pendingBranchGroup ?? undefined,
+ completedAt: occurredAt,
+ timestamp: occurredAt
}
],
busy: false,
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
index b010a6f878f..79b6f41952c 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
@@ -307,6 +307,13 @@ describe('chatPartsEquivalent', () => {
expect(chatPartsEquivalent(partA, partB)).toBe(false)
})
+ it('returns false when visible timeline boundaries change', () => {
+ const started = { type: 'text' as const, text: 'Hello', timestamp: 10 }
+ const completed = { ...started, completedAt: 11 }
+
+ expect(chatPartsEquivalent(started, completed)).toBe(false)
+ })
+
it('returns true for identical reasoning parts', () => {
const partA = { type: 'reasoning' as const, text: 'Thinking...' }
const partB = { type: 'reasoning' as const, text: 'Thinking...' }
@@ -392,6 +399,13 @@ describe('chatMessagesEquivalent', () => {
expect(chatMessagesEquivalent(msg('1', 'user', 'Hello'), msg('1', 'user', 'Hello'))).toBe(true)
})
+ it('returns false when a visible message timestamp changes', () => {
+ const before = { ...msg('1', 'user', 'Hello'), timestamp: 10 }
+ const after = { ...before, timestamp: 11 }
+
+ expect(chatMessagesEquivalent(before, after)).toBe(false)
+ })
+
it('returns false when text part content differs', () => {
expect(chatMessagesEquivalent(msg('1', 'user', 'Hello'), msg('1', 'user', 'World'))).toBe(false)
})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index b6cd683b59b..4d46dc5fa53 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -139,9 +139,20 @@ const _chatMessageFieldsExhaustive: {
[K in Exclude<keyof ChatMessage, (typeof COMPARED_FIELDS)[number] | (typeof IGNORED_FIELDS)[number]>]: never
} = {}
-const COMPARED_FIELDS = ['id', 'role', 'pending', 'error', 'hidden', 'branchGroupId', 'interim', 'reactions'] as const
+const COMPARED_FIELDS = [
+ 'id',
+ 'role',
+ 'pending',
+ 'error',
+ 'hidden',
+ 'branchGroupId',
+ 'interim',
+ 'reactions',
+ 'timestamp',
+ 'completedAt'
+] as const
-const IGNORED_FIELDS = ['timestamp', 'attachmentRefs', 'parts', 'rowId'] as const
+const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'rowId'] as const
// Compile-time check: every ChatMessagePart discriminant must be handled by
// chatPartsEquivalent. If @assistant-ui adds a new part type, this fails tsc.
@@ -179,6 +190,10 @@ export function chatPartsEquivalent(aPart: ChatMessage['parts'][number], bPart:
return false
}
+ if (aPart.timestamp !== bPart.timestamp || aPart.completedAt !== bPart.completedAt) {
+ return false
+ }
+
if (aPart.type === 'text' || aPart.type === 'reasoning') {
return (aPart as { text: string }).text === (bPart as { text: string }).text
}
@@ -202,8 +217,8 @@ export function chatPartsEquivalent(aPart: ChatMessage['parts'][number], bPart:
// audio, data-*), fall back to shallow primitive-key comparison — conservative:
// if we're not sure, claim not-equal (one extra setMessages is harmless, but
// skipping an update would break the UI).
- const aPrimitive = aPart as Record<string, unknown>
- const bPrimitive = bPart as Record<string, unknown>
+ const aPrimitive = aPart as unknown as Record<string, unknown>
+ const bPrimitive = bPart as unknown as Record<string, unknown>
const aKeys = Object.keys(aPrimitive).filter(k => typeof aPrimitive[k] !== 'object' || aPrimitive[k] === null)
const bKeys = Object.keys(bPrimitive).filter(k => typeof bPrimitive[k] !== 'object' || bPrimitive[k] === null)
@@ -236,6 +251,8 @@ export function chatMessagesEquivalent(a: ChatMessage, b: ChatMessage): boolean
a.error !== b.error ||
a.hidden !== b.hidden ||
a.branchGroupId !== b.branchGroupId ||
+ a.timestamp !== b.timestamp ||
+ a.completedAt !== b.completedAt ||
// Interim gates the action footer, so flipping it must repaint (e.g. a
// previewed final settling onto a sealed interim bubble restores the bar).
(a.interim ?? false) !== (b.interim ?? false) ||
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
index 2f39c2a2eb5..b75668f78ec 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
@@ -8,9 +8,12 @@ import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime }
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { formatTimelineRange, formatTimelineTimestamp } from './timestamp'
+
import { Thread } from '.'
const createdAt = new Date('2026-05-01T00:00:00.000Z')
+const completedAt = createdAt.getTime() / 1000 + 1.25
class TestResizeObserver {
observe() {}
@@ -37,15 +40,28 @@ function userMessage(): ThreadMessage {
content: [{ type: 'text', text: 'question one' }],
attachments: [],
createdAt,
- metadata: { custom: {} }
- } as ThreadMessage
+ metadata: { custom: { timelineTimestamp: createdAt.getTime() / 1000 } }
+ } as unknown as ThreadMessage
}
function assistantMessage(): ThreadMessage {
return {
id: 'assistant-1',
role: 'assistant',
- content: [{ type: 'text', text: 'done' }],
+ content: [
+ {
+ type: 'reasoning',
+ text: 'checked carefully',
+ timestamp: createdAt.getTime() / 1000 + 0.05,
+ completedAt: createdAt.getTime() / 1000 + 0.1
+ },
+ {
+ type: 'text',
+ text: 'done',
+ timestamp: createdAt.getTime() / 1000 + 0.125,
+ completedAt: createdAt.getTime() / 1000 + 0.5
+ }
+ ],
status: { type: 'complete', reason: 'stop' },
createdAt,
metadata: {
@@ -53,14 +69,20 @@ function assistantMessage(): ThreadMessage {
unstable_annotations: [],
unstable_data: [],
steps: [],
- custom: {}
+ custom: { timelineCompletedAt: completedAt, timelineTimestamp: createdAt.getTime() / 1000 }
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
-function Harness({ onBranchInNewChat }: { onBranchInNewChat?: (messageId: string) => void }) {
+function Harness({
+ assistant = assistantMessage(),
+ onBranchInNewChat
+}: {
+ assistant?: ThreadMessage
+ onBranchInNewChat?: (messageId: string) => void
+}) {
const runtime = useExternalStoreRuntime<ThreadMessage>({
- messages: [userMessage(), assistantMessage()],
+ messages: [userMessage(), assistant],
isRunning: false,
onNew: async () => {}
})
@@ -90,3 +112,41 @@ describe('AssistantMessage branch button visibility (bug #2 fix)', () => {
expect(screen.queryByRole('button', { name: 'Branch in new chat' })).toBeNull()
})
})
+
+describe('message timeline timestamps', () => {
+ it('always renders precise user and assistant lifecycle times', async () => {
+ const { container } = render(<Harness />)
+
+ await screen.findByText('done')
+
+ const stamps = Array.from(container.querySelectorAll('[data-slot="timeline-timestamp"]')).map(node =>
+ node.textContent?.trim()
+ )
+
+ const startedAt = createdAt.getTime() / 1000
+
+ expect(stamps).toContain(formatTimelineTimestamp(startedAt))
+ expect(stamps).toContain(formatTimelineRange(startedAt, completedAt))
+ expect(stamps).toContain(formatTimelineRange(startedAt + 0.05, startedAt + 0.1))
+ expect(stamps).toContain(formatTimelineRange(startedAt + 0.125, startedAt + 0.5))
+ })
+
+ it('suppresses an aggregate assistant stamp that exactly duplicates its sole part', async () => {
+ const startedAt = createdAt.getTime() / 1000
+
+ const assistant = {
+ ...assistantMessage(),
+ content: [{ completedAt, text: 'done', timestamp: startedAt, type: 'text' }]
+ } as unknown as ThreadMessage
+
+ const { container } = render(<Harness assistant={assistant} />)
+
+ await screen.findByText('done')
+
+ const stamps = Array.from(container.querySelectorAll('[data-slot="timeline-timestamp"]')).map(node =>
+ node.textContent?.trim()
+ )
+
+ expect(stamps.filter(stamp => stamp === formatTimelineRange(startedAt, completedAt))).toHaveLength(1)
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
index d0293b22adf..a4ef0d5fbe7 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -18,7 +18,7 @@ import {
import { MESSAGE_PARTS_COMPONENTS } from '@/components/assistant-ui/thread/message-parts'
import { ReactionPicker } from '@/components/assistant-ui/thread/message-reactions'
import { ResponseLoadingIndicator, StreamStallIndicator } from '@/components/assistant-ui/thread/status'
-import { formatMessageTimestamp } from '@/components/assistant-ui/thread/timestamp'
+import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { useMessageReactions, useTapbackDoubleClick } from '@/components/assistant-ui/thread/use-message-reactions'
import { AGENT_MESSAGE_RE } from '@/components/assistant-ui/thread/user-message'
import { TooltipIconButton } from '@/components/assistant-ui/tooltip-icon-button'
@@ -29,7 +29,6 @@ import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
import { AudioLines, GitForkIcon, Loader2Icon, RefreshCwIcon, SmilePlusIcon, VolumeXIcon, XIcon } from '@/lib/icons'
import { extractPreviewTargets } from '@/lib/preview-targets'
-import { formatAgo } from '@/lib/time'
import { useEnterAnimation } from '@/lib/use-enter-animation'
import { cn } from '@/lib/utils'
import { playSpeechText, stopVoicePlayback } from '@/lib/voice-playback'
@@ -222,6 +221,7 @@ export const AssistantMessage: FC<{
</ErrorPrimitive.Root>
</MessagePrimitive.Error>
</div>
+ <MessageTimelineTimestamp className="px-(--message-text-indent) pt-0.5" suppressIfDuplicatePart />
{hasVisibleText && !isInterim && (
<AssistantFooter getMessageText={getMessageText} messageId={messageId} onBranchInNewChat={onBranchInNewChat} />
)}
@@ -262,7 +262,6 @@ const AssistantActionBar: FC<MessageActionProps> = ({ messageId, getMessageText,
}
data-slot="aui_msg-actions"
>
- <MessageAge />
{onBranchInNewChat && (
<TooltipIconButton
onClick={() => {
@@ -364,26 +363,6 @@ const ReadAloudButton: FC<{ getText: () => string; messageId: string }> = ({ get
)
}
-const MessageAge: FC = () => {
- const { t } = useI18n()
- const createdAt = useAuiState(s => s.message.createdAt)
- const date = createdAt ? new Date(createdAt) : null
-
- if (!date || Number.isNaN(date.getTime())) {
- return null
- }
-
- // Compact "2h ago" (shared util) with the absolute time on hover.
- return (
- <span
- className="px-0.5 text-[0.6875rem] tabular-nums text-muted-foreground"
- title={formatMessageTimestamp(date, t.assistant.thread) || undefined}
- >
- {formatAgo(date.getTime(), t.agents)}
- </span>
- )
-}
-
const AssistantFooter: FC<MessageActionProps> = props => (
<div className="flex min-h-6 flex-col items-end gap-1 pr-(--message-text-indent) pl-(--message-text-indent)">
<BranchPickerPrimitive.Root
diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
index e328867af9e..96e46879c05 100644
--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
@@ -1,5 +1,6 @@
import {
type ReasoningMessagePartComponent,
+ type TextMessagePartProps,
type ToolCallMessagePartProps,
useAuiState,
useMessagePartReasoning
@@ -11,6 +12,7 @@ import { ClarifyTool } from '@/components/assistant-ui/clarify-tool'
import { MarkdownText, MarkdownTextContent } from '@/components/assistant-ui/markdown-text'
import { McpSetupTool } from '@/components/assistant-ui/mcp-setup-tool'
import { AgentDeliveryNotice, deliveryTargetFromCommand } from '@/components/assistant-ui/thread/agent-delivery'
+import { TimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { DelegateTool } from '@/components/assistant-ui/tool/delegate'
import { ToolFallback, ToolGroupSlot } from '@/components/assistant-ui/tool/fallback'
import { formatElapsed, useElapsedSeconds, useMeasuredDuration } from '@/components/chat/activity-timer'
@@ -24,8 +26,10 @@ import { useEnterAnimation } from '@/lib/use-enter-animation'
import { cn } from '@/lib/utils'
import { $reasoningCollapsedByDefault } from '@/store/reasoning-disclosure'
-const ImageGenerateTool: FC<ToolCallMessagePartProps> = props => {
- const { args, result } = props
+type TimelineToolCallProps = ToolCallMessagePartProps & { completedAt?: number; timestamp?: number }
+
+const ImageGenerateTool: FC<TimelineToolCallProps> = props => {
+ const { args, completedAt, result, timestamp } = props
const aspectRatio = typeof args?.aspect_ratio === 'string' ? args.aspect_ratio : undefined
// The image card owns successful generations. Failed or malformed results
@@ -37,22 +41,28 @@ const ImageGenerateTool: FC<ToolCallMessagePartProps> = props => {
return (
<div className="mt-1.5">
+ <TimelineTimestamp className="mb-0.5 block" completedAt={completedAt} timestamp={timestamp} />
<GeneratedImage aspectRatio={aspectRatio} result={result} />
</div>
)
}
-const DelegateToolPart: FC<ToolCallMessagePartProps> = props => {
+const DelegateToolPart: FC<TimelineToolCallProps> = props => {
// A call that failed outright dispatched nothing — there are no children to
// list, only an error. The generic row extracts and expands it properly.
if (props.isError) {
return <ToolFallback {...props} />
}
- return <DelegateTool args={props.args} result={props.result} toolCallId={props.toolCallId} />
+ return (
+ <>
+ <TimelineTimestamp className="mb-0.5 block" completedAt={props.completedAt} timestamp={props.timestamp} />
+ <DelegateTool args={props.args} result={props.result} toolCallId={props.toolCallId} />
+ </>
+ )
}
-const ChainToolFallback: FC<ToolCallMessagePartProps> = props => {
+const ChainToolFallback: FC<TimelineToolCallProps> = props => {
// todo parts are hoisted to a dedicated panel above the message content.
if (props.toolName === 'todo') {
return null
@@ -86,7 +96,12 @@ const ChainToolFallback: FC<ToolCallMessagePartProps> = props => {
}
if (props.toolName === 'clarify') {
- return <ClarifyTool {...props} />
+ return (
+ <>
+ <TimelineTimestamp className="mb-0.5 block" completedAt={props.completedAt} timestamp={props.timestamp} />
+ <ClarifyTool {...props} />
+ </>
+ )
}
if (props.toolName === 'setup_mcp') {
@@ -96,14 +111,25 @@ const ChainToolFallback: FC<ToolCallMessagePartProps> = props => {
return <ToolFallback {...props} />
}
+type TimelineTextPartProps = TextMessagePartProps & { completedAt?: number; timestamp?: number }
+
+const TimelineMarkdownText: FC<TimelineTextPartProps> = ({ completedAt, timestamp }) => (
+ <>
+ <TimelineTimestamp className="mb-0.5 block" completedAt={completedAt} timestamp={timestamp} />
+ <MarkdownText />
+ </>
+)
+
const ThinkingDisclosure: FC<{
children: ReactNode
+ completedAt?: number
messageRunning?: boolean
pending?: boolean
+ timestamp?: number
// Required: the block's duration is remembered against this key, so a
// component that mounts after the block finished can still report it.
timerKey: string
-}> = ({ children, messageRunning = false, pending = false, timerKey }) => {
+}> = ({ children, completedAt, messageRunning = false, pending = false, timestamp, timerKey }) => {
const { t } = useI18n()
const reasoningCollapsedByDefault = useStore($reasoningCollapsedByDefault)
// `null` = no explicit user toggle yet. Live reasoning remains visible by
@@ -182,9 +208,17 @@ const ThinkingDisclosure: FC<{
data-slot="aui_thinking-disclosure"
ref={enterRef}
>
- <ScaffoldRow onToggle={() => setUserOpen(!open)} open={open}>
+ <ScaffoldRow
+ onToggle={() => setUserOpen(!open)}
+ open={open}
+ trailing={
+ <span className="flex shrink-0 items-center gap-1.5">
+ <TimelineTimestamp className={SCAFFOLD_META_CLASS} completedAt={completedAt} timestamp={timestamp} />
+ {pending && <ActivityTimerText className={SCAFFOLD_META_CLASS} seconds={elapsed} />}
+ </span>
+ }
+ >
<span className={cn(SCAFFOLD_LABEL_CLASS, pending && 'shimmer')}>{thoughtLabel}</span>
- {pending && <ActivityTimerText className={SCAFFOLD_META_CLASS} seconds={elapsed} />}
</ScaffoldRow>
{open && (
<div
@@ -237,6 +271,22 @@ const ReasoningAccordionGroup: FC<{ children?: ReactNode; endIndex: number; star
.some(p => p?.type === 'reasoning' && typeof p.text === 'string' && p.text.trim().length > 0)
)
+ const timestamp = useAuiState(s =>
+ s.message.parts.slice(Math.max(0, startIndex), endIndex + 1).reduce<number | undefined>((earliest, part) => {
+ const value = part.type === 'reasoning' ? (part as { timestamp?: number }).timestamp : undefined
+
+ return value === undefined ? earliest : earliest === undefined ? value : Math.min(earliest, value)
+ }, undefined)
+ )
+
+ const completedAt = useAuiState(s =>
+ s.message.parts.slice(Math.max(0, startIndex), endIndex + 1).reduce<number | undefined>((latest, part) => {
+ const value = part.type === 'reasoning' ? (part as { completedAt?: number }).completedAt : undefined
+
+ return value === undefined ? latest : latest === undefined ? value : Math.max(latest, value)
+ }, undefined)
+ )
+
if (!hasContent) {
return null
}
@@ -247,9 +297,11 @@ const ReasoningAccordionGroup: FC<{ children?: ReactNode; endIndex: number; star
// to measure the second and third blocks from the first one's start and
// report the running total as each block's duration.
<ThinkingDisclosure
+ completedAt={completedAt}
messageRunning={messageRunning}
pending={pending}
timerKey={`reasoning:${messageId}:${startIndex}`}
+ timestamp={timestamp}
>
{children}
</ThinkingDisclosure>
@@ -284,7 +336,7 @@ const ReasoningTextPart: ReasoningMessagePartComponent = () => {
export const MESSAGE_PARTS_COMPONENTS = {
Reasoning: ReasoningTextPart,
ReasoningGroup: ReasoningAccordionGroup,
- Text: MarkdownText,
+ Text: TimelineMarkdownText,
ToolGroup: ToolGroupSlot,
tools: { Fallback: ChainToolFallback }
} as const
diff --git a/apps/desktop/src/components/assistant-ui/thread/system-message.tsx b/apps/desktop/src/components/assistant-ui/thread/system-message.tsx
index 2a8e7b17fe8..dcaa7fd1c30 100644
--- a/apps/desktop/src/components/assistant-ui/thread/system-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/system-message.tsx
@@ -2,6 +2,7 @@ import { MessagePrimitive, useAuiState } from '@assistant-ui/react'
import { type FC } from 'react'
import { messageContentText } from '@/components/assistant-ui/thread/content'
+import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { SCAFFOLD_LABEL_CLASS } from '@/components/chat/scaffold-row'
import { Codicon } from '@/components/ui/codicon'
import { ToolIcon } from '@/components/ui/tool-icon'
@@ -60,6 +61,7 @@ export const SystemMessage: FC = () => {
<span className="text-muted-foreground/55">steered</span>
<span className="text-muted-foreground/35">·</span>
<span className="whitespace-pre-wrap">{steerNote.groups.text.trim()}</span>
+ <MessageTimelineTimestamp />
</MessagePrimitive.Root>
)
}
@@ -91,6 +93,7 @@ export const SystemMessage: FC = () => {
<LinkifiedText className="whitespace-pre-wrap" explicitOnly pretty={false} text={output} />
</>
)}
+ <MessageTimelineTimestamp className={cn(multiline ? 'mt-0.5 block' : 'ml-1.5')} />
</MessagePrimitive.Root>
)
}
@@ -107,6 +110,7 @@ export const SystemMessage: FC = () => {
data-slot="aui_system-message-root"
>
<LinkifiedText className="whitespace-pre-wrap" explicitOnly pretty={false} text={text} />
+ <MessageTimelineTimestamp className={cn(multiline ? 'mt-0.5 block' : 'ml-1.5')} />
</MessagePrimitive.Root>
)
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-timestamp.tsx b/apps/desktop/src/components/assistant-ui/thread/timeline-timestamp.tsx
new file mode 100644
index 00000000000..1e74e7600ee
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-timestamp.tsx
@@ -0,0 +1,108 @@
+import { useAuiState } from '@assistant-ui/react'
+import type { FC } from 'react'
+
+import { cn } from '@/lib/utils'
+
+import { formatTimelineRange } from './timestamp'
+
+const preciseDateTime = new Intl.DateTimeFormat(undefined, {
+ day: 'numeric',
+ fractionalSecondDigits: 3,
+ hour: 'numeric',
+ minute: '2-digit',
+ month: 'short',
+ second: '2-digit',
+ year: 'numeric'
+})
+
+const validUnixSeconds = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0
+
+const unixDate = (value: unknown): Date | null => {
+ if (!validUnixSeconds(value)) {
+ return null
+ }
+
+ const date = new Date(value * 1000)
+
+ return Number.isNaN(date.getTime()) ? null : date
+}
+
+export const TimelineTimestamp: FC<{
+ className?: string
+ completedAt?: number
+ timestamp?: number
+}> = ({ className, completedAt, timestamp }) => {
+ const started = unixDate(timestamp)
+
+ if (!started || !validUnixSeconds(timestamp)) {
+ return null
+ }
+
+ const completed =
+ validUnixSeconds(completedAt) && completedAt > timestamp ? unixDate(completedAt) : null
+
+ const validCompletedAt = completed && validUnixSeconds(completedAt) ? completedAt : undefined
+ const startLabel = formatTimelineRange(timestamp, undefined)
+ const completedLabel = validCompletedAt === undefined ? '' : formatTimelineRange(validCompletedAt, undefined)
+
+ const title = completed
+ ? `${preciseDateTime.format(started)} → ${preciseDateTime.format(completed)}`
+ : preciseDateTime.format(started)
+
+ return (
+ <span
+ className={cn('text-[0.625rem] leading-4 tabular-nums text-muted-foreground/55', className)}
+ data-slot="timeline-timestamp"
+ title={title}
+ >
+ <time dateTime={started.toISOString()}>{startLabel}</time>
+ {completed && validCompletedAt !== undefined && (
+ <>
+ {' → '}
+ <time dateTime={completed.toISOString()}>{completedLabel}</time>
+ </>
+ )}
+ </span>
+ )
+}
+
+/** Timestamp for the current assistant-ui message lifecycle. */
+export const MessageTimelineTimestamp: FC<{
+ className?: string
+ suppressIfDuplicatePart?: boolean
+}> = ({ className, suppressIfDuplicatePart = false }) => {
+ const timestamp = useAuiState(s => {
+ const value = (s.message.metadata?.custom as { timelineTimestamp?: unknown } | undefined)?.timelineTimestamp
+
+ return validUnixSeconds(value) ? value : undefined
+ })
+
+ const completedAt = useAuiState(s => {
+ const value = (s.message.metadata?.custom as { timelineCompletedAt?: unknown } | undefined)?.timelineCompletedAt
+
+ return validUnixSeconds(value) ? value : undefined
+ })
+
+ const duplicatePart = useAuiState(s => {
+ const custom = (s.message.metadata?.custom ?? {}) as {
+ timelineCompletedAt?: unknown
+ timelineTimestamp?: unknown
+ }
+
+ const solePart = s.message.parts.length === 1 ? (s.message.parts[0] as { completedAt?: unknown; timestamp?: unknown }) : null
+
+ return (
+ Boolean(solePart) &&
+ solePart?.timestamp === custom.timelineTimestamp &&
+ (solePart?.completedAt === custom.timelineCompletedAt ||
+ (!validUnixSeconds(solePart?.completedAt) && !validUnixSeconds(custom.timelineCompletedAt)))
+ )
+ })
+
+ if (suppressIfDuplicatePart && duplicatePart) {
+ return null
+ }
+
+ return <TimelineTimestamp className={className} completedAt={completedAt} timestamp={timestamp} />
+}
diff --git a/apps/desktop/src/components/assistant-ui/thread/timestamp.test.ts b/apps/desktop/src/components/assistant-ui/thread/timestamp.test.ts
index 938d7de81e0..ea43f22a6d1 100644
--- a/apps/desktop/src/components/assistant-ui/thread/timestamp.test.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/timestamp.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
-import { formatMessageTimestamp } from './timestamp'
+import { formatMessageTimestamp, formatTimelineRange, formatTimelineTimestamp } from './timestamp'
const labels = {
today: (time: string) => `Today at ${time}`,
@@ -34,3 +34,30 @@ describe('formatMessageTimestamp', () => {
expect(out.length).toBeGreaterThan(0)
})
})
+
+describe('precise timeline timestamps', () => {
+ it('includes seconds and milliseconds for an event', () => {
+ const local = new Date(2026, 4, 1, 13, 2, 3, 456)
+ const formatted = formatTimelineTimestamp(local.getTime() / 1000)
+
+ expect(formatted).toMatch(/13|1/)
+ expect(formatted).toContain('02')
+ expect(formatted).toContain('03')
+ expect(formatted).toContain('456')
+ })
+
+ it('renders start and finish as a range', () => {
+ const start = new Date(2026, 4, 1, 13, 2, 3, 456).getTime() / 1000
+ const finish = start + 1.25
+
+ expect(formatTimelineRange(start, finish)).toBe(
+ `${formatTimelineTimestamp(start)} → ${formatTimelineTimestamp(finish)}`
+ )
+ })
+
+ it('returns an empty string for invalid timeline values', () => {
+ expect(formatTimelineTimestamp(undefined)).toBe('')
+ expect(formatTimelineTimestamp(Number.NaN)).toBe('')
+ expect(formatTimelineRange(undefined, 10)).toBe('')
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/timestamp.ts b/apps/desktop/src/components/assistant-ui/thread/timestamp.ts
index f2b0689dd6e..bbe20372085 100644
--- a/apps/desktop/src/components/assistant-ui/thread/timestamp.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/timestamp.ts
@@ -1,5 +1,41 @@
import { fmtClock, fmtDayTime } from '@/lib/time'
+const fmtTimelineClock = new Intl.DateTimeFormat(undefined, {
+ fractionalSecondDigits: 3,
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit'
+})
+
+const timelineDate = (seconds: number | undefined): Date | null => {
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) {
+ return null
+ }
+
+ const date = new Date(seconds * 1000)
+
+ return Number.isNaN(date.getTime()) ? null : date
+}
+
+/** Millisecond-precise local clock for transcript activity boundaries. */
+export function formatTimelineTimestamp(seconds: number | undefined): string {
+ const date = timelineDate(seconds)
+
+ return date ? fmtTimelineClock.format(date) : ''
+}
+
+export function formatTimelineRange(start: number | undefined, end: number | undefined): string {
+ const from = formatTimelineTimestamp(start)
+
+ if (!from) {
+ return ''
+ }
+
+ const to = formatTimelineTimestamp(end)
+
+ return to ? `${from} → ${to}` : from
+}
+
function startOfDay(d: Date): number {
return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
index 22e918389a8..7ac4fd1d04b 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
@@ -4,6 +4,7 @@ import { type FC, type ReactNode, useCallback, useEffect, useRef, useState } fro
import { DirectiveContent } from '@/components/assistant-ui/directive-text'
import { messageAttachmentRefs, messageContentText } from '@/components/assistant-ui/thread/content'
import { ReactionBadge, ReactionPicker } from '@/components/assistant-ui/thread/message-reactions'
+import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { type RestoreMessageTarget } from '@/components/assistant-ui/thread/types'
import { useMessageReactions } from '@/components/assistant-ui/thread/use-message-reactions'
import { UserMessageText } from '@/components/assistant-ui/thread/user-message-text'
@@ -378,6 +379,7 @@ export const UserMessage: FC<{
data-slot="aui_user-message-root"
>
<ProcessNotificationNote text={messageText.trim()} />
+ <MessageTimelineTimestamp className="self-center" />
</MessagePrimitive.Root>
)
}
@@ -571,6 +573,7 @@ export const UserMessage: FC<{
onRetract={() => react(null)}
reactions={shownReactions}
/>
+ <MessageTimelineTimestamp className="self-end pr-1.5" />
<BranchPickerPrimitive.Root
className={cn(
'checkpoint-container flex items-center gap-1 pb-0 pt-1 pl-1.5 text-[0.75rem] leading-none text-(--ui-text-tertiary)',
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model/types.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model/types.ts
index 66afaf48406..844d8069631 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model/types.ts
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model/types.ts
@@ -3,8 +3,10 @@ export type ToolStatus = 'error' | 'running' | 'success' | 'warning'
export interface ToolPart {
args?: unknown
+ completedAt?: number
isError?: boolean
result?: unknown
+ timestamp?: number
toolCallId?: string
toolName: string
type: 'tool-call'
diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
index 6e56d0918c1..b2c94ecf69a 100644
--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx
@@ -18,6 +18,7 @@ import {
import { useSessionView } from '@/app/chat/session-view'
import { AnsiText } from '@/components/assistant-ui/ansi-text'
+import { TimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { useElapsedSeconds } from '@/components/chat/activity-timer'
import { ActivityTimerText } from '@/components/chat/activity-timer-text'
import { CompactMarkdown } from '@/components/chat/compact-markdown'
@@ -353,11 +354,11 @@ function ToolEntry({ part }: ToolEntryProps) {
// below and re-running buildToolView (full JSON.stringify of result) on every
// stream delta — the freeze on big `/learn` runs. Re-derive a stable part from
// the referentially-stable args/result so the memos hold across deltas.
- const { args, isError, result, toolCallId, toolName } = part
+ const { args, completedAt, isError, result, timestamp, toolCallId, toolName } = part
const stablePart = useMemo<ToolPart>(
- () => ({ args, isError, result, toolCallId, toolName, type: 'tool-call' }),
- [args, isError, result, toolCallId, toolName]
+ () => ({ args, completedAt, isError, result, timestamp, toolCallId, toolName, type: 'tool-call' }),
+ [args, completedAt, isError, result, timestamp, toolCallId, toolName]
)
const disclosureId = toolEntryDisclosureId(messageId, stablePart)
@@ -488,8 +489,12 @@ function ToolEntry({ part }: ToolEntryProps) {
// `opacity-0` (yet still clickable) button straddling the caret/duration made
// the disclosure caret hard to hit. Copy now lives in the expanded body's
// top-right, where it can't fight the caret for the right edge.
- const trailing =
- isPending && !embedded ? <ActivityTimerText className={SCAFFOLD_META_CLASS} seconds={elapsed} /> : undefined
+ const trailing = !embedded ? (
+ <span className="flex shrink-0 items-center gap-1.5">
+ <TimelineTimestamp className={SCAFFOLD_META_CLASS} completedAt={completedAt} timestamp={timestamp} />
+ {isPending && <ActivityTimerText className={SCAFFOLD_META_CLASS} seconds={elapsed} />}
+ </span>
+ ) : undefined
// Once a turn has settled, a hover/focus-revealed dismiss lets the user clear
// a completed/failed row that would otherwise sit at the tail of the chat.
@@ -790,19 +795,27 @@ export function splitRunItems(toolNames: readonly string[]): RunItem[] {
// files, ran 5 commands". Live, it narrates in the present tense above the
// ticker and offers no toggle, since there is nothing settled to unfold yet.
function ToolRunHeader({
+ completedAt,
live,
onToggle,
open,
+ startedAt,
summary
}: {
+ completedAt?: number
live: boolean
onToggle?: () => void
open: boolean
+ startedAt?: number
summary: string
}) {
return (
<div data-conversation-scaffold="" data-tool-summary="">
- <ScaffoldRow onToggle={onToggle} open={open}>
+ <ScaffoldRow
+ onToggle={onToggle}
+ open={open}
+ trailing={<TimelineTimestamp completedAt={completedAt} timestamp={startedAt} />}
+ >
<FadeText className={cn(SCAFFOLD_LABEL_CLASS, 'truncate')}>
{live ? <span className="shimmer">{summary}</span> : summary}
</FadeText>
@@ -812,11 +825,13 @@ function ToolRunHeader({
}
interface ToolRunState {
+ completedAt?: number
count: number
/** Disclosure id of each row in the run, so the run can tell when one is open. */
entryIds: readonly string[]
key: string
live: boolean
+ startedAt?: number
/** A call still awaiting a result that could be the one blocking on approval. */
pendingApprovalTool: boolean
summary: string
@@ -832,6 +847,7 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
return useAuiState(state => {
const parts = state.message.parts
const tools = parts.slice(Math.max(0, startIndex), endIndex + 1).filter(isToolCallPart)
+ const timelineTools = tools as unknown as ToolPart[]
// Live means the turn is still working and nothing has come after this run
// — not that some call is unresolved. Those differ in the gap between one
@@ -843,8 +859,11 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
// that moves on to later parts, leaves the run settled and collapsible.
const live = selectMessageRunning(state) && endIndex >= parts.length - 1
- const signature = tools
- .map(tool => `${tool.toolCallId}:${tool.result === undefined ? 0 : 1}`)
+ const signature = timelineTools
+ .map(
+ tool =>
+ `${tool.toolCallId}:${tool.result === undefined ? 0 : 1}:${tool.timestamp ?? ''}:${tool.completedAt ?? ''}`
+ )
.concat(String(live))
.join('|')
@@ -852,10 +871,28 @@ function useToolRun(startIndex: number, endIndex: number): ToolRunState {
cache.current = {
signature,
value: {
+ completedAt: timelineTools.reduce<number | undefined>(
+ (latest, tool) =>
+ tool.completedAt === undefined
+ ? latest
+ : latest === undefined
+ ? tool.completedAt
+ : Math.max(latest, tool.completedAt),
+ undefined
+ ),
count: tools.length,
entryIds: tools.map(tool => toolEntryDisclosureId(state.message.id, tool)),
key: tools[0]?.toolCallId ?? '',
live,
+ startedAt: timelineTools.reduce<number | undefined>(
+ (earliest, tool) =>
+ tool.timestamp === undefined
+ ? earliest
+ : earliest === undefined
+ ? tool.timestamp
+ : Math.min(earliest, tool.timestamp),
+ undefined
+ ),
pendingApprovalTool: tools.some(tool => tool.result === undefined && APPROVAL_TOOLS.has(tool.toolName)),
summary: summarizeToolRun(tools, live)
}
@@ -886,7 +923,12 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =
startIndex
}) => {
const messageRunning = useAuiState(selectMessageRunning)
- const { count, entryIds, key, live, pendingApprovalTool, summary } = useToolRun(startIndex, endIndex)
+
+ const { completedAt, count, entryIds, key, live, pendingApprovalTool, startedAt, summary } = useToolRun(
+ startIndex,
+ endIndex
+ )
+
const sessionId = useStore(useSessionView().$runtimeId)
const approval = useStore(useMemo(() => sessionApprovalRequest(sessionId), [sessionId]))
const disclosureId = `tool-run:${key}`
@@ -917,9 +959,11 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =
ref={enterRef}
>
<ToolRunHeader
+ completedAt={completedAt}
live={live}
onToggle={live ? undefined : () => setToolDisclosureOpen(disclosureId, !expanded)}
open={expanded}
+ startedAt={startedAt}
summary={summary}
/>
{live && !unfurled && <ToolRunTicker>{children}</ToolRunTicker>}
@@ -978,8 +1022,18 @@ export const ToolGroupSlot: FC<PropsWithChildren<{ endIndex: number; startIndex:
* its return type and the underlying ToolEntry stays mounted across
* group-shape changes.
*/
-export const ToolFallback = ({ toolCallId, toolName, args, isError, result }: ToolCallMessagePartProps) => {
- const part: ToolPart = { args, isError, result, toolCallId, toolName, type: 'tool-call' }
+type TimelineToolCallProps = ToolCallMessagePartProps & { completedAt?: number; timestamp?: number }
+
+export const ToolFallback = ({
+ toolCallId,
+ toolName,
+ args,
+ completedAt,
+ isError,
+ result,
+ timestamp
+}: TimelineToolCallProps) => {
+ const part: ToolPart = { args, completedAt, isError, result, timestamp, toolCallId, toolName, type: 'tool-call' }
return <ToolEntry part={part} />
}
diff --git a/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx b/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx
index 39fa91496b1..decc0d03b28 100644
--- a/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx
@@ -8,6 +8,7 @@ import { clearDismissedToolRows } from '@/store/tool-dismiss'
import { $toolDisclosureStates } from '@/store/tool-view'
import { Thread } from '../thread'
+import { formatTimelineRange } from '../thread/timestamp'
// A run of tool calls collapses to a one-line summary once it has settled, but
// a run with anything still pending always renders its rows. That rule is what
@@ -103,7 +104,7 @@ function groupedPendingMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
function pendingOnlyMessage(): ThreadMessage {
@@ -128,7 +129,7 @@ function pendingOnlyMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
function completedOnlyMessage(): ThreadMessage {
@@ -142,6 +143,8 @@ function completedOnlyMessage(): ThreadMessage {
toolName: 'read_file',
args: { path: '/etc/hosts' },
argsText: JSON.stringify({ path: '/etc/hosts' }),
+ timestamp: createdAt.getTime() / 1000 + 10.125,
+ completedAt: createdAt.getTime() / 1000 + 12.875,
result: { content: '127.0.0.1 localhost' }
}
],
@@ -154,7 +157,7 @@ function completedOnlyMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
function failedOnlyMessage(): ThreadMessage {
@@ -181,7 +184,7 @@ function failedOnlyMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
// Two settled activity calls in a row, so the run earns a summary line and
@@ -197,6 +200,8 @@ function settledRunMessage(): ThreadMessage {
toolName: 'read_file',
args: { path: '/repo/src/wiring.tsx' },
argsText: JSON.stringify({ path: '/repo/src/wiring.tsx' }),
+ timestamp: createdAt.getTime() / 1000 + 20,
+ completedAt: createdAt.getTime() / 1000 + 21,
result: { content: 'export const Wiring = () => null' }
},
{
@@ -205,6 +210,8 @@ function settledRunMessage(): ThreadMessage {
toolName: 'terminal',
args: { command: 'ls -la' },
argsText: JSON.stringify({ command: 'ls -la' }),
+ timestamp: createdAt.getTime() / 1000 + 22,
+ completedAt: createdAt.getTime() / 1000 + 23.5,
result: { exit_code: 0, stdout: 'wiring.tsx' }
}
],
@@ -217,7 +224,7 @@ function settledRunMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
// Activity, an edit, then more activity — all adjacent, so assistant-ui hands
@@ -278,7 +285,7 @@ function editBetweenRunsMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
// A finished turn that left a call without a result — interrupted, or the
@@ -313,7 +320,7 @@ function abandonedRunMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
// The gap between one sequential call finishing and the next arriving: the
@@ -350,7 +357,7 @@ function betweenSequentialCallsMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
// Still streaming, but the agent has moved past its first run and left both of
@@ -392,7 +399,7 @@ function movedOnMessage(): ThreadMessage {
steps: [],
custom: {}
}
- } as ThreadMessage
+ } as unknown as ThreadMessage
}
function GroupHarness({ message }: { message: ThreadMessage }) {
@@ -653,3 +660,33 @@ describe('flat tool list approval surfacing', () => {
expect(screen.queryByLabelText('Dismiss')).toBeNull()
})
})
+
+describe('tool lifecycle timestamps', () => {
+ it('shows the precise call and completion times on a settled tool row', async () => {
+ const { container } = render(<GroupHarness message={completedOnlyMessage()} />)
+
+ await screen.findByText(/Read/)
+
+ const timestamps = Array.from(container.querySelectorAll('[data-slot="timeline-timestamp"]')).map(node =>
+ node.textContent?.trim()
+ )
+
+ const startedAt = createdAt.getTime() / 1000 + 10.125
+
+ expect(timestamps).toContain(formatTimelineRange(startedAt, createdAt.getTime() / 1000 + 12.875))
+ })
+
+ it('shows the full lifecycle range when settled calls are collapsed', async () => {
+ const { container } = render(<GroupHarness message={settledRunMessage()} />)
+
+ await waitFor(() => expect(container.querySelector('[data-tool-summary]')).toBeTruthy())
+
+ const timestamps = Array.from(container.querySelectorAll('[data-slot="timeline-timestamp"]')).map(node =>
+ node.textContent?.trim()
+ )
+
+ expect(timestamps).toContain(
+ formatTimelineRange(createdAt.getTime() / 1000 + 20, createdAt.getTime() / 1000 + 23.5)
+ )
+ })
+})
diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.ts
index af178036a46..38bc2aca889 100644
--- a/apps/desktop/src/lib/chat-messages.test.ts
+++ b/apps/desktop/src/lib/chat-messages.test.ts
@@ -8,6 +8,7 @@ import {
appendReasoningPart,
chatMessageText,
collectUnspokenTurnSpeech,
+ completeOpenTimelineParts,
mergeFinalAssistantText,
preserveLocalAssistantErrors,
reasoningPart,
@@ -58,6 +59,25 @@ describe('toChatMessages', () => {
expect(messages).toHaveLength(1)
expect(messages[0].parts.map(p => p.type)).toEqual(['text', 'tool-call', 'text'])
expect(chatMessageText(messages[0])).toBe('Planning.Done.')
+ expect(messages[0].timestamp).toBe(1)
+ expect(messages[0].parts.map(p => p.timestamp)).toEqual([1, 2, 3])
+ })
+
+ it('starts a hydrated bubble at an earlier leading tool call', () => {
+ const messages = toChatMessages([
+ {
+ role: 'assistant',
+ content: '',
+ timestamp: 1,
+ tool_calls: [{ id: 'tc', function: { name: 'terminal', arguments: '{}' } }]
+ },
+ { role: 'tool', tool_call_id: 'tc', content: 'ok', timestamp: 2 },
+ { role: 'assistant', content: 'Done.', timestamp: 3 }
+ ])
+
+ expect(messages).toHaveLength(1)
+ expect(messages[0].timestamp).toBe(1)
+ expect(messages[0].parts.map(part => part.timestamp)).toEqual([1, 3])
})
it('keeps assistant tool-call iterations in one loaded assistant bubble', () => {
@@ -95,6 +115,11 @@ describe('toChatMessages', () => {
const assistantMessages = messages.filter(message => message.role === 'assistant')
expect(assistantMessages).toHaveLength(1)
+ expect(assistantMessages[0].timestamp).toBe(2)
+ expect(assistantMessages[0].parts.map(part => part.timestamp)).toEqual([2, 2, 4, 4, 6])
+ expect(assistantMessages[0].parts.filter(part => part.type === 'tool-call').map(part => part.completedAt)).toEqual([
+ 3, 5
+ ])
expect(assistantMessages[0].parts.filter(part => part.type === 'tool-call')).toHaveLength(2)
expect(chatMessageText(assistantMessages[0])).toContain("Let me also check if there's a top-level lint workflow.")
expect(chatMessageText(assistantMessages[0])).toContain('Now let me check git status and commit.')
@@ -389,39 +414,37 @@ describe('renderMediaTags', () => {
})
})
-describe('interleaved reasoning/text coalescing', () => {
- it('keeps narration contiguous when reasoning interrupts mid-sentence', () => {
- // Models that interleave reasoning_content + content deltas emit
- // text → reasoning → text within one tool-bounded segment. The two text
- // fragments are really one sentence and must not be split by the
- // "Thinking" block between them.
- let parts: ChatMessagePart[] = appendAssistantTextPart([], 'Let me ')
- parts = appendReasoningPart(parts, 'checking the file...')
- parts = appendAssistantTextPart(parts, 'verify the full file is correct:')
+describe('interleaved reasoning/text boundaries', () => {
+ it('preserves text → reasoning → text as three ordered activities', () => {
+ let parts: ChatMessagePart[] = appendAssistantTextPart([], 'Let me ', 1)
+ parts = appendReasoningPart(parts, 'checking the file...', 2)
+ parts = appendAssistantTextPart(parts, 'verify the full file is correct:', 3)
- expect(parts.map(p => p.type)).toEqual(['text', 'reasoning'])
- expect((parts[0] as { text: string }).text).toBe('Let me verify the full file is correct:')
- expect((parts[1] as { text: string }).text).toBe('checking the file...')
+ expect(parts.map(p => p.type)).toEqual(['text', 'reasoning', 'text'])
+ expect(parts.map(p => p.timestamp)).toEqual([1, 2, 3])
+ expect(parts.map(p => p.completedAt)).toEqual([2, 3, undefined])
})
- it('merges reasoning bursts that straddle a narration fragment', () => {
- let parts: ChatMessagePart[] = appendReasoningPart([], 'first thought ')
- parts = appendAssistantTextPart(parts, 'Working on it.')
- parts = appendReasoningPart(parts, 'second thought')
+ it('preserves reasoning → text → reasoning as three ordered activities', () => {
+ let parts: ChatMessagePart[] = appendReasoningPart([], 'first thought ', 1)
+ parts = appendAssistantTextPart(parts, 'Working on it.', 2)
+ parts = appendReasoningPart(parts, 'second thought', 3)
- expect(parts.map(p => p.type)).toEqual(['reasoning', 'text'])
- expect((parts[0] as { text: string }).text).toBe('first thought second thought')
- expect((parts[1] as { text: string }).text).toBe('Working on it.')
+ expect(parts.map(p => p.type)).toEqual(['reasoning', 'text', 'reasoning'])
+ expect(parts.map(p => p.timestamp)).toEqual([1, 2, 3])
+ expect(parts.map(p => p.completedAt)).toEqual([2, 3, undefined])
})
it('starts a fresh text part after a tool call (segment boundary)', () => {
- let parts: ChatMessagePart[] = appendAssistantTextPart([], 'Let me check.')
- parts = upsertToolPart(parts, { name: 'read_file', tool_id: 'tc-1' }, 'running')
- parts = appendAssistantTextPart(parts, 'Now editing.')
+ let parts: ChatMessagePart[] = appendAssistantTextPart([], 'Let me check.', 10.125)
+ parts = upsertToolPart(parts, { name: 'read_file', tool_id: 'tc-1' }, 'running', 11.25)
+ parts = appendAssistantTextPart(parts, 'Now editing.', 12.5)
expect(parts.map(p => p.type)).toEqual(['text', 'tool-call', 'text'])
expect((parts[0] as { text: string }).text).toBe('Let me check.')
expect((parts[2] as { text: string }).text).toBe('Now editing.')
+ expect(parts.map(p => p.timestamp)).toEqual([10.125, 11.25, 12.5])
+ expect(parts[0].completedAt).toBe(11.25)
})
it('does not merge reasoning across a tool call', () => {
@@ -436,6 +459,25 @@ describe('interleaved reasoning/text coalescing', () => {
})
describe('preserveLocalAssistantErrors', () => {
+ it('preserves richer live boundaries when the durable row has only its completion time', () => {
+ const durable = toChatMessages([{ role: 'assistant', content: 'Done.', timestamp: 3 }])
+
+ const live: ChatMessage[] = [
+ {
+ completedAt: 3,
+ id: 'assistant-stream',
+ parts: [{ completedAt: 3, text: 'Done.', timestamp: 1, type: 'text' }],
+ role: 'assistant',
+ timestamp: 1
+ }
+ ]
+
+ const [message] = preserveLocalAssistantErrors(durable, live)
+
+ expect([message.timestamp, message.completedAt]).toEqual([1, 3])
+ expect(message.parts[0]).toMatchObject({ completedAt: 3, timestamp: 1, type: 'text' })
+ })
+
it('preserves a local user+error pair when hydration omits the failed turn', () => {
const nextMessages: ChatMessage[] = [
{
@@ -603,6 +645,48 @@ describe('preserveLocalAssistantErrors', () => {
})
describe('upsertToolPart', () => {
+ it('preserves call time through progress and records completion time', () => {
+ const started = upsertToolPart([], { name: 'read_file', tool_id: 'call-1' }, 'running', 100.125)
+
+ const progressed = upsertToolPart(
+ started,
+ { name: 'read_file', preview: 'still reading', tool_id: 'call-1' },
+ 'running',
+ 101.5
+ )
+
+ const completed = upsertToolPart(
+ progressed,
+ { name: 'read_file', result: { content: 'done' }, tool_id: 'call-1' },
+ 'complete',
+ 102.875
+ )
+
+ expect(completed).toHaveLength(1)
+ expect(completed[0].timestamp).toBe(100.125)
+ expect(completed[0].completedAt).toBe(102.875)
+ })
+
+ it('closes active commentary when a tool starts', () => {
+ const text = appendAssistantTextPart([], 'Checking first.', 20)
+ const withTool = upsertToolPart(text, { name: 'read_file', tool_id: 'call-2' }, 'running', 21)
+
+ expect(withTool[0].completedAt).toBe(21)
+ })
+
+ it('closes active commentary when only a tool completion arrives', () => {
+ const text = appendAssistantTextPart([], 'Checking first.', 20)
+ const withTool = upsertToolPart(text, { name: 'read_file', tool_id: 'call-2' }, 'complete', 21)
+
+ expect(withTool[0].completedAt).toBe(21)
+ })
+
+ it('closes unfinished timeline segments when a turn completes', () => {
+ const parts = appendAssistantTextPart([], 'Done.', 30.25)
+
+ expect(completeOpenTimelineParts(parts, 31.75)[0].completedAt).toBe(31.75)
+ })
+
it('preserves inline diffs from tool completion events', () => {
const parts = upsertToolPart(
[],
@@ -1031,6 +1115,23 @@ describe('upsertToolPart', () => {
})
describe('mergeFinalAssistantText', () => {
+ it('keeps confirmed text-reasoning-text boundaries in the final response', () => {
+ let parts: ChatMessagePart[] = appendAssistantTextPart([], 'First. ', 1)
+ parts = appendReasoningPart(parts, 'Think.', 2)
+ parts = appendAssistantTextPart(parts, 'Last.', 3)
+
+ const result = mergeFinalAssistantText(parts, 'First. Last.', 4)
+
+ expect(result.map(part => part.type)).toEqual(['text', 'reasoning', 'text'])
+ expect(result.map(part => part.timestamp)).toEqual([1, 2, 3])
+ })
+
+ it('timestamps completion-only text when no streamed text preceded it', () => {
+ const result = mergeFinalAssistantText([], 'final answer', 12.5)
+
+ expect(result[0]).toMatchObject({ text: 'final answer', timestamp: 12.5, type: 'text' })
+ })
+
it('removes all text parts and appends the final text', () => {
const parts = [
{ type: 'text' as const, text: 'streamed delta 1' },
diff --git a/apps/desktop/src/lib/chat-messages.ts b/apps/desktop/src/lib/chat-messages.ts
index 3328672e7dd..2a8edd941f5 100644
--- a/apps/desktop/src/lib/chat-messages.ts
+++ b/apps/desktop/src/lib/chat-messages.ts
@@ -8,13 +8,22 @@ import { normalize } from '@/lib/text'
import { parseTodos } from '@/lib/todos'
import type { MessageReaction, SessionMessage, UsageStats } from '@/types/hermes'
-export type ChatMessagePart = Exclude<ThreadMessageLike['content'], string>[number]
+export interface TimelinePartMetadata {
+ /** Unix seconds when this visible activity segment began. Fractional values
+ * preserve the millisecond precision available on live gateway events. */
+ timestamp?: number
+ /** Unix seconds when this segment stopped or handed off to the next one. */
+ completedAt?: number
+}
+
+export type ChatMessagePart = Exclude<ThreadMessageLike['content'], string>[number] & TimelinePartMetadata
export type ChatMessage = {
id: string
role: SessionMessage['role']
parts: ChatMessagePart[]
timestamp?: number
+ completedAt?: number
pending?: boolean
error?: string
branchGroupId?: string
@@ -32,6 +41,9 @@ export type ChatMessage = {
}
export type GatewayEventPayload = {
+ /** Unix seconds supplied by tests/newer gateways; the desktop falls back to
+ * its local receipt clock when older gateways omit it. */
+ timestamp?: number
text?: string
rendered?: string
status?: string
@@ -131,12 +143,12 @@ export type GatewayEventPayload = {
failure_reason?: string
}
-export function textPart(text: string): ChatMessagePart {
- return { type: 'text', text }
+export function textPart(text: string, timestamp?: number): ChatMessagePart {
+ return { type: 'text', text, ...(timestamp !== undefined ? { timestamp } : {}) }
}
-export function reasoningPart(text: string): ChatMessagePart {
- return { type: 'reasoning', text }
+export function reasoningPart(text: string, timestamp?: number): ChatMessagePart {
+ return { type: 'reasoning', text, ...(timestamp !== undefined ? { timestamp } : {}) }
}
const MEDIA_LINE_RE = /(^|\n)[\t ]*[`"']?MEDIA:\s*(?<line>`[^`\n]+`|"[^"\n]+"|'[^'\n]+'|\S+)[`"']?[\t ]*(\n|$)/g
@@ -167,8 +179,8 @@ export function renderMediaTags(text: string): string {
.replace(/\n{3,}/g, '\n\n')
}
-export function assistantTextPart(text: string): ChatMessagePart {
- return textPart(renderMediaTags(text))
+export function assistantTextPart(text: string, timestamp?: number): ChatMessagePart {
+ return textPart(renderMediaTags(text), timestamp)
}
export function chatMessageText(message: ChatMessage): string {
@@ -244,9 +256,28 @@ const normalizeWs = (value: string) => value.replace(/\s+/g, ' ').trim()
* - Keeps all other part types (tool-call, image, etc.).
* - Appends the final text as a new text part.
*/
-export function mergeFinalAssistantText(parts: ChatMessagePart[], finalText: string): ChatMessagePart[] {
+export function mergeFinalAssistantText(
+ parts: ChatMessagePart[],
+ finalText: string,
+ fallbackTimestamp?: number
+): ChatMessagePart[] {
const dedupeReference = normalizeWs(finalText)
+ const streamedText = normalizeWs(
+ parts
+ .filter((part): part is Extract<ChatMessagePart, { type: 'text' }> => part.type === 'text')
+ .map(part => part.text)
+ .join('')
+ )
+
+ // An authoritative final that is exactly the concatenation of streamed text
+ // confirms the content without erasing text↔reasoning activity boundaries.
+ if (streamedText && streamedText === dedupeReference) {
+ return parts
+ }
+
+ const previousText = parts.findLast(part => part.type === 'text')
+
const kept = parts.filter(part => {
if (part.type === 'text') {
// Sealed text parts were already finalized into their own bubbles —
@@ -268,7 +299,17 @@ export function mergeFinalAssistantText(parts: ChatMessagePart[], finalText: str
return !(r && dedupeReference.startsWith(r))
})
- return finalText ? [...kept, assistantTextPart(finalText)] : kept
+ if (!finalText) {
+ return kept
+ }
+
+ const finalPart = assistantTextPart(finalText, previousText?.timestamp ?? fallbackTimestamp)
+
+ if (previousText?.completedAt !== undefined) {
+ finalPart.completedAt = previousText.completedAt
+ }
+
+ return [...kept, finalPart]
}
const ATTACHED_CONTEXT_MARKER_RE = /(?:^|\n)--- Attached Context ---\s*\n/
@@ -407,54 +448,75 @@ function timelineDisplayContent(message: SessionMessage, content: string): strin
return content
}
-const STREAM_PART: Record<'reasoning' | 'text', (text: string) => ChatMessagePart> = {
+const STREAM_PART: Record<'reasoning' | 'text', (text: string, timestamp?: number) => ChatMessagePart> = {
reasoning: reasoningPart,
text: textPart
}
-// Coalesce a streaming delta into the most recent same-type part within the
-// current segment, where a segment is bounded by any non-streaming part (a
-// tool call, image, …). The opposite streaming channel (text <-> reasoning) is
-// transparent, so a reasoning burst between two content deltas can't shred one
-// sentence into text / Thinking / text — the fragmentation models that
-// interleave reasoning_content + content otherwise produce. Tool calls still
-// open a fresh part, preserving narration order across steps.
+function completeOpenStreamParts(parts: ChatMessagePart[], completedAt: number): ChatMessagePart[] {
+ return parts.map(part =>
+ (part.type === 'text' || part.type === 'reasoning') && part.completedAt === undefined
+ ? ({ ...part, completedAt } as ChatMessagePart)
+ : part
+ )
+}
+
+/** Seal every still-open visible activity when the assistant turn stops. */
+export function completeOpenTimelineParts(parts: ChatMessagePart[], completedAt: number): ChatMessagePart[] {
+ return parts.map(part =>
+ part.timestamp !== undefined && part.completedAt === undefined
+ ? ({ ...part, completedAt } as ChatMessagePart)
+ : part
+ )
+}
+
+// Coalesce only adjacent deltas of the same channel. Switching between text
+// and reasoning is a real timeline boundary and must remain visible even when
+// both channels arrive inside one batched renderer flush.
function appendStreamPart(
parts: ChatMessagePart[],
type: 'reasoning' | 'text',
- delta: string
+ delta: string,
+ timestamp?: number
): { index: number; parts: ChatMessagePart[] } {
const next = [...parts]
- for (let i = next.length - 1; i >= 0; i--) {
- const part = next[i]
+ const tailIndex = next.length - 1
+ const tail = next[tailIndex]
- if (part.type === type) {
- next[i] = { ...part, text: `${(part as { text: string }).text}${delta}` } as ChatMessagePart
+ if (tail?.type === type && tail.completedAt === undefined) {
+ next[tailIndex] = { ...tail, text: `${tail.text}${delta}` } as ChatMessagePart
- return { index: i, parts: next }
- }
+ return { index: tailIndex, parts: next }
+ }
- if (part.type !== 'text' && part.type !== 'reasoning') {
- break
- }
+ if (
+ timestamp !== undefined &&
+ (tail?.type === 'text' || tail?.type === 'reasoning') &&
+ tail.completedAt === undefined
+ ) {
+ next[tailIndex] = { ...tail, completedAt: timestamp } as ChatMessagePart
}
- next.push(STREAM_PART[type](delta))
+ next.push(STREAM_PART[type](delta, timestamp))
return { index: next.length - 1, parts: next }
}
-export function appendTextPart(parts: ChatMessagePart[], delta: string): ChatMessagePart[] {
- return appendStreamPart(parts, 'text', delta).parts
+export function appendTextPart(parts: ChatMessagePart[], delta: string, timestamp?: number): ChatMessagePart[] {
+ return appendStreamPart(parts, 'text', delta, timestamp).parts
}
-export function appendReasoningPart(parts: ChatMessagePart[], delta: string): ChatMessagePart[] {
- return appendStreamPart(parts, 'reasoning', delta).parts
+export function appendReasoningPart(parts: ChatMessagePart[], delta: string, timestamp?: number): ChatMessagePart[] {
+ return appendStreamPart(parts, 'reasoning', delta, timestamp).parts
}
-export function appendAssistantTextPart(parts: ChatMessagePart[], delta: string): ChatMessagePart[] {
- const { index, parts: next } = appendStreamPart(parts, 'text', delta)
+export function appendAssistantTextPart(
+ parts: ChatMessagePart[],
+ delta: string,
+ timestamp?: number
+): ChatMessagePart[] {
+ const { index, parts: next } = appendStreamPart(parts, 'text', delta, timestamp)
const part = next[index]
if (part?.type !== 'text') {
@@ -675,11 +737,14 @@ function toolResult(
export function upsertToolPart(
parts: ChatMessagePart[],
payload: GatewayEventPayload | undefined,
- phase: 'running' | 'complete'
+ phase: 'running' | 'complete',
+ occurredAt = Date.now() / 1000
): ChatMessagePart[] {
const stableId = toolId(payload)
const name = payload?.name || 'tool'
- const next = [...parts]
+ // A completion can be the first tool event observed after reconnect, so it
+ // also constitutes a text/reasoning -> tool boundary when no start arrived.
+ const next = completeOpenStreamParts(parts, occurredAt)
const index = findToolPartIndex(next, name, stableId, payload, phase)
@@ -699,7 +764,12 @@ export function upsertToolPart(
toolName: name,
args: args as never,
argsText: JSON.stringify(args),
- ...(phase === 'complete' && { result: toolResult(payload, prevResult, prevArgs), isError: Boolean(payload?.error) })
+ timestamp: prev?.timestamp ?? occurredAt,
+ ...(phase === 'complete' && {
+ completedAt: occurredAt,
+ result: toolResult(payload, prevResult, prevArgs),
+ isError: Boolean(payload?.error)
+ })
} satisfies ChatMessagePart
if (index === -1) {
@@ -826,7 +896,7 @@ function parseStoredToolResult(content: unknown): unknown {
}
}
-function toolPartFromStoredCall(call: unknown, fallbackIndex: number): ChatMessagePart {
+function toolPartFromStoredCall(call: unknown, fallbackIndex: number, timestamp?: number): ChatMessagePart {
const row = recordFromUnknown(call) ?? {}
const fn = recordFromUnknown(row.function)
const id = String(row.id || row.tool_call_id || `stored-tool-${fallbackIndex}`)
@@ -842,7 +912,8 @@ function toolPartFromStoredCall(call: unknown, fallbackIndex: number): ChatMessa
toolCallId: id,
toolName,
args: args as never,
- argsText: Object.keys(args).length ? JSON.stringify(args) : ''
+ argsText: Object.keys(args).length ? JSON.stringify(args) : '',
+ ...(timestamp !== undefined ? { timestamp } : {})
}
}
@@ -872,6 +943,7 @@ function applyStoredToolResult(messages: ChatMessage[], toolMessage: SessionMess
const existing = parts[partIndex]
parts[partIndex] = {
...existing,
+ completedAt: toolMessage.timestamp,
result: parseStoredToolResult(content),
isError: false
} as ChatMessagePart
@@ -902,6 +974,7 @@ function applyStoredToolResultToParts(parts: ChatMessagePart[], toolMessage: Ses
const existing = next[partIndex]
next[partIndex] = {
...existing,
+ completedAt: toolMessage.timestamp,
result: parseStoredToolResult(content),
isError: false
} as ChatMessagePart
@@ -925,6 +998,8 @@ function storedToolMessagePart(toolMessage: SessionMessage, fallbackIndex: numbe
toolName: name,
args: args as never,
argsText: Object.keys(args).length ? JSON.stringify(args) : '',
+ timestamp: toolMessage.timestamp,
+ completedAt: toolMessage.timestamp,
result: context ? { context } : {},
isError: false
}
@@ -977,6 +1052,12 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
pendingToolTimestamp = undefined
}
+ const earliestTimestamp = (...values: (number | undefined)[]) => {
+ const timestamps = values.filter((value): value is number => value !== undefined)
+
+ return timestamps.length ? Math.min(...timestamps) : undefined
+ }
+
const appendPartsToActiveAssistant = (parts: ChatMessagePart[], timestamp?: number): boolean => {
if (activeAssistantIndex === null) {
return false
@@ -991,7 +1072,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
}
active.parts = [...active.parts, ...parts]
- active.timestamp = timestamp ?? active.timestamp
+ active.timestamp = earliestTimestamp(active.timestamp, timestamp, ...parts.map(part => part.timestamp))
return true
}
@@ -1068,15 +1149,21 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
(typeof message.reasoning_details === 'string' ? message.reasoning_details : '')
if (reasoning && message.role === 'assistant') {
- parts.push(reasoningPart(reasoning))
+ parts.push(reasoningPart(reasoning, message.timestamp))
}
if (displayContent) {
- parts.push(displayRole === 'assistant' ? assistantTextPart(displayContent) : textPart(displayContent))
+ parts.push(
+ displayRole === 'assistant'
+ ? assistantTextPart(displayContent, message.timestamp)
+ : textPart(displayContent, message.timestamp)
+ )
}
if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {
- parts.push(...message.tool_calls.map((call, callIndex) => toolPartFromStoredCall(call, callIndex)))
+ parts.push(
+ ...message.tool_calls.map((call, callIndex) => toolPartFromStoredCall(call, callIndex, message.timestamp))
+ )
}
if (!parts.length && !extractedAttachmentRefs?.length) {
@@ -1117,7 +1204,11 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
if (activeAssistant && (currentHasToolCall || activeHasToolCall)) {
activeAssistant.parts = [...activeAssistant.parts, ...parts]
- activeAssistant.timestamp = message.timestamp ?? activeAssistant.timestamp
+ activeAssistant.timestamp = earliestTimestamp(
+ activeAssistant.timestamp,
+ message.timestamp,
+ ...parts.map(part => part.timestamp)
+ )
return
}
@@ -1135,7 +1226,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
id: `${message.timestamp || Date.now()}-${index}-${displayRole}`,
role: displayRole,
parts,
- timestamp: message.timestamp,
+ timestamp: earliestTimestamp(message.timestamp, ...parts.map(part => part.timestamp)),
...(rowId !== undefined ? { rowId } : {}),
...(reactions.length ? { reactions } : {}),
...(extractedAttachmentRefs ? { attachmentRefs: extractedAttachmentRefs } : {})
@@ -1156,10 +1247,127 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
)
}
+const validTimelineBoundary = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0
+
+const earliestBoundary = (...values: (number | undefined)[]) => {
+ const valid = values.filter(validTimelineBoundary)
+
+ return valid.length ? Math.min(...valid) : undefined
+}
+
+const latestBoundary = (...values: (number | undefined)[]) => {
+ const valid = values.filter(validTimelineBoundary)
+
+ return valid.length ? Math.max(...valid) : undefined
+}
+
+const normalizedTimelineText = (message: ChatMessage) => chatMessageText(message).replace(/\s+/g, ' ').trim()
+
+const assistantTimelineMatch = (stored: ChatMessage, local: ChatMessage) => {
+ if (stored.id === local.id) {
+ return true
+ }
+
+ const localToolIds = new Set(
+ local.parts.filter(part => part.type === 'tool-call').map(part => (part.type === 'tool-call' ? part.toolCallId : ''))
+ )
+
+ const toolMatch = stored.parts.some(part => part.type === 'tool-call' && localToolIds.has(part.toolCallId))
+
+ if (toolMatch) {
+ return true
+ }
+
+ const storedText = normalizedTimelineText(stored)
+
+ return Boolean(storedText) && storedText === normalizedTimelineText(local)
+}
+
+const timelinePartMatch = (stored: ChatMessagePart, local: ChatMessagePart) => {
+ if (stored.type !== local.type) {
+ return false
+ }
+
+ if (stored.type === 'tool-call' && local.type === 'tool-call') {
+ return stored.toolCallId === local.toolCallId
+ }
+
+ if ((stored.type === 'text' || stored.type === 'reasoning') && local.type === stored.type) {
+ return stored.text.replace(/\s+/g, ' ').trim() === local.text.replace(/\s+/g, ' ').trim()
+ }
+
+ return false
+}
+
+/** Keep richer live timing when durable hydration has only one timestamp per row. */
+export function reconcileLocalAssistantTimeline(
+ nextMessages: ChatMessage[],
+ currentMessages: ChatMessage[]
+): ChatMessage[] {
+ const localAssistants = currentMessages.filter(message => message.role === 'assistant' && !message.hidden)
+ const matches = new Map<number, ChatMessage>()
+ let localCursor = localAssistants.length - 1
+
+ for (let nextIndex = nextMessages.length - 1; nextIndex >= 0; nextIndex -= 1) {
+ const message = nextMessages[nextIndex]
+
+ if (message.role !== 'assistant' || message.hidden) {
+ continue
+ }
+
+ for (let localIndex = localCursor; localIndex >= 0; localIndex -= 1) {
+ const local = localAssistants[localIndex]
+
+ if (assistantTimelineMatch(message, local)) {
+ matches.set(nextIndex, local)
+ localCursor = localIndex - 1
+
+ break
+ }
+ }
+ }
+
+ return nextMessages.map((message, messageIndex) => {
+ const local = matches.get(messageIndex)
+
+ if (!local) {
+ return message
+ }
+
+ const unusedLocalParts = new Set(local.parts.map((_, index) => index))
+
+ const parts = message.parts.map(part => {
+ const localIndex = local.parts.findIndex((candidate, index) => unusedLocalParts.has(index) && timelinePartMatch(part, candidate))
+
+ if (localIndex === -1) {
+ return part
+ }
+
+ unusedLocalParts.delete(localIndex)
+ const localPart = local.parts[localIndex]
+
+ return {
+ ...part,
+ completedAt: latestBoundary(part.completedAt, localPart.completedAt),
+ timestamp: earliestBoundary(part.timestamp, localPart.timestamp)
+ } as ChatMessagePart
+ })
+
+ return {
+ ...message,
+ completedAt: latestBoundary(message.completedAt, local.completedAt, ...parts.map(part => part.completedAt)),
+ parts,
+ timestamp: earliestBoundary(message.timestamp, local.timestamp, ...parts.map(part => part.timestamp))
+ }
+ })
+}
+
export function preserveLocalAssistantErrors(
nextMessages: ChatMessage[],
currentMessages: ChatMessage[]
): ChatMessage[] {
+ nextMessages = reconcileLocalAssistantTimeline(nextMessages, currentMessages)
const localById = new Map(currentMessages.map(message => [message.id, message]))
const mergedNextMessages = nextMessages.map(message => {
diff --git a/apps/desktop/src/lib/chat-runtime.test.ts b/apps/desktop/src/lib/chat-runtime.test.ts
index 09c079e688a..c4a6727a111 100644
--- a/apps/desktop/src/lib/chat-runtime.test.ts
+++ b/apps/desktop/src/lib/chat-runtime.test.ts
@@ -9,7 +9,8 @@ import {
messageCreatedAt,
optimisticAttachmentRef,
parseCommandDispatch,
- parseSlashCommand
+ parseSlashCommand,
+ toRuntimeMessage
} from './chat-runtime'
const DATA_URL = 'data:image/png;base64,iVBORw0KGgoAAAANS'
@@ -238,3 +239,15 @@ describe('messageCreatedAt', () => {
expect(messageCreatedAt({ timestamp: Number.NaN }, NOW).getTime()).toBe(NOW)
})
})
+
+describe('toRuntimeMessage timeline metadata', () => {
+ it('does not expose a fabricated visible timestamp for timestamp-less history', () => {
+ const runtime = toRuntimeMessage({
+ id: 'old-message',
+ parts: [{ text: 'old', type: 'text' }],
+ role: 'assistant'
+ })
+
+ expect((runtime.metadata?.custom as { timelineTimestamp?: number }).timelineTimestamp).toBeUndefined()
+ })
+})
diff --git a/apps/desktop/src/lib/chat-runtime.ts b/apps/desktop/src/lib/chat-runtime.ts
index c976e98fffd..aaa594160de 100644
--- a/apps/desktop/src/lib/chat-runtime.ts
+++ b/apps/desktop/src/lib/chat-runtime.ts
@@ -434,6 +434,11 @@ export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
...(message.reactions?.length ? { reactions: message.reactions } : {})
}
+ const timelineMeta =
+ typeof message.timestamp === 'number' && Number.isFinite(message.timestamp) && message.timestamp > 0
+ ? { timelineTimestamp: message.timestamp }
+ : {}
+
if (role === 'user') {
return {
id: message.id,
@@ -441,7 +446,7 @@ export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
content: message.parts.filter((part): part is Extract<ChatMessagePart, { type: 'text' }> => part.type === 'text'),
attachments: [],
createdAt,
- metadata: { custom: { attachmentRefs: message.attachmentRefs ?? [], ...reactionMeta } }
+ metadata: { custom: { attachmentRefs: message.attachmentRefs ?? [], ...reactionMeta, ...timelineMeta } }
} as ThreadMessage
}
@@ -453,7 +458,7 @@ export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
role,
content: [textPart(text)],
createdAt,
- metadata: { custom: {} }
+ metadata: { custom: timelineMeta }
} as ThreadMessage
}
@@ -473,7 +478,12 @@ export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
unstable_data: [],
steps: [],
// Carries ChatMessage.interim to AssistantMessage's footer gate.
- custom: { ...(message.interim ? { interim: true } : {}), ...reactionMeta }
+ custom: {
+ ...(message.interim ? { interim: true } : {}),
+ ...timelineMeta,
+ ...(message.completedAt !== undefined ? { timelineCompletedAt: message.completedAt } : {}),
+ ...reactionMeta
+ }
}
} as ThreadMessage
}
@@ -522,7 +532,13 @@ export function coalesceToolOnlyAssistants(messages: ChatMessage[], cache: ToolM
const merged =
cached && cached.prev === prev && cached.prevParts === prev.parts && cached.parts === message.parts
? cached.merged
- : { ...prev, parts: [...prev.parts, ...message.parts] }
+ : {
+ ...prev,
+ completedAt: [prev.completedAt, message.completedAt, ...message.parts.map(part => part.completedAt)]
+ .filter((value): value is number => value !== undefined)
+ .reduce<number | undefined>((latest, value) => (latest === undefined ? value : Math.max(latest, value)), undefined),
+ parts: [...prev.parts, ...message.parts]
+ }
cache.set(message, { merged, parts: message.parts, prev, prevParts: prev.parts })
out[out.length - 1] = merged
diff --git a/apps/desktop/src/lib/tool-run-continuity.test.ts b/apps/desktop/src/lib/tool-run-continuity.test.ts
index a009053db3d..19555654105 100644
--- a/apps/desktop/src/lib/tool-run-continuity.test.ts
+++ b/apps/desktop/src/lib/tool-run-continuity.test.ts
@@ -248,3 +248,37 @@ describe('run identity', () => {
expect(runs.map(run => run.map(t => t.toolCallId))).toEqual([['a'], ['b']])
})
})
+
+describe('coalesced tool lifecycle', () => {
+ it('keeps the latest completion boundary from a folded tool-only message', () => {
+ const messages: ChatMessage[] = [
+ {
+ completedAt: 2,
+ id: 'assistant-text',
+ parts: [assistantTextPart('Checking.')],
+ role: 'assistant',
+ timestamp: 1
+ },
+ {
+ id: 'assistant-tool',
+ parts: [
+ {
+ args: {} as never,
+ argsText: '{}',
+ completedAt: 5,
+ timestamp: 3,
+ toolCallId: 'call-1',
+ toolName: 'terminal',
+ type: 'tool-call'
+ }
+ ],
+ role: 'assistant',
+ timestamp: 3
+ }
+ ]
+
+ const [merged] = coalesceToolOnlyAssistants(messages, createToolMergeCache())
+
+ expect(merged.completedAt).toBe(5)
+ })
+})