tree.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import { describe, expect, it } from 'vitest'
  2. import type {
  3. SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView,
  4. } from '@deepseek-ai/dsh-client-runtime/client'
  5. import { deriveFlat, deriveGroups, formatRelativeTime, projectLabel, UNGROUPED_KEY, UNGROUPED_LABEL } from '../src/client/tree.ts'
  6. import { createWorkspaceViewStore } from '../src/client/stores.ts'
  7. const sid = (id: string) => id as SessionId
  8. const wid = (id: string) => id as WorkspaceId
  9. const summary = (id: string, updatedAt: number, cwd?: string): SessionSummary => ({
  10. id: sid(id), displayTitle: id, running: false, blank: false, updatedAt, ...(cwd === undefined ? {} : { cwd }),
  11. })
  12. const list = (...items: SessionSummary[]): SessionListState => ({
  13. ids: items.map(item => item.id),
  14. byId: Object.fromEntries(items.map(item => [item.id, item])),
  15. current: undefined,
  16. phase: 'ready',
  17. })
  18. const workspace = (id: string, sessionIds: string[]): WorkspaceView => ({
  19. workspaceId: wid(id), path: `/projects/${id}`, title: id,
  20. sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
  21. })
  22. const view = (expandedProjects: readonly string[] = [], query = '') => ({
  23. expandedProjects, expandedSessions: [] as string[], query,
  24. })
  25. describe('deriveGroups', () => {
  26. it('keeps Host Workspace and sessionIds order without Client recency sorting', () => {
  27. const sessions = list(summary('newer', 20), summary('older', 10))
  28. const workspaces = [workspace('first', ['older', 'newer']), workspace('empty', [])]
  29. const groups = deriveGroups(sessions, workspaces, view(['first']))
  30. expect(groups.map(group => group.key)).toEqual(['first', 'empty'])
  31. expect(groups[0]!.sessions.map(session => session.id)).toEqual([sid('older'), sid('newer')])
  32. })
  33. it('puts only real unaccounted Sessions in the trailing Ungrouped group', () => {
  34. const sessions = list(summary('owned', 1, '/projects/first'), summary('loose', 9, '/other'))
  35. const groups = deriveGroups(sessions, [workspace('first', ['owned'])], view([UNGROUPED_KEY]))
  36. expect(groups.map(group => group.key)).toEqual(['first', UNGROUPED_KEY])
  37. expect(groups[1]!.sessions.map(session => session.id)).toEqual([sid('loose')])
  38. })
  39. it('shows only the current blank session in its Workspace count and tree', () => {
  40. const currentBlank = { ...summary('current-blank', 5), blank: true }
  41. const staleBlank = { ...summary('stale-blank', 4), blank: true }
  42. const real = summary('shown', 3)
  43. const sessions = {
  44. ...list(real, currentBlank, staleBlank),
  45. current: currentBlank.id,
  46. }
  47. const groups = deriveGroups(
  48. sessions, [workspace('first', ['shown', 'current-blank', 'stale-blank'])], view(['first']),
  49. )
  50. expect(groups[0]!.sessions.map(session => session.id)).toEqual([real.id, currentBlank.id])
  51. expect(groups[0]!.sessions.find(session => session.id === currentBlank.id)!.title).toBe('New Session')
  52. expect(groups[0]!.sessionCount).toBe(2)
  53. // A non-current blank stray never surfaces an Ungrouped bucket either.
  54. const strayGroups = deriveGroups(list({ ...summary('stray', 2), blank: true }), [workspace('first', [])], view())
  55. expect(strayGroups.map(group => group.key)).toEqual(['first'])
  56. })
  57. it('searches the current blank session by its New Session title', () => {
  58. const currentBlank = { ...summary('opaque-current', 5), blank: true }
  59. const staleBlank = { ...summary('new session stale', 4), blank: true }
  60. const sessions = {
  61. ...list(currentBlank, staleBlank),
  62. current: currentBlank.id,
  63. }
  64. const groups = deriveGroups(
  65. sessions, [workspace('first', ['opaque-current', 'new session stale'])], view([], 'new session'),
  66. )
  67. expect(groups[0]!.sessions.map(session => session.id)).toEqual([currentBlank.id])
  68. expect(groups[0]!.sessions[0]!.title).toBe('New Session')
  69. expect(groups[0]!.sessionCount).toBe(1)
  70. })
  71. it('builds, sorts, expands, and cycle-guards an ungrouped session tree', () => {
  72. const parent = summary('parent', 1)
  73. const oldChild = { ...summary('old-child', 10), parentId: parent.id }
  74. const newChild = { ...summary('new-child', 20), parentId: parent.id }
  75. const tieB = { ...summary('tie-b', 20), parentId: parent.id }
  76. const tieA = { ...summary('tie-a', 20), parentId: parent.id }
  77. const self = { ...summary('self', 2), parentId: sid('self') }
  78. const orphan = { ...summary('orphan', 3), parentId: sid('missing') }
  79. const cycleA = { ...summary('cycle-a', 4), parentId: sid('cycle-b') }
  80. const cycleB = { ...summary('cycle-b', 5), parentId: sid('cycle-a') }
  81. const groups = deriveGroups(
  82. list(parent, oldChild, newChild, tieB, tieA, self, orphan, cycleA, cycleB),
  83. [],
  84. { expandedProjects: [UNGROUPED_KEY], expandedSessions: [parent.id, cycleA.id, cycleB.id], query: '' },
  85. )
  86. expect(groups).toHaveLength(1)
  87. expect(groups[0]!.sessions.map(node => node.id)).toEqual([
  88. sid('orphan'), sid('self'), parent.id, sid('cycle-a'),
  89. ])
  90. expect(groups[0]!.sessions[2]!.children.map(node => node.id)).toEqual([
  91. newChild.id, tieA.id, tieB.id, oldChild.id,
  92. ])
  93. // Equal timestamps use ids as a deterministic tiebreak in either input order.
  94. expect(deriveGroups(list(summary('tie-a', 1), summary('tie-b', 1)), [], view([UNGROUPED_KEY]))[0]!
  95. .sessions.map(node => node.id)).toEqual([sid('tie-a'), sid('tie-b')])
  96. })
  97. it('tolerates Workspace membership arriving before its Session summary', () => {
  98. const partial: SessionListState = {
  99. ...list(),
  100. ids: [sid('present')],
  101. byId: { [sid('present')]: summary('present', 1) },
  102. }
  103. const groups = deriveGroups(partial, [workspace('project', ['missing', 'present'])], view(['project']))
  104. expect(groups[0]!.sessions.map(node => node.id)).toEqual([sid('present')])
  105. })
  106. it('searches descendants with ancestors and handles cycles, self parents, and label-only hits', () => {
  107. const root = { ...summary('root', 1), displayTitle: 'Ancestor' }
  108. const match = { ...summary('match', 2), displayTitle: 'Needle child', parentId: root.id }
  109. const sibling = { ...summary('sibling', 3), displayTitle: 'Other child', parentId: root.id }
  110. const self = { ...summary('self', 4), displayTitle: 'Needle self', parentId: sid('self') }
  111. const orphan = { ...summary('orphan', 5), displayTitle: 'Needle orphan', parentId: sid('absent') }
  112. const cycleA = { ...summary('cycle-a', 6), displayTitle: 'Needle cycle A', parentId: sid('cycle-b') }
  113. const cycleB = { ...summary('cycle-b', 7), displayTitle: 'Needle cycle B', parentId: sid('cycle-a') }
  114. const sessions = list(root, match, sibling, self, orphan, cycleA, cycleB)
  115. const groups = deriveGroups(sessions, [workspace('project', sessions.ids)], view([], 'needle'))
  116. expect(groups[0]!.sessions.flatMap(node => [node.id, ...node.children.map(child => child.id)])).toEqual([
  117. root.id, match.id, self.id, orphan.id, cycleA.id, cycleB.id,
  118. ])
  119. const labelOnly = deriveGroups(
  120. list(summary('hidden', 1)),
  121. [workspace('label-hit', ['hidden']), workspace('other', [])],
  122. view([], 'label'),
  123. )
  124. expect(labelOnly).toEqual([
  125. expect.objectContaining({ key: 'label-hit', expanded: false, sessions: [], sessionCount: 1 }),
  126. ])
  127. })
  128. it('marks selected Workspace and Ungrouped sessions without relying on an Intent', () => {
  129. const owned = summary('owned', 1)
  130. const loose = summary('loose', 2)
  131. const ws = workspace('project', ['owned'])
  132. const ownedGroups = deriveGroups({ ...list(owned, loose), current: owned.id }, [ws], view())
  133. expect(ownedGroups.find(group => group.key === 'project')!.containsCurrent).toBe(true)
  134. const looseGroups = deriveGroups({ ...list(owned, loose), current: loose.id }, [ws], view())
  135. expect(looseGroups.find(group => group.key === UNGROUPED_KEY)!.containsCurrent).toBe(true)
  136. })
  137. })
  138. describe('deriveFlat', () => {
  139. it('flattens every session — fork children included — newest-first with id tiebreak', () => {
  140. const parent = summary('parent', 10)
  141. const child = { ...summary('child', 30), parentId: parent.id }
  142. const tieB = summary('tie-b', 20)
  143. const tieA = summary('tie-a', 20)
  144. const rows = deriveFlat(list(parent, child, tieB, tieA), { query: '' })
  145. expect(rows.map(row => row.id)).toEqual([sid('child'), sid('tie-a'), sid('tie-b'), sid('parent')])
  146. // Rows are branch-free: no children, no expansion.
  147. expect(rows.every(row => row.children.length === 0 && !row.hasChildren && !row.expanded)).toBe(true)
  148. })
  149. it('search filters by case-insensitive display-title substring', () => {
  150. const hit = { ...summary('hit', 2), displayTitle: 'Needle row' }
  151. const miss = { ...summary('miss', 1), displayTitle: 'Other' }
  152. expect(deriveFlat(list(hit, miss), { query: ' NEEDLE ' }).map(row => row.id)).toEqual([sid('hit')])
  153. })
  154. it('tolerates ids whose summary has not landed yet', () => {
  155. const partial: SessionListState = { ...list(summary('present', 1)), ids: [sid('ghost'), sid('present')] }
  156. expect(deriveFlat(partial, { query: '' }).map(row => row.id)).toEqual([sid('present')])
  157. })
  158. it('shows only the current blank session with its New Session title', () => {
  159. const currentBlank = { ...summary('current-blank', 9), blank: true }
  160. const staleBlank = { ...summary('stale-blank', 8), blank: true }
  161. const sessions = {
  162. ...list(summary('real', 1), currentBlank, staleBlank),
  163. current: currentBlank.id,
  164. }
  165. const rows = deriveFlat(sessions, { query: '' })
  166. expect(rows.map(row => row.id)).toEqual([currentBlank.id, sid('real')])
  167. expect(rows.map(row => row.title)).toEqual(['New Session', 'real'])
  168. expect(deriveFlat(sessions, { query: 'new session' }).map(row => row.id)).toEqual([currentBlank.id])
  169. expect(deriveFlat(sessions, { query: 'stale-blank' })).toEqual([])
  170. })
  171. })
  172. describe('createWorkspaceViewStore', () => {
  173. it('defaults to workspace grouping; setGroupBy is the sole mutation', () => {
  174. const store = createWorkspaceViewStore().create()
  175. expect(store.getSnapshot().groupBy).toBe('workspace')
  176. store.actions.setGroupBy('flat')
  177. expect(store.getSnapshot().groupBy).toBe('flat')
  178. })
  179. })
  180. describe('projectLabel', () => {
  181. it('uses the Ungrouped fallback and extracts POSIX and Windows basenames', () => {
  182. expect(projectLabel(undefined)).toBe(UNGROUPED_LABEL)
  183. expect(projectLabel('')).toBe(UNGROUPED_LABEL)
  184. expect(projectLabel('/projects/demo/')).toBe('demo')
  185. expect(projectLabel('C:\\projects\\demo\\')).toBe('demo')
  186. expect(projectLabel('/')).toBe('/')
  187. })
  188. })
  189. describe('formatRelativeTime', () => {
  190. it('formats current, minute, hour, day, month, and year buckets', () => {
  191. const now = 400 * 24 * 60 * 60 * 1_000
  192. expect(formatRelativeTime(now, now)).toBe('now')
  193. expect(formatRelativeTime(now - 5 * 60_000, now)).toBe('5min')
  194. expect(formatRelativeTime(now - 3 * 3_600_000, now)).toBe('3h')
  195. expect(formatRelativeTime(now - 2 * 86_400_000, now)).toBe('2d')
  196. expect(formatRelativeTime(now - 60 * 86_400_000, now)).toBe('2mo')
  197. expect(formatRelativeTime(0, now)).toBe('1y')
  198. })
  199. })