tree.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 {
  6. deriveFlat, deriveGroups, deriveSearchResults, projectLabel, relativeTime,
  7. UNGROUPED_KEY, UNGROUPED_LABEL,
  8. } from '../src/client/tree.ts'
  9. import { createWorkspaceViewStore } from '../src/client/stores.ts'
  10. const sid = (id: string) => id as SessionId
  11. const wid = (id: string) => id as WorkspaceId
  12. const summary = (id: string, updatedAt: number, cwd?: string): SessionSummary => ({
  13. id: sid(id), displayTitle: id, running: false, waitingApproval: false, blank: false, updatedAt, ...(cwd === undefined ? {} : { cwd }),
  14. })
  15. const list = (...items: SessionSummary[]): SessionListState => ({
  16. ids: items.map(item => item.id),
  17. byId: Object.fromEntries(items.map(item => [item.id, item])),
  18. current: undefined,
  19. phase: 'ready',
  20. })
  21. const workspace = (id: string, sessionIds: string[], title = id): WorkspaceView => ({
  22. workspaceId: wid(id), path: `/projects/${id}`, title,
  23. sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
  24. })
  25. const view = (expandedProjects: readonly string[] = []) => ({
  26. expandedProjects,
  27. })
  28. const noArchive: readonly SessionId[] = []
  29. const archived = (...ids: string[]): readonly SessionId[] => ids.map(sid)
  30. describe('deriveGroups', () => {
  31. it('keeps Host Workspace and sessionIds order without Client recency sorting', () => {
  32. const sessions = list(summary('newer', 20), summary('older', 10))
  33. const workspaces = [workspace('first', ['older', 'newer']), workspace('empty', [])]
  34. const groups = deriveGroups(sessions, workspaces, noArchive, view(['first']))
  35. expect(groups.map(group => group.key)).toEqual(['first', 'empty'])
  36. expect(groups[0]!.sessions.map(session => session.id)).toEqual([sid('older'), sid('newer')])
  37. })
  38. it('puts only real unaccounted Sessions in the trailing Ungrouped group', () => {
  39. const sessions = list(summary('owned', 1, '/projects/first'), summary('loose', 9, '/other'))
  40. const groups = deriveGroups(sessions, [workspace('first', ['owned'])], noArchive, view([UNGROUPED_KEY]))
  41. expect(groups.map(group => group.key)).toEqual(['first', UNGROUPED_KEY])
  42. expect(groups[1]!.sessions.map(session => session.id)).toEqual([sid('loose')])
  43. })
  44. it('shows only the current blank session in its Workspace count and tree', () => {
  45. const currentBlank = { ...summary('current-blank', 5), blank: true }
  46. const staleBlank = { ...summary('stale-blank', 4), blank: true }
  47. const real = summary('shown', 3)
  48. const sessions = {
  49. ...list(real, currentBlank, staleBlank),
  50. current: currentBlank.id,
  51. }
  52. const groups = deriveGroups(
  53. sessions, [workspace('first', ['shown', 'current-blank', 'stale-blank'])], noArchive, view(['first']),
  54. )
  55. expect(groups[0]!.sessions.map(session => session.id)).toEqual([real.id, currentBlank.id])
  56. const blankNode = groups[0]!.sessions.find(session => session.id === currentBlank.id)!
  57. // The stored placeholder title stays canonical; the renderer swaps in
  58. // the localized New Session label via the blank flag.
  59. expect(blankNode.title).toBe('New Session')
  60. expect(blankNode.blank).toBe(true)
  61. expect(groups[0]!.sessions.find(session => session.id === real.id)!.blank).toBe(false)
  62. expect(groups[0]!.sessionCount).toBe(2)
  63. // A non-current blank stray never surfaces an Ungrouped bucket either.
  64. const strayGroups = deriveGroups(list({ ...summary('stray', 2), blank: true }), [workspace('first', [])], noArchive, view())
  65. expect(strayGroups.map(group => group.key)).toEqual(['first'])
  66. })
  67. it('ignores fork lineage and sorts every ungrouped session as a top-level row', () => {
  68. const parent = summary('parent', 1)
  69. const oldChild = { ...summary('old-child', 10), parentId: parent.id }
  70. const newChild = { ...summary('new-child', 20), parentId: parent.id }
  71. const tieB = { ...summary('tie-b', 20), parentId: parent.id }
  72. const tieA = { ...summary('tie-a', 20), parentId: parent.id }
  73. const self = { ...summary('self', 2), parentId: sid('self') }
  74. const orphan = { ...summary('orphan', 3), parentId: sid('missing') }
  75. const cycleA = { ...summary('cycle-a', 4), parentId: sid('cycle-b') }
  76. const cycleB = { ...summary('cycle-b', 5), parentId: sid('cycle-a') }
  77. const groups = deriveGroups(
  78. list(parent, oldChild, newChild, tieB, tieA, self, orphan, cycleA, cycleB),
  79. [],
  80. noArchive,
  81. { expandedProjects: [UNGROUPED_KEY] },
  82. )
  83. expect(groups).toHaveLength(1)
  84. expect(groups[0]!.sessions.map(node => node.id)).toEqual([
  85. newChild.id, tieA.id, tieB.id, oldChild.id,
  86. cycleB.id, cycleA.id, orphan.id, self.id, parent.id,
  87. ])
  88. // Equal timestamps use ids as a deterministic tiebreak in either input order.
  89. expect(deriveGroups(list(summary('tie-a', 1), summary('tie-b', 1)), [], noArchive, view([UNGROUPED_KEY]))[0]!
  90. .sessions.map(node => node.id)).toEqual([sid('tie-a'), sid('tie-b')])
  91. })
  92. it('tolerates Workspace membership arriving before its Session summary', () => {
  93. const partial: SessionListState = {
  94. ...list(),
  95. ids: [sid('present')],
  96. byId: { [sid('present')]: summary('present', 1) },
  97. }
  98. const groups = deriveGroups(partial, [workspace('project', ['missing', 'present'])], noArchive, view(['project']))
  99. expect(groups[0]!.sessions.map(node => node.id)).toEqual([sid('present')])
  100. })
  101. it('hides archived sessions from workspace groups and Ungrouped', () => {
  102. const kept = summary('kept', 1, '/projects/first')
  103. const gone = summary('gone', 2, '/projects/first')
  104. const looseGone = summary('loose-gone', 3, '/other')
  105. const sessions = list(kept, gone, looseGone)
  106. const groups = deriveGroups(
  107. sessions, [workspace('first', ['kept', 'gone'])], archived('gone', 'loose-gone'), view(['first', UNGROUPED_KEY]),
  108. )
  109. // The archived member drops from its group AND the archived stray never
  110. // surfaces an Ungrouped bucket; counts follow the visible rows.
  111. expect(groups.map(group => group.key)).toEqual(['first'])
  112. expect(groups[0]!.sessions.map(node => node.id)).toEqual([kept.id])
  113. expect(groups[0]!.sessionCount).toBe(1)
  114. })
  115. it('marks selected Workspace and Ungrouped sessions without relying on an Intent', () => {
  116. const owned = summary('owned', 1)
  117. const loose = summary('loose', 2)
  118. const ws = workspace('project', ['owned'])
  119. const ownedGroups = deriveGroups({ ...list(owned, loose), current: owned.id }, [ws], noArchive, view())
  120. expect(ownedGroups.find(group => group.key === 'project')!.containsCurrent).toBe(true)
  121. const looseGroups = deriveGroups({ ...list(owned, loose), current: loose.id }, [ws], noArchive, view())
  122. expect(looseGroups.find(group => group.key === UNGROUPED_KEY)!.containsCurrent).toBe(true)
  123. })
  124. })
  125. describe('deriveFlat', () => {
  126. it('flattens every session — fork children included — newest-first with id tiebreak', () => {
  127. const parent = summary('parent', 10)
  128. const child = { ...summary('child', 30), parentId: parent.id }
  129. const tieB = summary('tie-b', 20)
  130. const tieA = summary('tie-a', 20)
  131. const rows = deriveFlat(list(parent, child, tieB, tieA), noArchive)
  132. expect(rows.map(row => row.id)).toEqual([sid('child'), sid('tie-a'), sid('tie-b'), sid('parent')])
  133. })
  134. it('tolerates ids whose summary has not landed yet', () => {
  135. const partial: SessionListState = { ...list(summary('present', 1)), ids: [sid('ghost'), sid('present')] }
  136. expect(deriveFlat(partial, noArchive).map(row => row.id)).toEqual([sid('present')])
  137. })
  138. it('shows only the current blank session and excludes blanks from search', () => {
  139. const currentBlank = { ...summary('current-blank', 9), blank: true }
  140. const staleBlank = { ...summary('stale-blank', 8), blank: true }
  141. const sessions = {
  142. ...list(summary('real', 1), currentBlank, staleBlank),
  143. current: currentBlank.id,
  144. }
  145. const rows = deriveFlat(sessions, noArchive)
  146. expect(rows.map(row => row.id)).toEqual([currentBlank.id, sid('real')])
  147. expect(rows.map(row => row.title)).toEqual(['New Session', 'real'])
  148. expect(rows.map(row => row.blank)).toEqual([true, false])
  149. })
  150. it('hides archived sessions in flat mode', () => {
  151. const kept = summary('kept', 1)
  152. const gone = summary('gone', 2)
  153. expect(deriveFlat(list(kept, gone), archived('gone')).map(row => row.id)).toEqual([kept.id])
  154. })
  155. })
  156. describe('deriveSearchResults archive filtering', () => {
  157. it('archived sessions never match — not by title and not via a backend content hit', () => {
  158. const hit = summary('hit', 2)
  159. hit.displayTitle = 'Needle row'
  160. const gone = summary('gone', 1)
  161. gone.displayTitle = 'Needle archived'
  162. const result = deriveSearchResults(
  163. list(hit, gone),
  164. [],
  165. 'needle',
  166. archived('gone'),
  167. { items: [{ sessionId: gone.id, snippet: 'needle body' }], hasMore: false },
  168. 10,
  169. )
  170. expect(result.items.map(item => item.id)).toEqual([hit.id])
  171. })
  172. })
  173. describe('deriveSearchResults', () => {
  174. it('merges local title/Workspace matches before ranked content hits and enriches duplicates', () => {
  175. const titleHit = summary('title-hit', 30, '/projects/a')
  176. titleHit.displayTitle = 'Needle title'
  177. const workspaceHit = summary('workspace-hit', 20, '/projects/b')
  178. workspaceHit.displayTitle = 'Ordinary title'
  179. const contentHit = summary('content-hit', 10, '/projects/c')
  180. const sessions = list(titleHit, workspaceHit, contentHit)
  181. const result = deriveSearchResults(
  182. sessions,
  183. [
  184. workspace('a', ['title-hit'], 'Alpha'),
  185. workspace('b', ['workspace-hit'], 'Needle Workspace'),
  186. workspace('duplicate-owner', ['title-hit'], 'Ignored duplicate owner'),
  187. ],
  188. ' NEEDLE ',
  189. noArchive,
  190. {
  191. items: [
  192. { sessionId: contentHit.id, snippet: 'body needle excerpt' },
  193. { sessionId: contentHit.id, snippet: 'ignored duplicate excerpt' },
  194. { sessionId: titleHit.id, snippet: 'title session body excerpt' },
  195. { sessionId: sid('unknown'), snippet: 'not in session.list' },
  196. ],
  197. hasMore: false,
  198. },
  199. 10,
  200. )
  201. expect(result).toEqual({
  202. items: [
  203. {
  204. id: titleHit.id,
  205. title: 'Needle title',
  206. workspace: 'Alpha',
  207. running: false,
  208. snippet: 'title session body excerpt',
  209. },
  210. {
  211. id: workspaceHit.id,
  212. title: 'Ordinary title',
  213. workspace: 'Needle Workspace',
  214. running: false,
  215. },
  216. {
  217. id: contentHit.id,
  218. title: 'content-hit',
  219. workspace: 'c',
  220. running: false,
  221. snippet: 'body needle excerpt',
  222. },
  223. ],
  224. hasMore: false,
  225. })
  226. })
  227. it('excludes blank sessions from search regardless of query or content hits', () => {
  228. const currentBlank = { ...summary('opaque-current', 5), blank: true }
  229. const staleBlank = { ...summary('new session stale', 4), blank: true }
  230. const sessions = {
  231. ...list(currentBlank, staleBlank),
  232. current: currentBlank.id,
  233. }
  234. // Blank placeholders never match — not their localized-display title, not
  235. // their id, and not even a backend content hit naming them.
  236. const result = deriveSearchResults(
  237. sessions,
  238. [workspace('first', ['opaque-current', 'new session stale'])],
  239. 'new session',
  240. noArchive,
  241. {
  242. items: [
  243. { sessionId: staleBlank.id, snippet: 'stale body' },
  244. { sessionId: currentBlank.id, snippet: 'current body' },
  245. ],
  246. hasMore: false,
  247. },
  248. 10,
  249. )
  250. expect(result.items).toEqual([])
  251. })
  252. it('uses the supplied cap and preserves either local overflow or backend hasMore', () => {
  253. const rows = Array.from({ length: 5 }, (_, index) => {
  254. const item = summary(`s-${String(index).padStart(2, '0')}`, index)
  255. item.displayTitle = `Needle ${String(index)}`
  256. return item
  257. })
  258. const overflow = deriveSearchResults(
  259. list(...rows),
  260. [],
  261. 'needle',
  262. noArchive,
  263. { items: [], hasMore: false },
  264. 3,
  265. )
  266. expect(overflow.items).toHaveLength(3)
  267. expect(overflow.hasMore).toBe(true)
  268. const backendMore = deriveSearchResults(
  269. list(summary('body', 1)),
  270. [],
  271. 'needle',
  272. noArchive,
  273. { items: [{ sessionId: sid('body'), snippet: 'needle' }], hasMore: true },
  274. 3,
  275. )
  276. expect(backendMore.items).toHaveLength(1)
  277. expect(backendMore.hasMore).toBe(true)
  278. expect(deriveSearchResults(list(), [], ' ', noArchive, { items: [], hasMore: true }, 3))
  279. .toEqual({ items: [], hasMore: false })
  280. })
  281. })
  282. describe('createWorkspaceViewStore', () => {
  283. it('defaults to workspace grouping; setGroupBy is the sole mutation', () => {
  284. const store = createWorkspaceViewStore().create()
  285. expect(store.getSnapshot().groupBy).toBe('workspace')
  286. store.actions.setGroupBy('flat')
  287. expect(store.getSnapshot().groupBy).toBe('flat')
  288. })
  289. })
  290. describe('projectLabel', () => {
  291. it('uses the Ungrouped fallback and extracts POSIX and Windows basenames', () => {
  292. expect(projectLabel(undefined)).toBe(UNGROUPED_LABEL)
  293. expect(projectLabel('')).toBe(UNGROUPED_LABEL)
  294. expect(projectLabel('/projects/demo/')).toBe('demo')
  295. expect(projectLabel('C:\\projects\\demo\\')).toBe('demo')
  296. expect(projectLabel('/')).toBe('/')
  297. })
  298. })
  299. describe('relativeTime', () => {
  300. it('buckets current, minute, hour, day, month, and year distances', () => {
  301. const now = 400 * 24 * 60 * 60 * 1_000
  302. expect(relativeTime(now, now)).toEqual({ unit: 'now', n: 0 })
  303. expect(relativeTime(now - 5 * 60_000, now)).toEqual({ unit: 'minutes', n: 5 })
  304. expect(relativeTime(now - 3 * 3_600_000, now)).toEqual({ unit: 'hours', n: 3 })
  305. expect(relativeTime(now - 2 * 86_400_000, now)).toEqual({ unit: 'days', n: 2 })
  306. expect(relativeTime(now - 60 * 86_400_000, now)).toEqual({ unit: 'months', n: 2 })
  307. expect(relativeTime(0, now)).toEqual({ unit: 'years', n: 1 })
  308. })
  309. })