Files
apes-sidebar/tests/sidechat-transcript.spec.ts
T
Menghuan1918 5330eab474 feat(sidechat): 实时推送 + 排队可见 + per-thread 模型选择 + 底栏重构
侧边对话的四处用户痛点,加上「实时 fork」与「隐藏会话」两条路线的可行性结论。
全部结论都有真机复现取证(在运行中的宿主上建线程 + 读真实 session 日志)。

- 排队信息漏入:create 的 `inbox.clear()` 围栏确实生效(真机复现:子会话
  request 只有 [boundary, 问题]);但幽灵来源比文档更宽——父会话 mid-turn 且
  工具未返回时,种子被截断在 `turn/start` 之前,而 inbox 的「领取」splice 发生
  在其后,于是**父会话本轮已领取的输入**在种子折叠里仍是 pending;而冷恢复
  路径完全没有围栏。修法:create 保留硬围栏(本线程自己不可能有排队输入),
  resume 改为 `inheritedPendingIds` 只折继承前缀得到幽灵 id → `inbox.remove(id)`
  精确清扫,绝不误杀用户自己排的队。
- 消息不及时:新增 `/sidebar/ws/sidechat` 推送(`session/event` 60ms、
  `agent/assistant-stream` 250ms 去抖,**纯失效帧**,客户端带 afterSeq 重拉),
  2s 轮询降级为 15s 兜底,断线自愈。
- 模型选不了:宿主对 `origin:'subagent'` 会话**显式禁用**自带选择器,
  `sessionController.selectModel` 又被 subagent fence 挡;插件因此自建
  `sidechat.models`(直通宿主模型目录)与 `sidechat.model`(append
  `model/selection` + `installModelSelection`),并让 `sidechat.info` 报**有效**
  选择而不是冻结的创建期 options。
- 排队可见 / 回显 / spinner / 错误行:`sidechat.events` 增返 `pending`(claim
  顺序)、`sidechat.dequeue` 按 id 撤销或清空、发送即本地回显、立即 thinking
  行、`turn/end{error}` 与失败 attempt 渲染成可见错误行;另修掉「首问未 claim
  时连发第二条会注入第二对 boundary+question」(新增 `boundaryPending`)。
- 底栏重构(用户反馈「注意力全在底栏,看不到上栏的保存为新会话」):顶栏整条
  删除,`[+新建][线程][保存][归档] … [模型选择器][发送/停止]` 与主会话底栏对齐
  (图标靠左、选择器靠右完整显示,agent 徽标不再显示);推理强度改为**平铺行**
  ——宿主 `Menu` 的 submenu 只能开在父项右侧(无翻转开关)且会让整个面板失去
  滚动,钉在侧栏右缘必然被裁;每个控件加宿主 `Tooltip` 悬停气泡(锚在启用的
  span 上,禁用态才解释得了「为什么不能点」),替代原生 title。

设计文档:docs/plans/2026-10-12-sidechat-native-surface.md(含取证、判定、
实施偏差与未验证项);AGENTS §3.4 第 4/10 条同步。

门禁:`tsc --noEmit` / `eslint .` / `vitest run`(2268 passed / 17 skipped)全绿;
宿主半 build + pack 后真实挂载进 sidechat-test profile 并验证新路由与 WS 通道。
2026-10-12 00:56:34 +08:00

590 lines
25 KiB
TypeScript

