~bigbes/lethe

ref: 34867fba4a37a882c2190e4af137984a56e26d98 lethe/web/src/features/home/useSessions.ts -rw-r--r-- 1.5 KiB
34867fba — Eugene Blikh docs(lethe-oidc-stub): record review pass + conclusion a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { useQuery } from '@tanstack/react-query'
import type { UseQueryResult } from '@tanstack/react-query'
import { apiFetch } from '../../api/client'
import { adaptSession } from '../../api/adapters'
import type { Session, SessionDTO, Tool, Host } from '../../api/adapters'

export interface HomeFilters {
  since?: '1d' | '7d' | '30d' | '90d' | 'all'
  tool?: Tool
  host?: Host
  cwd?: string
}

interface SessionsResponse {
  sessions: SessionDTO[]
  limit: number
  offset: number
}

function sinceToEpoch(since: string): number {
  const now = Math.floor(Date.now() / 1000)
  switch (since) {
    case '1d':  return now - 1 * 86400
    case '7d':  return now - 7 * 86400
    case '30d': return now - 30 * 86400
    case '90d': return now - 90 * 86400
    default:    return 0
  }
}

export function useSessions(filters: HomeFilters): UseQueryResult<Session[]> {
  const since = filters.since ?? '30d'

  return useQuery({
    queryKey: ['sessions', filters],
    queryFn: async () => {
      const params = new URLSearchParams()

      if (since !== 'all') {
        params.set('since', String(sinceToEpoch(since)))
      }
      if (filters.tool) {
        params.set('tool', filters.tool)
      }
      if (filters.host) {
        params.set('host', filters.host)
      }
      if (filters.cwd) {
        params.set('cwd', filters.cwd)
      }

      const qs = params.toString()
      const url = `/api/v1/sessions${qs ? `?${qs}` : ''}`
      const data = await apiFetch<SessionsResponse>(url)
      return data.sessions.map(adaptSession)
    },
  })
}