chat-stats-bash-sample.spec.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // @vitest-environment jsdom
  2. // StatsLine (composer.dock entry): totals derivation + the RFC
  3. // hard acceptance — zero renders during streaming. Bash sample row: the
  4. // canonical sub-agent differential decided INSIDE the component off the
  5. // standard useSessions kit (no registry predicates — tool ring dissolved).
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { act, cleanup, render } from '@testing-library/react'
  8. import type {
  9. AssistantMessageNode, ConversationSnapshot, SessionId, SessionListState, ToolResultNode,
  10. } from '@deepseek-ai/dsh-client-runtime/client'
  11. import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
  12. import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
  13. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  14. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  15. import { StatsLine, deriveStats, formatDuration, formatTokens, type StatsLineProps } from '../src/client/chat/StatsLine.tsx'
  16. import { BashRow } from '../src/client/toolviews/bash-sample.tsx'
  17. import { zh } from '../src/client/locales.ts'
  18. type BashRowProps = Parameters<typeof BashRow>[0]
  19. // Mirrors the real lookup chain (conversation namespace, then common).
  20. const t: BashRowProps['t'] = makeTranslate(zh, commonZh)
  21. afterEach(cleanup)
  22. const SID = 's1' as SessionId
  23. const assistant = (seq: number, turn: number, usage?: unknown): AssistantMessageNode => ({
  24. kind: 'assistant', seq, time: seq * 1_000, turn, step: seq, blocks: [{ kind: 'text', text: `t${seq}` }],
  25. ...(usage === undefined ? {} : { usage }),
  26. })
  27. function snapshotBase(): ConversationSnapshot {
  28. return {
  29. sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
  30. pending: [], queue: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
  31. hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null,
  32. }
  33. }
  34. function makeSource(init?: Partial<ConversationSnapshot>) {
  35. let snap: ConversationSnapshot = { ...snapshotBase(), ...init }
  36. const subs = new Set<() => void>()
  37. return {
  38. set: (next: Partial<ConversationSnapshot>) => {
  39. snap = { ...snap, ...next }
  40. for (const fn of [...subs]) fn()
  41. },
  42. source: {
  43. getSnapshot: () => snap,
  44. subscribe: (fn: () => void) => {
  45. subs.add(fn)
  46. return () => subs.delete(fn)
  47. },
  48. },
  49. }
  50. }
  51. describe('deriveStats', () => {
  52. it('folds turns/steps/token split and cache hit percentage', () => {
  53. const stats = deriveStats([
  54. assistant(1, 1, { inputTokens: 100, outputTokens: 50, cacheReadTokens: 900 }),
  55. assistant(2, 1, { inputTokens: 100, outputTokens: 50 }),
  56. assistant(3, 2),
  57. ])
  58. expect(stats.turns).toBe(2)
  59. expect(stats.steps).toBe(3)
  60. expect(stats.inputTokens).toBe(1100)
  61. expect(stats.outputTokens).toBe(100)
  62. expect(stats.cacheHitPct).toBe(82)
  63. })
  64. it('cache hit stays null with no cache accounting; out-of-window tool results ignored', () => {
  65. const tool: ToolResultNode = {
  66. kind: 'tool-result', seq: 5, time: 5_000, callId: 'c', call: null, callTime: null, content: [],
  67. isError: false, callView: null, resultView: null,
  68. }
  69. const stats = deriveStats([tool, assistant(1, 1)])
  70. expect(stats.steps).toBe(1)
  71. expect(stats.toolMs).toBe(0)
  72. expect(stats.cacheHitPct).toBeNull()
  73. })
  74. it('sums LLM wall time from assistant timing and tool wall time from call/result pairs', () => {
  75. const timed: AssistantMessageNode = {
  76. ...assistant(1, 1),
  77. timing: { stepStartTime: 1_000, firstTokenTime: 1_200, completedTime: 3_500 },
  78. }
  79. const untimed: AssistantMessageNode = {
  80. ...assistant(2, 1),
  81. timing: { stepStartTime: null, firstTokenTime: null, completedTime: 9_000 },
  82. }
  83. const tool: ToolResultNode = {
  84. kind: 'tool-result', seq: 5, time: 7_000, callId: 'c', call: null, callTime: 4_000, content: [],
  85. isError: false, callView: null, resultView: null,
  86. }
  87. const stats = deriveStats([timed, untimed, tool])
  88. expect(stats.llmMs).toBe(2_500)
  89. expect(stats.toolMs).toBe(3_000)
  90. })
  91. })
  92. describe('formatters', () => {
  93. it('formats token counts compactly', () => {
  94. expect(formatTokens(517)).toBe('517')
  95. expect(formatTokens(12_240)).toBe('12.2K')
  96. expect(formatTokens(517_000)).toBe('517K')
  97. expect(formatTokens(1_230_000)).toBe('1.2M')
  98. })
  99. it('formats durations under and over a minute', () => {
  100. expect(formatDuration(45_230)).toBe('45.2s')
  101. expect(formatDuration(162_000)).toBe('2m42s')
  102. })
  103. })
  104. describe('StatsLine', () => {
  105. function props(source: { getSnapshot(): ConversationSnapshot; subscribe(fn: () => void): () => void }): StatsLineProps {
  106. return { useSession: bindSnapshotSelector(source) }
  107. }
  108. it('renders the grouped stats row and hides with zero steps', () => {
  109. const { source } = makeSource({
  110. nodes: [assistant(1, 1, { inputTokens: 10, outputTokens: 5, cacheReadTokens: 90 })],
  111. })
  112. const view = render(<StatsLine {...props(source)} />)
  113. // No timing on the fixture: the duration group drops out whole.
  114. expect(view.container.textContent).toBe('1 turns · 1 steps|Cache hit 90%|Input 100 tok · Output 5 tok')
  115. const empty = makeSource()
  116. const emptyView = render(<StatsLine {...props(empty.source)} />)
  117. expect(emptyView.container.textContent).toBe('')
  118. })
  119. it('renders ZERO times during streaming chunk frames (RFC hard acceptance)', () => {
  120. const { set, source } = makeSource({ nodes: [assistant(1, 1)] })
  121. let renders = 0
  122. function Counting(p: StatsLineProps) {
  123. renders += 1
  124. return <StatsLine {...p} />
  125. }
  126. render(<Counting {...props(source)} />)
  127. const before = renders
  128. // Chunk frames swap partial only; nodes keeps its reference (object-layer contract).
  129. act(() => { set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'a' }] } }) })
  130. act(() => { set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'ab' }] } }) })
  131. act(() => { set({ running: true }) })
  132. expect(renders).toBe(before)
  133. })
  134. })
  135. describe('bash sample row', () => {
  136. const ROOT = 'root-1' as SessionId
  137. const CHILD = 'child-1' as SessionId
  138. const result = (callId: string): ToolResultNode => ({
  139. kind: 'tool-result', seq: 3, time: 3_000, callId,
  140. call: { name: 'bash', argsRaw: '{"command":"make build","description":"Build"}' },
  141. callTime: 2_000,
  142. content: [], isError: false, callView: null, resultView: null,
  143. })
  144. /** Real list-store engine: the family fixture the in-component parentId branch reads. */
  145. function listStore() {
  146. return createSnapshotStore<SessionListState>({
  147. ids: [ROOT, CHILD],
  148. byId: {
  149. [ROOT]: { id: ROOT, title: 'r', displayTitle: 'r', running: false, waitingApproval: false, blank: false, updatedAt: 0 },
  150. [CHILD]: { id: CHILD, title: 'c', displayTitle: 'c', parentId: ROOT, running: false, waitingApproval: false, blank: false, updatedAt: 0 },
  151. },
  152. current: undefined,
  153. phase: 'ready',
  154. })
  155. }
  156. const rowProps = (sessionId: SessionId, over?: {
  157. store?: ReturnType<typeof listStore>
  158. }): BashRowProps => ({
  159. callId: 'c1', toolName: 'bash', block: result('c1'),
  160. openFile: vi.fn(),
  161. sessionId,
  162. useSessions: bindSnapshotSelector(over?.store ?? listStore()),
  163. t,
  164. } as unknown as BashRowProps)
  165. it('differential rendering: the scoped variant in sub-sessions, global at roots', () => {
  166. const scoped = render(<BashRow {...rowProps(CHILD)} />)
  167. expect(scoped.container.querySelector('[data-sample="bash-scoped"]')).not.toBeNull()
  168. expect(scoped.getByText('scoped')).toBeTruthy()
  169. const plain = render(<BashRow {...rowProps(ROOT)} />)
  170. expect(plain.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  171. })
  172. it('a session outside the list renders the global arm (no parent known)', () => {
  173. const view = render(<BashRow {...rowProps('gone' as SessionId)} />)
  174. expect(view.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  175. })
  176. it('a live parentId write flips the row to the scoped variant (store subscription)', () => {
  177. const store = listStore()
  178. const orphan = 'late-child' as SessionId
  179. store.update((d) => {
  180. d.ids.push(orphan)
  181. d.byId[orphan] = { id: orphan, title: 'l', displayTitle: 'l', running: false, waitingApproval: false, blank: false, updatedAt: 0 }
  182. })
  183. const view = render(<BashRow {...rowProps(orphan, { store })} />)
  184. expect(view.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  185. act(() => {
  186. store.update((d) => { d.byId[orphan]!.parentId = ROOT })
  187. })
  188. expect(view.container.querySelector('[data-sample="bash-scoped"]')).not.toBeNull()
  189. })
  190. it('summarizes as Bash · description on both arms without row click targets', () => {
  191. const global = render(<BashRow {...rowProps(ROOT)} />)
  192. // Two renders share document.body: query inside each container.
  193. const globalRow = global.container.querySelector('[data-sample="bash-global"]')!
  194. expect(globalRow.textContent).toContain('Bash')
  195. expect(globalRow.textContent).toContain('Build')
  196. expect(globalRow.getAttribute('data-clickable')).toBeNull()
  197. const scoped = render(<BashRow {...rowProps(CHILD)} />)
  198. const scopedRow = scoped.container.querySelector('[data-sample="bash-scoped"]')!
  199. expect(scopedRow.textContent).toContain('Bash')
  200. expect(scopedRow.textContent).toContain('Build')
  201. expect(scopedRow.getAttribute('data-clickable')).toBeNull()
  202. })
  203. })