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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // @vitest-environment jsdom
  2. // StatsLine (rendered inside the chat view body): 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, fireEvent, 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 type { ToolRowProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
  14. import { StatsLine, deriveStats, type StatsLineProps } from '../src/client/chat/StatsLine.tsx'
  15. import { BashRow } from '../src/client/toolviews/bash-sample.tsx'
  16. afterEach(cleanup)
  17. const SID = 's1' as SessionId
  18. const assistant = (seq: number, turn: number, usage?: unknown): AssistantMessageNode => ({
  19. kind: 'assistant', seq, time: seq * 1_000, turn, step: seq, blocks: [{ kind: 'text', text: `t${seq}` }],
  20. ...(usage === undefined ? {} : { usage }),
  21. })
  22. function snapshotBase(): ConversationSnapshot {
  23. return {
  24. sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
  25. pending: [], queue: [], todos: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null,
  26. hasMore: false, loadingOlder: false, promptError: null, blank: false, lastAgentError: null,
  27. }
  28. }
  29. function makeSource(init?: Partial<ConversationSnapshot>) {
  30. let snap: ConversationSnapshot = { ...snapshotBase(), ...init }
  31. const subs = new Set<() => void>()
  32. return {
  33. set: (next: Partial<ConversationSnapshot>) => {
  34. snap = { ...snap, ...next }
  35. for (const fn of [...subs]) fn()
  36. },
  37. source: {
  38. getSnapshot: () => snap,
  39. subscribe: (fn: () => void) => {
  40. subs.add(fn)
  41. return () => subs.delete(fn)
  42. },
  43. },
  44. }
  45. }
  46. describe('deriveStats', () => {
  47. it('folds turns/steps/tokens and cache hit percentage', () => {
  48. const stats = deriveStats([
  49. assistant(1, 1, { inputTokens: 100, outputTokens: 50, cacheReadTokens: 900 }),
  50. assistant(2, 1, { inputTokens: 100, outputTokens: 50 }),
  51. assistant(3, 2),
  52. ])
  53. expect(stats.turns).toBe(2)
  54. expect(stats.steps).toBe(3)
  55. expect(stats.tokens).toBe(1200)
  56. expect(stats.cacheHitPct).toBe(82)
  57. })
  58. it('cache hit stays null with no cache accounting; non-assistant nodes ignored', () => {
  59. const tool: ToolResultNode = {
  60. kind: 'tool-result', seq: 5, time: 5_000, callId: 'c', call: null, callTime: null, content: [],
  61. isError: false, callView: null, resultView: null,
  62. }
  63. const stats = deriveStats([tool, assistant(1, 1)])
  64. expect(stats.steps).toBe(1)
  65. expect(stats.cacheHitPct).toBeNull()
  66. })
  67. })
  68. describe('StatsLine', () => {
  69. function props(source: { getSnapshot(): ConversationSnapshot; subscribe(fn: () => void): () => void }): StatsLineProps {
  70. return { useSession: bindSnapshotSelector(source) }
  71. }
  72. it('renders the joined stats row and hides with zero steps', () => {
  73. const { source } = makeSource({
  74. nodes: [assistant(1, 1, { inputTokens: 10, outputTokens: 5, cacheReadTokens: 90 })],
  75. })
  76. const view = render(<StatsLine {...props(source)} />)
  77. expect(view.getByText('cache hit 90% · 105 tokens · 1 turns · 1 steps')).toBeTruthy()
  78. const empty = makeSource()
  79. const emptyView = render(<StatsLine {...props(empty.source)} />)
  80. expect(emptyView.container.textContent).toBe('')
  81. })
  82. it('renders ZERO times during streaming chunk frames (RFC hard acceptance)', () => {
  83. const { set, source } = makeSource({ nodes: [assistant(1, 1)] })
  84. let renders = 0
  85. function Counting(p: StatsLineProps) {
  86. renders += 1
  87. return <StatsLine {...p} />
  88. }
  89. render(<Counting {...props(source)} />)
  90. const before = renders
  91. // Chunk frames swap partial only; nodes keeps its reference (object-layer contract).
  92. act(() => { set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'a' }] } }) })
  93. act(() => { set({ partial: { turn: 1, step: 2, blocks: [{ kind: 'text', text: 'ab' }] } }) })
  94. act(() => { set({ running: true }) })
  95. expect(renders).toBe(before)
  96. })
  97. })
  98. describe('bash sample row', () => {
  99. const ROOT = 'root-1' as SessionId
  100. const CHILD = 'child-1' as SessionId
  101. const result = (callId: string): ToolResultNode => ({
  102. kind: 'tool-result', seq: 3, time: 3_000, callId,
  103. call: { name: 'bash', argsRaw: '{"command":"make build","description":"Build"}' },
  104. callTime: 2_000,
  105. content: [], isError: false, callView: null, resultView: null,
  106. })
  107. /** Real list-store engine: the family fixture the in-component parentId branch reads. */
  108. function listStore() {
  109. return createSnapshotStore<SessionListState>({
  110. ids: [ROOT, CHILD],
  111. byId: {
  112. [ROOT]: { id: ROOT, title: 'r', displayTitle: 'r', running: false, blank: false, updatedAt: 0 },
  113. [CHILD]: { id: CHILD, title: 'c', displayTitle: 'c', parentId: ROOT, running: false, blank: false, updatedAt: 0 },
  114. },
  115. current: undefined,
  116. phase: 'ready',
  117. })
  118. }
  119. const rowProps = (sessionId: SessionId, over?: {
  120. store?: ReturnType<typeof listStore>
  121. openDetails?: () => void
  122. }): ToolRowProps => ({
  123. callId: 'c1', toolName: 'bash', block: result('c1'),
  124. openDetails: over?.openDetails ?? vi.fn(),
  125. sessionId,
  126. useSessions: bindSnapshotSelector(over?.store ?? listStore()),
  127. } as unknown as ToolRowProps)
  128. it('differential rendering: the scoped variant in sub-sessions, global at roots', () => {
  129. const scoped = render(<BashRow {...rowProps(CHILD)} />)
  130. expect(scoped.container.querySelector('[data-sample="bash-scoped"]')).not.toBeNull()
  131. expect(scoped.getByText('scoped')).toBeTruthy()
  132. const plain = render(<BashRow {...rowProps(ROOT)} />)
  133. expect(plain.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  134. })
  135. it('a session outside the list renders the global arm (no parent known)', () => {
  136. const view = render(<BashRow {...rowProps('gone' as SessionId)} />)
  137. expect(view.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  138. })
  139. it('a live parentId write flips the row to the scoped variant (store subscription)', () => {
  140. const store = listStore()
  141. const orphan = 'late-child' as SessionId
  142. store.update((d) => {
  143. d.ids.push(orphan)
  144. d.byId[orphan] = { id: orphan, title: 'l', displayTitle: 'l', running: false, blank: false, updatedAt: 0 }
  145. })
  146. const view = render(<BashRow {...rowProps(orphan, { store })} />)
  147. expect(view.container.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  148. act(() => {
  149. store.update((d) => { d.byId[orphan]!.parentId = ROOT })
  150. })
  151. expect(view.container.querySelector('[data-sample="bash-scoped"]')).not.toBeNull()
  152. })
  153. it('summarizes as Bash · description and hands clicks to openDetails on both arms', () => {
  154. const openGlobal = vi.fn()
  155. const global = render(<BashRow {...rowProps(ROOT, { openDetails: openGlobal })} />)
  156. // Two renders share document.body: query inside each container.
  157. const globalRow = global.container.querySelector('[data-sample="bash-global"]')!
  158. expect(globalRow.textContent).toContain('Bash')
  159. expect(globalRow.textContent).toContain('Build')
  160. fireEvent.click(globalRow)
  161. expect(openGlobal).toHaveBeenCalledTimes(1)
  162. const openScoped = vi.fn()
  163. const scoped = render(<BashRow {...rowProps(CHILD, { openDetails: openScoped })} />)
  164. const scopedRow = scoped.container.querySelector('[data-sample="bash-scoped"]')!
  165. expect(scopedRow.textContent).toContain('Bash')
  166. expect(scopedRow.textContent).toContain('Build')
  167. fireEvent.click(scopedRow)
  168. expect(openScoped).toHaveBeenCalledTimes(1)
  169. })
  170. })