1
0

tree.spec.ts 16 KB

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