/**
* Unit tests for the Side Chat transcript mapping (src/client/sidechat-
* transcript.ts): the seed cut at session/end-seed, context-injection rows
* (plugin-stamped sources and the legacy boundary-prefix blob), chunk
* streaming accumulation superseded by assembled messages, tool call/result
* pairing, and orphan failed results.
*/
import { describe, expect, it } from 'vitest'
import { createToolResultMessage, ToolCallId } from '@deepseek-ai/dsh-llm'
import type { SidebarHistoryEntry, SidebarSessionEvent } from '../src/context-types.ts'
import { SIDE_BOUNDARY_PREFIX, SIDE_BOUNDARY_PROMPT, SIDE_INJECTION_SOURCE_KIND } from '../src/sidechat-core.ts'
import {
formatDurationMs,
formatTokens,
toolArgsSummary,
transcriptRows,
type SidechatTranscriptRow,
} from '../src/client/sidechat-transcript.ts'
/** One history entry (event + optional view). */
function entry(event: SidebarSessionEvent): SidebarHistoryEntry {
return { event }
}
/** One log event fixture. Surface-eligible events carry their required
* `surfaceOp: 'append'` marker, exactly like the live pipeline appends them. */
function ev(type: string, seq: number, data: Record<string, unknown> = {}): SidebarSessionEvent {
const event: SidebarSessionEvent = { type, seq, time: seq * 1000, data }
if (type === 'user/message' || type === 'assistant/message' || type === 'tool/result') {
return { ...event, surfaceOp: 'append' } as SidebarSessionEvent
}
return event
}
function textBlocks(...texts: string[]): unknown[] {
return texts.map(text => ({ type: 'text', text }))
}
/** One 0.1.6-era tool/result message (user role, nested `tool-result` wrapper). */
function legacyResultMessage(callId: string, text: string, isError = false): Record<string, unknown> {
return {
role: 'user',
source: { kind: 'tool', callId },
content: [{ type: 'tool-result', toolCallId: callId, isError, content: textBlocks(text) }],
}
}
/** One 0.1.7 tool/result message (tool role, blocks + `isError` on the message). */
function toolRoleResultMessage(callId: string, text: string, isError = false): Record<string, unknown> {
return {
role: 'tool',
source: { kind: 'tool', callId },
toolCallId: callId,
content: textBlocks(text),
isError,
}
}
describe('transcriptRows', () => {
it('cuts the inherited seed at the last end-seed and renders the boundary as an injection row', () => {
const entries = [
entry(ev('user/message', 0, { content: textBlocks('inherited'), source: { kind: 'user' } })),
entry(ev('session/end-seed', 1)),
entry(ev('user/message', 2, { content: textBlocks(`${SIDE_BOUNDARY_PREFIX}\n\nmode`), source: { kind: SIDE_INJECTION_SOURCE_KIND } })),
entry(ev('user/message', 3, { content: textBlocks('the side question'), source: { kind: 'user' } })),
]
const rows = transcriptRows(entries)
expect(rows).toEqual([
{ kind: 'injection', seq: 2, text: `${SIDE_BOUNDARY_PREFIX}\n\nmode` },
{ kind: 'user', seq: 3, text: 'the side question' },
])
})
it('splits the LEGACY wrapped first message (boundary + question in one user row) at the boundary prompt', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, {
content: textBlocks(`${SIDE_BOUNDARY_PROMPT}\n\nthe first question`),
source: { kind: 'user' },
})),
entry(ev('user/message', 2, { content: textBlocks('follow-up'), source: { kind: 'user' } })),
]
const rows = transcriptRows(entries)
expect(rows).toEqual([
{ kind: 'injection', seq: 1, text: SIDE_BOUNDARY_PROMPT },
{ kind: 'user', seq: 1, text: 'the first question' },
{ kind: 'user', seq: 2, text: 'follow-up' },
])
})
it('renders any plugin-sourced context message as an injection row, boundary prefix or not', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { content: textBlocks('runtime context'), source: { kind: 'plugin:other-plugin' } })),
entry(ev('user/message', 2, { content: textBlocks('q'), source: { kind: 'user' } })),
]
const rows = transcriptRows(entries)
expect(rows).toEqual([
{ kind: 'injection', seq: 1, text: 'runtime context' },
{ kind: 'user', seq: 2, text: 'q' },
])
})
it('accumulates live deltas per block and supersedes them on settle', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { content: textBlocks('q'), source: { kind: 'user' } })),
entry(ev('turn/start', 2, { turn: 1 })),
entry(ev('step/start', 3, { turn: 1, step: 1 })),
entry(ev('assistant/live-chunk', 4, { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'Hel' } })),
entry(ev('assistant/live-chunk', 5, { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'lo' } })),
entry(ev('assistant/live-chunk', 6, { turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 1, text: 'think' } })),
]
const rows = transcriptRows(entries)
const assistant = rows.find(row => row.kind === 'assistant') as Extract<SidechatTranscriptRow, { kind: 'assistant' }>
expect(assistant.text).toBe('Hello')
expect(assistant.settled).toBe(false)
const reasoning = rows.find(row => row.kind === 'reasoning') as Extract<SidechatTranscriptRow, { kind: 'reasoning' }>
expect(reasoning.text).toBe('think')
})
it('replaces streaming rows with the settled assistant message', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { content: textBlocks('q'), source: { kind: 'user' } })),
entry(ev('turn/start', 2, { turn: 1 })),
entry(ev('step/start', 3, { turn: 1, step: 1 })),
entry(ev('assistant/live-chunk', 4, { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'par' } })),
entry(ev('assistant/message', 5, { turn: 1, step: 1, message: { content: textBlocks('final answer') } })),
]
const rows = transcriptRows(entries)
const assistants = rows.filter(row => row.kind === 'assistant')
expect(assistants).toHaveLength(1)
expect(assistants[0]).toMatchObject({ kind: 'assistant', text: 'final answer', settled: true })
})
it('pairs tool calls with results and marks failures', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('step/start', 2, { turn: 1, step: 1 })),
entry(ev('tool/call', 3, { turn: 1, step: 1, callId: 'c1', name: 'read', arguments: '{"path":"a"}' })),
// The shape 0.1.7 writes: tool role, result blocks and `isError` at the
// message's own top level (no `tool-result` wrapper).
entry(ev('tool/result', 4, {
turn: 1,
step: 1,
message: toolRoleResultMessage('c1', 'denied', true),
error: { name: 'EACCES', code: 'EACCES' },
})),
]
const rows = transcriptRows(entries)
expect(rows).toHaveLength(1)
const tool = rows[0]
expect(tool).toMatchObject({
kind: 'tool',
name: 'read',
args: '{"path":"a"}',
resultText: 'denied',
failed: true,
executing: false,
})
})
it('reads the tool/result message dsh-llm actually produces (producer round-trip)', () => {
const message = createToolResultMessage({
callId: ToolCallId('c1'),
// A literal block array: the producer takes real ContentBlocks, not the
// loose `unknown[]` the log fixtures above are written with.
content: [{ type: 'text', text: 'produced output' }],
isError: false,
})
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('tool/call', 1, { callId: 'c1', name: 'bash', arguments: '{"command":"ls"}' })),
entry(ev('tool/result', 2, { message: message as unknown as Record<string, unknown> })),
]
const rows = transcriptRows(entries)
expect(rows).toHaveLength(1)
expect(rows[0]).toMatchObject({ kind: 'tool', name: 'bash', resultText: 'produced output', executing: false })
})
it('reads a LEGACY 0.1.6-era tool result wrapper (historical logs keep that shape)', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('step/start', 2, { turn: 1, step: 1 })),
entry(ev('tool/call', 3, { turn: 1, step: 1, callId: 'c1', name: 'read', arguments: '{"path":"a"}' })),
entry(ev('tool/result', 4, {
turn: 1,
step: 1,
message: legacyResultMessage('c1', 'legacy denied', true),
error: { name: 'EACCES', code: 'EACCES' },
})),
]
const rows = transcriptRows(entries)
expect(rows).toHaveLength(1)
expect(rows[0]).toMatchObject({ kind: 'tool', name: 'read', resultText: 'legacy denied', failed: true })
})
it('keeps a call executing until its result lands and surfaces orphan failures', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('step/start', 2, { turn: 1, step: 1 })),
entry(ev('tool/call', 3, { turn: 1, step: 1, callId: 'c1', name: 'bash', arguments: '{}' })),
]
let rows = transcriptRows(entries)
expect(rows[0]).toMatchObject({ kind: 'tool', executing: true })
// Orphan failed result outside the fetched window still surfaces.
const orphan = [
entry(ev('session/end-seed', 0)),
entry(ev('tool/result', 1, {
turn: 1,
step: 1,
message: toolRoleResultMessage('gone', 'boom', true),
error: { name: 'X', code: 'X' },
})),
]
rows = transcriptRows(orphan)
expect(rows[0]).toMatchObject({ kind: 'tool', failed: true, resultText: 'boom' })
})
})
describe('failure rows', () => {
it('renders a turn/end error through the reason message', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('turn/end', 2, { turn: 1, reason: { kind: 'error', error: { message: 'provider exploded', code: 'X' } } })),
]
const rows = transcriptRows(entries)
// The visible failure comes first, the turn's duration tail after it.
expect(rows[0]).toEqual({ kind: 'error', seq: 2, text: 'provider exploded' })
expect(rows[1]).toMatchObject({ kind: 'turnSummary', seq: 2 })
})
it('falls back to a string rendering when the reason carries no message', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/end', 1, { turn: 1, reason: { kind: 'error' } })),
]
// Never blank, never a thrown mapping.
expect(transcriptRows(entries)[0]).toEqual({ kind: 'error', seq: 1, text: '[object Object]' })
})
it('renders a failed assistant/attempt from its terminal finish chunk', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('assistant/attempt', 2, {
turn: 1,
step: 1,
stream: [
{ type: 'text-chunks', time0: 0, index: 0, dt: [], texts: ['partial'] },
// The adapter-failure shape dsh-llm's `adapterFailureChunk` writes.
{ type: 'chunk', time: 1, chunk: { type: 'finish', reason: { kind: 'error', failure: { message: 'quota exceeded', code: 'QUOTA' } } } },
],
})),
]
expect(transcriptRows(entries)[0]).toEqual({ kind: 'error', seq: 2, text: 'quota exceeded' })
})
it('renders ONE error row when the failed attempt is followed by its turn/end', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('assistant/attempt', 2, {
turn: 1,
step: 1,
stream: [{ type: 'chunk', time: 1, chunk: { type: 'finish', reason: { kind: 'error', failure: { message: 'quota exceeded', code: 'QUOTA' } } } }],
})),
// The agent loop repeats the same failure as the turn's own reason: the
// attempt's row already covers it.
entry(ev('turn/end', 3, { turn: 1, reason: { kind: 'error', error: { message: 'quota exceeded', code: 'QUOTA' } } })),
]
const errors = transcriptRows(entries).filter(row => row.kind === 'error')
expect(errors).toEqual([{ kind: 'error', seq: 2, text: 'quota exceeded' }])
})
it('renders nothing for an attempt that finished without an error', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('assistant/attempt', 1, {
turn: 1,
step: 1,
stream: [{ type: 'chunk', time: 1, chunk: { type: 'finish', reason: { kind: 'stop' } } }],
})),
]
expect(transcriptRows(entries)).toEqual([])
})
it('keeps an error row\'s identity across pulls (reuse pass)', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/end', 1, { turn: 1, reason: { kind: 'error', error: { message: 'boom' } } })),
]
const first = transcriptRows(entries)
const second = transcriptRows(entries, first)
expect(second[0]).toBe(first[0])
})
})
describe('user row identity', () => {
it('carries the durable message id and leaves older logs without one', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { id: 'msg-1', content: textBlocks('the question'), source: { kind: 'user' } })),
entry(ev('user/message', 2, { content: textBlocks('a legacy row'), source: { kind: 'user' } })),
]
expect(transcriptRows(entries)).toEqual([
{ kind: 'user', seq: 1, text: 'the question', messageId: 'msg-1' },
{ kind: 'user', seq: 2, text: 'a legacy row' },
])
})
})
describe('turnSummary rows', () => {
it('emits one tail row per turn: envelope-time duration + last-input/summed-output usage', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('assistant/message', 2, { turn: 1, step: 1, message: { content: textBlocks('a') }, usage: { inputTokens: 100, outputTokens: 40 } })),
entry(ev('assistant/message', 3, { turn: 1, step: 2, message: { content: textBlocks('b') }, usage: { inputTokens: 160, outputTokens: 30 } })),
entry(ev('turn/end', 4, { turn: 1, reason: 'completed' })),
]
const rows = transcriptRows(entries)
expect(rows.at(-1)).toEqual({ kind: 'turnSummary', seq: 4, inputTokens: 160, outputTokens: 70, durationMs: 3000 })
})
it('keeps a duration-only tail without usage and a usage-only tail without a turn/start', () => {
const cancelled = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 2, { turn: 1 })),
entry(ev('turn/end', 7, { turn: 1, reason: 'cancelled' })),
]
expect(transcriptRows(cancelled).at(-1)).toEqual({ kind: 'turnSummary', seq: 7, durationMs: 5000 })
const seedCutStart = [
entry(ev('session/end-seed', 0)),
entry(ev('assistant/message', 2, { turn: 1, step: 1, message: { content: textBlocks('a') }, usage: { inputTokens: 10, outputTokens: 5 } })),
entry(ev('turn/end', 3, { turn: 1, reason: 'completed' })),
]
expect(transcriptRows(seedCutStart).at(-1)).toEqual({ kind: 'turnSummary', seq: 3, inputTokens: 10, outputTokens: 5 })
})
it('skips the tail entirely when nothing is computable', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/end', 1, { turn: 1, reason: 'completed' })),
]
expect(transcriptRows(entries)).toEqual([])
})
})
describe('tool cards', () => {
const callRow = (seq: number, name: string, args: string): SidebarHistoryEntry =>
entry(ev('tool/call', seq, { turn: 1, step: 1, callId: `c${seq}`, name, arguments: args }))
const resultRow = (seq: number, callId: string, text: string, extra: Record<string, unknown> = {}): SidebarHistoryEntry =>
entry(ev('tool/result', seq, {
turn: 1,
step: 1,
// The 0.1.7 first-class tool-role message shape.
message: toolRoleResultMessage(callId, text),
...extra,
}))
const toolRow = (entries: readonly SidebarHistoryEntry[]) => {
const rows = transcriptRows(entries)
expect(rows).toHaveLength(1)
return rows[0] as Extract<SidechatTranscriptRow, { kind: 'tool' }>
}
it('derives the call-time terminal card for bash and refines output/exit from the result marker', () => {
const row = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"echo hi","workdir":"/w"}'),
resultRow(2, 'c1', 'hi\n[exit code: 3]'),
])
expect(row.card).toEqual({ type: 'terminal', command: 'echo hi', cwd: '/w', output: 'hi', exitCode: 3 })
})
it('recovers the signal pill and defaults a marker-less settle to exit code 0', () => {
const signaled = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x"}'),
resultRow(2, 'c1', 'boom\n[killed by signal: SIGKILL]'),
])
expect(signaled.card).toEqual({ type: 'terminal', command: 'x', output: 'boom', signal: 'SIGKILL' })
const clean = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x"}'),
resultRow(2, 'c1', 'ok'),
])
expect(clean.card).toEqual({ type: 'terminal', command: 'x', output: 'ok', exitCode: 0 })
})
it('skips the terminal card for background bash and drops it on failed results', () => {
const background = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x","run_in_background":true}'),
])
expect(background.card).toBeUndefined()
const failed = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x"}'),
resultRow(2, 'c1', 'denied', { error: { name: 'EACCES', code: 'EACCES' } }),
])
expect(failed.card).toBeUndefined()
})
it('derives literal diff cards for edit/write calls and refines from the result meta hunks', () => {
const edit = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'edit', '{"file_path":"/a.ts","old_string":"x","new_string":"y"}'),
])
expect(edit.card).toEqual({ type: 'diff', diffs: [{ path: '/a.ts', oldText: 'x', newText: 'y' }] })
const write = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'write', '{"file_path":"/new.ts","content":"body"}'),
])
expect(write.card).toEqual({ type: 'diff', diffs: [{ path: '/new.ts', oldText: null, newText: 'body' }] })
const refined = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'edit', '{"file_path":"/a.ts","old_string":"x","new_string":"y"}'),
resultRow(2, 'c1', 'ok', { meta: { diffs: [{ path: '/a.ts', oldText: 'x\nctx', newText: 'y\nctx' }] } }),
])
expect(refined.card).toEqual({ type: 'diff', diffs: [{ path: '/a.ts', oldText: 'x\nctx', newText: 'y\nctx' }] })
const malformed = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'edit', '{"file_path":"/a.ts","old_string":"x","new_string":"y"}'),
resultRow(2, 'c1', 'ok', { meta: { diffs: [{ path: 7, oldText: 'x', newText: 'y' }] } }),
])
// Malformed meta declines to the call-time literal card, never throws.
expect(malformed.card).toEqual({ type: 'diff', diffs: [{ path: '/a.ts', oldText: 'x', newText: 'y' }] })
})
it('builds the read card from the result line-window meta and declines malformed windows', () => {
const read = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'read', '{"path":"/a.ts","offset":2,"limit":2}'),
resultRow(2, 'c1', 'window text', {
meta: { path: '/a.ts', offset: 2, lines: [{ number: 2, text: 'b' }, { number: 3, text: 'c' }], totalLines: 5, lang: 'ts' },
}),
])
expect(read.card).toEqual({
type: 'read',
label: '/a.ts',
lines: [{ number: 2, text: 'b' }, { number: 3, text: 'c' }],
totalLines: 5,
lang: 'ts',
})
const nonMonotonic = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'read', '{"path":"/a.ts"}'),
resultRow(2, 'c1', 'window text', {
meta: { path: '/a.ts', offset: 1, lines: [{ number: 3, text: 'c' }, { number: 2, text: 'b' }], totalLines: 5 },
}),
])
expect(nonMonotonic.card).toBeUndefined()
})
it('leaves unknown tools on the generic row', () => {
const row = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'todo_write', '{"todos":[]}'),
])
expect(row.card).toBeUndefined()
})
})
describe('usage formatting', () => {
it('formatTokens mirrors the main conversation K/M compaction', () => {
expect(formatTokens(517)).toBe('517')
expect(formatTokens(999)).toBe('999')
expect(formatTokens(1_234)).toBe('1.2K')
expect(formatTokens(12_234)).toBe('12.2K')
expect(formatTokens(122_345)).toBe('122K')
expect(formatTokens(1_234_567)).toBe('1.2M')
})
it('formatDurationMs mirrors the main conversation s / m+s cadence', () => {
expect(formatDurationMs(0)).toBe('0s')
expect(formatDurationMs(500)).toBe('0.5s')
expect(formatDurationMs(45_200)).toBe('45.2s')
expect(formatDurationMs(61_000)).toBe('1m1s')
expect(formatDurationMs(162_000)).toBe('2m42s')
})
})
describe('toolArgsSummary', () => {
it('picks the most identifying string field', () => {
expect(toolArgsSummary('{"command":"ls -la","timeout":1000}')).toBe('ls -la')
expect(toolArgsSummary('{"file_path":"/a/b.ts","old_string":"x"}')).toBe('/a/b.ts')
expect(toolArgsSummary('{"pattern":"foo","path":"/repo"}')).toBe('/repo')
})
it('flattens and truncates raw text when no known key parses', () => {
expect(toolArgsSummary('{"custom":"v"}')).toBe('{"custom":"v"}')
expect(toolArgsSummary('not json at all')).toBe('not json at all')
expect(toolArgsSummary(`{"command":"${'x'.repeat(200)}"`)).toHaveLength(80)
expect(toolArgsSummary(`{"command":"${'x'.repeat(200)}"`)).toMatch(/…$/)
})
it('reads empty for missing or blank input', () => {
expect(toolArgsSummary(undefined)).toBe('')
expect(toolArgsSummary('{"command":" "}')).toBe('{"command":" "}')
})
})
describe('transcriptRows row reuse (the poll-to-poll identity pass)', () => {
it('re-adopts the previous poll\'s row objects wherever content is unchanged', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { content: textBlocks('the side question'), source: { kind: 'user' } })),
entry(ev('assistant/message', 2, { message: { content: textBlocks('the answer') } })),
]
const first = transcriptRows(entries)
const second = transcriptRows(entries, first)
expect(second).toEqual(first)
// Settled rows keep their object identity (fresh references defeat the
// downstream memo and re-render the whole transcript every 2s poll).
expect(second[1]).toBe(first[1])
expect(second[2]).toBe(first[2])
})
it('rebuilds changed rows and everything past the change', () => {
const before = transcriptRows([
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { content: textBlocks('q'), source: { kind: 'user' } })),
])
const after = transcriptRows([
entry(ev('session/end-seed', 0)),
entry(ev('user/message', 1, { content: textBlocks('q'), source: { kind: 'user' } })),
entry(ev('user/message', 2, { content: textBlocks('q2'), source: { kind: 'user' } })),
], before)
expect(after).toHaveLength(2)
expect(after[0]).toBe(before[0])
expect(after[1]).not.toBe(before[1])
expect(after[1]).toMatchObject({ kind: 'user', seq: 2, text: 'q2' })
})
it('never re-adopts a row whose rendered fields changed (tool result lands)', () => {
const call = entry(ev('tool/call', 1, { callId: 'c1', name: 'bash', arguments: '{"command":"ls"}' }))
const before = transcriptRows([entry(ev('session/end-seed', 0)), call])
expect(before[0]).toMatchObject({ kind: 'tool', executing: true })
const result = entry(ev('tool/result', 2, {
message: { source: { callId: 'c1' }, content: [{ type: 'tool-result', content: [{ type: 'text', text: 'out' }] }] },
}))
const after = transcriptRows([entry(ev('session/end-seed', 0)), call, result], before)
expect(after[0]).not.toBe(before[0])
expect(after[0]).toMatchObject({ kind: 'tool', executing: false, resultText: 'out' })
})
})
describe('transcriptRows row reuse (newer row kinds)', () => {
it('re-adopts settled turnSummary rows (token usage tail)', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('turn/end', 2, { turn: 1, reason: 'completed' })),
]
const first = transcriptRows(entries)
const summary = first.find(row => row.kind === 'turnSummary')
expect(summary).toBeDefined()
const second = transcriptRows(entries, first)
expect(second[second.length - 1]).toBe(summary)
})
it('re-adopts a tool row whose card landed (executing flip forces the rebuild)', () => {
const call = entry(ev('tool/call', 1, { callId: 'c1', name: 'bash', arguments: '{"command":"ls"}' }))
const before = transcriptRows([entry(ev('session/end-seed', 0)), call])
expect(before[0]).toMatchObject({ kind: 'tool', executing: true })
const result = entry(ev('tool/result', 2, {
message: { source: { callId: 'c1' }, content: [{ type: 'tool-result', content: [{ type: 'text', text: 'out\n[exit 0]' }] }] },
}))
const after = transcriptRows([entry(ev('session/end-seed', 0)), call, result], before)
expect(after[0]).not.toBe(before[0])
expect(after[0]).toMatchObject({ kind: 'tool', executing: false })
})
})