tree.spec.ts 17 KB

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