Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(chat): stamp a thinking part's duration in the parser, from its request

reviewa06ddbf86287
diff --git a/src/core/transcript-reader.test.ts b/src/core/transcript-reader.test.ts
index 0aa773ac0..2e0716021 100644
--- a/src/core/transcript-reader.test.ts
+++ b/src/core/transcript-reader.test.ts
@@ -112,7 +112,7 @@ describe('readSessionName — remote (SSH project) sessions', () => {
// ─────────────────────────────────────────────────────────────────────────────────────────────
import os from 'os'
import path from 'path'
-import { parseChatMessages, parseChatWindow, readChatWindow, SYSTEM_RESULT_MAX } from './transcript-reader'
+import { claudeChatRecordParser, parseChatMessages, parseChatWindow, readChatWindow, SYSTEM_RESULT_MAX } from './transcript-reader'
const jl = (o: object): string => JSON.stringify(o) + '\n'
const said = (role: 'user' | 'assistant', text: string): string =>
@@ -364,8 +364,17 @@ describe('message time (`at`, from the line\'s ISO `timestamp`)', () => {
})
describe('thinking parts (opt-in `thinking`)', () => {
- const assistantThinkingLine = (thinking: string): string =>
- jl({ type: 'assistant', message: { content: [{ type: 'thinking', thinking, signature: 'sig' }] } })
+ const T0 = Date.parse('2026-11-02T10:00:00.000Z')
+ const iso = (ms: number): string => new Date(T0 + ms).toISOString()
+ const assistantThinkingLine = (thinking: string, timestamp?: string): string =>
+ jl({ type: 'assistant', timestamp, message: { id: 'msg_1', content: [{ type: 'thinking', thinking, signature: 'sig' }] } })
+ const promptAt = (timestamp?: string): string => jl({ type: 'user', timestamp, message: { content: 'go' } })
+ const thinkingPart = (raw: string, opts = { thinking: true }) => {
+ const msgs = parseChatMessages(raw.split('\n'), opts)
+ const parts = msgs.flatMap((m) => m.parts).filter((p) => p.kind === 'thinking')
+ expect(parts).toHaveLength(1)
+ return parts[0] as { kind: 'thinking'; text: string; ms?: number }
+ }
it('caps a thinking text at SYSTEM_RESULT_MAX, like a system record\'s body', () => {
const msgs = parseChatMessages([assistantThinkingLine('x'.repeat(SYSTEM_RESULT_MAX + 5))], { thinking: true })
@@ -377,6 +386,51 @@ describe('thinking parts (opt-in `thinking`)', () => {
it('without the option a thinking-only line is still no message (unchanged)', () => {
expect(parseChatMessages([assistantThinkingLine('x'.repeat(SYSTEM_RESULT_MAX + 5))])).toEqual([])
+ expect(parseChatMessages((promptAt(iso(0)) + assistantThinkingLine('hmm', iso(12_400))).split('\n'))).toEqual([
+ { role: 'user', parts: [{ kind: 'text', text: 'go' }], at: T0 }
+ ])
+ })
+
+ it('stamps how long the model thought: from the user prompt 12.4 s earlier', () => {
+ expect(thinkingPart(promptAt(iso(0)) + assistantThinkingLine('hmm', iso(12_400)))).toEqual({ kind: 'thinking', text: 'hmm', ms: 12_400 })
+ })
+
+ it('measures from the newest USER record, not the record right before the thinking (the shape claude writes)', () => {
+ // Measured: the record right before a thinking summary is an EMPTY encrypted thinking block of
+ // the same message ~10 ms earlier, with attachment / api-request lines in between; the request
+ // started at the tool_result.
+ const raw =
+ toolUse('t1', 'ls') +
+ jl({ type: 'user', timestamp: iso(0), message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: 'x' }] } }) +
+ jl({ type: 'attachment', timestamp: iso(5), attachment: { type: 'todo_reminder' } }) +
+ jl({ type: 'api-request', timestamp: iso(20) }) +
+ jl({ type: 'assistant', timestamp: iso(8_990), message: { id: 'msg_1', content: [{ type: 'thinking', thinking: '', signature: 'sig' }] } }) +
+ assistantThinkingLine('now the fix', iso(9_000))
+ expect(thinkingPart(raw).ms).toBe(9_000)
+ })
+
+ it('a hidden meta user line is a request too', () => {
+ const meta = jl({ type: 'user', isMeta: true, timestamp: iso(3_000), message: { content: 'caveat' } })
+ expect(thinkingPart(promptAt(iso(0)) + meta + assistantThinkingLine('hmm', iso(5_000))).ms).toBe(2_000)
+ })
+
+ it('no `ms` when the newest user record is unstamped, the gap is negative, or no user record precedes it', () => {
+ expect('ms' in thinkingPart(promptAt(iso(0)) + promptAt(undefined) + assistantThinkingLine('hmm', iso(12_400)))).toBe(false)
+ expect('ms' in thinkingPart(promptAt(iso(0)) + assistantThinkingLine('hmm', undefined))).toBe(false)
+ expect('ms' in thinkingPart(promptAt(iso(12_400)) + assistantThinkingLine('hmm', iso(0)))).toBe(false)
+ // The first record in the window.
+ expect('ms' in thinkingPart(assistantThinkingLine('hmm', iso(12_400)))).toBe(false)
+ })
+
+ it('a paged window that starts after the prompt carries no `ms` (it cannot see the request)', () => {
+ const prompt = promptAt(iso(0))
+ const file = Buffer.from(prompt + assistantThinkingLine('hmm', iso(12_400)))
+ const parse = claudeChatRecordParser({ thinking: true })
+ const whole = parseChatWindow(file, 0, parse).messages.flatMap((m) => m.parts)
+ expect(whole[1]).toEqual({ kind: 'thinking', text: 'hmm', ms: 12_400 })
+ // The window starts on the thinking line: the buffer begins one lookbehind byte earlier.
+ const older = parseChatWindow(file.subarray(prompt.length - 1), prompt.length - 1, parse).messages.flatMap((m) => m.parts)
+ expect(older).toEqual([{ kind: 'thinking', text: 'hmm' }])
})
})
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index 513ba7fc2..c14672211 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -363,7 +363,8 @@ export interface ChatParseOptions {
* claude's TUI prints between tool calls. Most thinking blocks carry only an encrypted
* `signature` and an empty `thinking` (measured: 137 of 913 on one machine had text); those, and
* every `redacted_thinking`, yield nothing either way. Off by default: the shared golden fixtures
- * (`thinking.pages.json`) and the phone's `chat.page` keep dropping them.
+ * (`thinking.pages.json`) and the phone's `chat.page` keep dropping them. Each part carries `ms`,
+ * how long the model thought, when the stamps can tell (see the `ChatPart` type).
*/
thinking?: boolean
}
@@ -532,6 +533,9 @@ function parseChatRecords(
// its output record (cleared by any other push, so output attaches only to the record right
// before it).
let awaitingOutput: { family: 'slash' | 'bash'; part: Extract<ChatPart, { kind: 'tool' }> } | null = null
+ // The stamp of the newest `user` record so far, hidden meta lines included: when the request a
+ // thinking record answers was made, so its `ms` (see the type). Read only on the opt-in branch.
+ let lastUserAt: number | undefined
const push = (m: ChatMessage, offset: number): void => {
awaitingOutput = null
// `at` rides BOTH paths (additive): the time the line was written, for the thread's relative
@@ -554,6 +558,8 @@ function parseChatRecords(
// `null` / a number / a string parse fine and would throw on the reads below, failing the whole
// page over one line another program wrote. One bad line costs one line (the Swift port agrees).
if (!o || typeof o !== 'object' || Array.isArray(o)) continue
+ // Before the meta check: a hidden user line is still a request the model answers.
+ if (o.type === 'user') lastUserAt = lineTime(o.timestamp)
if (isHiddenMetaRecord(o)) continue
at = lineTime(o.timestamp)
const content = o.message?.content
@@ -576,7 +582,13 @@ function parseChatRecords(
else if (c.type === 'thinking') {
if (opts?.thinking && typeof c.thinking === 'string' && c.thinking.trim()) {
// Capped like a system record's body: one runaway block must not size the whole page.
- parts.push({ kind: 'thinking', text: c.thinking.slice(0, SYSTEM_RESULT_MAX) })
+ const part: Extract<ChatPart, { kind: 'thinking' }> = {
+ kind: 'thinking',
+ text: c.thinking.slice(0, SYSTEM_RESULT_MAX)
+ }
+ const ms = at !== undefined && lastUserAt !== undefined ? at - lastUserAt : undefined
+ if (ms !== undefined && ms >= 0) part.ms = ms
+ parts.push(part)
}
}
else if (c.type === 'tool_use') {
diff --git a/src/renderer/lib/chatThinking.test.ts b/src/renderer/lib/chatThinking.test.ts
index cd63e3ab1..b45132ba2 100644
--- a/src/renderer/lib/chatThinking.test.ts
+++ b/src/renderer/lib/chatThinking.test.ts
@@ -1,45 +1,5 @@
import { describe, expect, it } from 'vitest'
-import type { ChatMessage } from '@shared/types'
-import { thinkingDuration, thinkingLabel } from './chatThinking'
-
-const think = (at?: number): ChatMessage => ({ role: 'assistant', parts: [{ kind: 'thinking', text: 'hmm' }], ...(at === undefined ? {} : { at }) })
-const say = (at?: number): ChatMessage => ({ role: 'assistant', parts: [{ kind: 'text', text: 'ok' }], ...(at === undefined ? {} : { at }) })
-
-describe('thinkingDuration', () => {
- it('duration is the gap to the next stamped message', () => {
- expect(thinkingDuration([think(1000), say(13_400)], 0)).toBe(12_400)
- })
-
- it('a zero gap is a duration, not "unknown"', () => {
- expect(thinkingDuration([think(5000), say(5000)], 0)).toBe(0)
- })
-
- it('no duration for the last message, an unstamped neighbour, a negative gap, or a mixed message', () => {
- // The last message has no next one to measure against.
- expect(thinkingDuration([say(0), think(1000)], 1)).toBeUndefined()
- // Either stamp missing.
- expect(thinkingDuration([think(), say(13_400)], 0)).toBeUndefined()
- expect(thinkingDuration([think(1000), say()], 0)).toBeUndefined()
- // The next line is stamped EARLIER (another machine's clock): never a negative duration.
- expect(thinkingDuration([think(13_400), say(1000)], 0)).toBeUndefined()
- // A message that also holds text or a tool did not spend the gap thinking alone.
- const mixed: ChatMessage = { role: 'assistant', parts: [{ kind: 'thinking', text: 'hmm' }, { kind: 'text', text: 'ok' }], at: 1000 }
- expect(thinkingDuration([mixed, say(13_400)], 0)).toBeUndefined()
- const withTool: ChatMessage = {
- role: 'assistant',
- parts: [{ kind: 'thinking', text: 'hmm' }, { kind: 'tool', name: 'Bash', arg: 'ls' }],
- at: 1000
- }
- expect(thinkingDuration([withTool, say(13_400)], 0)).toBeUndefined()
- })
-
- it('no duration for a message that is not thinking at all, or an index out of range', () => {
- expect(thinkingDuration([say(1000), say(13_400)], 0)).toBeUndefined()
- expect(thinkingDuration([{ role: 'assistant', parts: [], at: 1000 }, say(13_400)], 0)).toBeUndefined()
- expect(thinkingDuration([think(1000)], 5)).toBeUndefined()
- expect(thinkingDuration([], 0)).toBeUndefined()
- })
-})
+import { thinkingLabel } from './chatThinking'
describe('thinkingLabel', () => {
it.each([
diff --git a/src/renderer/lib/chatThinking.ts b/src/renderer/lib/chatThinking.ts
index 815fa610c..5a075ef33 100644
--- a/src/renderer/lib/chatThinking.ts
+++ b/src/renderer/lib/chatThinking.ts
@@ -1,23 +1,6 @@
-// Pure decisions behind the ⌘M thread's thinking fold (ChatPanel): how long a thinking block took,
-// and what its summary line says. No React — see ChatPanel.tsx for the glue and chatThinking.test.ts
-// for the pins.
-import type { ChatMessage } from '@shared/types'
-
-/**
- * How long message `i` spent thinking, in ms: the gap from its `at` to the NEXT message's `at`.
- *
- * Only when message `i` holds ONLY thinking parts — a line that also carries text or a tool call did
- * not spend that gap thinking — and both lines are stamped. A negative gap (the next line written by
- * a clock behind this one) is no duration either: undefined, never a made-up or negative time.
- */
-export function thinkingDuration(messages: readonly ChatMessage[], i: number): number | undefined {
- const m = messages[i]
- const next = messages[i + 1]
- if (!m || !next || m.at === undefined || next.at === undefined) return undefined
- if (m.parts.length === 0 || !m.parts.every((p) => p.kind === 'thinking')) return undefined
- const gap = next.at - m.at
- return gap >= 0 ? gap : undefined
-}
+// The ⌘M thread's thinking fold (ChatPanel): what its summary line says. How long the thinking took
+// is the parser's to stamp (`ms` on the part — see `ChatPart` in shared/types.ts for why the thread
+// cannot derive it from its neighbours). No React — see chatThinking.test.ts for the pins.
/** The fold's summary: "Thinking" with no duration, else "Thought for 12s" / "Thought for 1m 35s". */
export function thinkingLabel(ms: number | undefined): string {
diff --git a/src/renderer/nodes/ChatPanel.thread.test.tsx b/src/renderer/nodes/ChatPanel.thread.test.tsx
index 75a75a411..aa601c5ca 100644
--- a/src/renderer/nodes/ChatPanel.thread.test.tsx
+++ b/src/renderer/nodes/ChatPanel.thread.test.tsx
@@ -207,12 +207,11 @@ describe('⌘M thread look', () => {
expect(days[1].nextElementSibling?.classList.contains('term-chat__msg--folded')).toBe(true)
})
- it('a thinking part is a closed fold labelled with its duration', async () => {
- const u: ChatMessage = { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0, at: now - 30_000 }
+ it('a thinking part is a closed fold labelled with the duration the parser stamped', async () => {
await mount([
- u,
- { role: 'assistant', parts: [{ kind: 'thinking', text: 'hmm **deep**' }], key: 10, at: now - 20_000 },
- { role: 'assistant', parts: [{ kind: 'text', text: 'ok' }], key: 20, at: now - 8_000 }
+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0 },
+ { role: 'assistant', parts: [{ kind: 'thinking', text: 'hmm **deep**', ms: 12_400 }], key: 10 },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'ok' }], key: 20 }
])
const d = host.querySelector<HTMLDetailsElement>('details.term-chat__thinking')!
expect(d.open).toBe(false)
@@ -220,11 +219,11 @@ describe('⌘M thread look', () => {
expect(d.querySelector('.term-chat__text strong')?.textContent).toBe('deep')
})
- it('a thinking fold with no measurable duration just says Thinking', async () => {
+ it('a thinking fold without a stamped duration just says Thinking, whatever its neighbours\' times', async () => {
await mount([
- { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0 },
- { role: 'assistant', parts: [{ kind: 'thinking', text: 'hmm' }], key: 10 },
- { role: 'assistant', parts: [{ kind: 'text', text: 'ok' }], key: 20 }
+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0, at: now - 30_000 },
+ { role: 'assistant', parts: [{ kind: 'thinking', text: 'hmm' }], key: 10, at: now - 20_000 },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'ok' }], key: 20, at: now - 8_000 }
])
expect(host.querySelector('details.term-chat__thinking > summary')?.textContent).toBe('Thinking')
})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 1bd312c5b..7b77909d0 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -58,7 +58,7 @@ import { useCodeBlockCopy } from './CodeBlockCopy'
import { useCodeHighlight } from './CodeHighlight'
import { assistantTurnEnds, chatAbsoluteTime, chatClockTime, dayDividers } from '../lib/chatThread'
import { groupToolCalls, partPosition } from '../lib/chatToolGroups'
-import { thinkingDuration, thinkingLabel } from '../lib/chatThinking'
+import { thinkingLabel } from '../lib/chatThinking'
import { ChatToolGroup } from './ChatToolGroup'
import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSession'
import { chatPageDirection, pageChatThread } from '../lib/chatPageKeys'
@@ -1000,10 +1000,10 @@ export function ChatPanel({
) : p.kind === 'thinking' ? (
// Claude's thinking summary — the "thinking out loud" line its TUI prints between tool calls.
// A fold, closed by default and dimmed, so it never reads as the answer; its line says how long
- // the thinking took when the stamps can tell (lib/chatThinking.ts). Native and uncontrolled,
- // like the tool block: it keeps whatever the user opened while the thread re-renders.
+ // the thinking took when the parser could stamp it (`p.ms`). Native and uncontrolled, like the
+ // tool block: it keeps whatever the user opened while the thread re-renders.
<details key={key} className="term-chat__thinking">
- <summary>{thinkingLabel(thinkingDuration(messages, i))}</summary>
+ <summary>{thinkingLabel(p.ms)}</summary>
<MarkdownText text={p.text} />
</details>
) : p.body ? (
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 2b6d31365..29e2bc828 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -3584,7 +3584,22 @@ export interface TranscriptLine {
* metadata so committed tool cards keep the same summary/diff-click treatment as live ones. */
export type ChatPart =
| { kind: 'text'; text: string }
- | { kind: 'thinking'; text: string }
+ | {
+ kind: 'thinking'
+ text: string
+ /**
+ * How long the model thought, in ms — this record's timestamp minus that of the newest `user`
+ * record before it (the prompt, tool_result or meta line the request answered). Present only on
+ * the opt-in `thinking` read, only when both stamps exist and the gap is ≥ 0. Measured 2026-11-02
+ * on CLI 2.1.275–2.1.316: a thinking record is written when the thinking ENDS, and the record
+ * after it is a tool call whose write time scales with its input, so the gap to the NEXT record
+ * is not thinking time; nor is the gap to the record right BEFORE it, which is an empty
+ * encrypted thinking record of the same message written ~10 ms earlier (1,018 of 1,037).
+ * A paged read sees only its own window, so a thinking record with no `user` record before it
+ * in that window (the start of an older page) carries no `ms`.
+ */
+ ms?: number
+ }
| {
kind: 'tool'
name: string