sessions.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import type { ChatMessage, JsonValue, SessionSummary } from '@shared/types'
  2. import { apiRequest, apiUrl, unwrapData } from './client'
  3. import { normalizeChatMessage, normalizeSession, number, record, values } from '@/utils/normalize'
  4. const EXCLUDED_SOURCES = 'cron,ios_group,yaoyao_workspace'
  5. export interface SessionPage {
  6. items: SessionSummary[]
  7. nextCursor?: string | null
  8. total?: number
  9. }
  10. export interface MessagePage {
  11. session?: SessionSummary
  12. messages: ChatMessage[]
  13. total: number
  14. returned: number
  15. hasMore: boolean
  16. offset: number
  17. limit: number
  18. }
  19. export async function getSessions(profile?: string, cursor?: string, limit = 100, view: 'chat' | 'history' = 'chat'): Promise<SessionPage> {
  20. const offset = Math.max(0, Number.parseInt(cursor ?? '0', 10) || 0)
  21. const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/sessions', {
  22. profile,
  23. offset,
  24. limit: Math.max(1, Math.min(200, limit)),
  25. order: 'recent',
  26. archived: 'exclude',
  27. exclude: EXCLUDED_SOURCES,
  28. view,
  29. })))
  30. const source = record(payload)
  31. const rawItems = values(source.items ?? source.sessions ?? payload)
  32. const items = rawItems.map(item => normalizeSession(item, profile)).filter(session => session.id)
  33. .filter(session => !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source))
  34. const total = number(source.total)
  35. const nextOffset = offset + items.length
  36. return {
  37. items,
  38. nextCursor: typeof source.nextCursor === 'string'
  39. ? source.nextCursor
  40. : typeof source.next_cursor === 'string'
  41. ? source.next_cursor
  42. : total > nextOffset && items.length ? String(nextOffset) : null,
  43. total: total || undefined,
  44. }
  45. }
  46. export async function searchSessions(query: string, profile?: string, limit = 100): Promise<SessionSummary[]> {
  47. const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/sessions/search', {
  48. q: query,
  49. profile,
  50. limit: Math.max(1, Math.min(200, limit)),
  51. exclude: EXCLUDED_SOURCES,
  52. })))
  53. const source = record(payload)
  54. return values(source.items ?? source.sessions ?? source.results ?? payload).map(item => normalizeSession(item, profile))
  55. .filter(session => session.id && !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source))
  56. }
  57. export async function getSession(id: string, profile?: string): Promise<SessionSummary> {
  58. const payload = unwrapData(await apiRequest<unknown>(apiUrl(`/api/app/sessions/${encodeURIComponent(id)}`, { profile })))
  59. const source = record(payload)
  60. return normalizeSession(source.session ?? payload, profile)
  61. }
  62. export async function getMessages(
  63. sessionId: string,
  64. offset: number,
  65. limit = 150,
  66. profile?: string,
  67. forceRefresh = false,
  68. view: 'chat' | 'history' = 'chat',
  69. ): Promise<MessagePage> {
  70. const safeOffset = Math.max(0, Math.trunc(offset))
  71. const safeLimit = Math.max(1, Math.min(500, Math.trunc(limit)))
  72. const url = apiUrl(`/api/app/sessions/${encodeURIComponent(sessionId)}/messages`, {
  73. offset: safeOffset,
  74. limit: safeLimit,
  75. order: 'latest',
  76. include_compacted: true,
  77. profile,
  78. ...(view === 'history' ? {view} : {}),
  79. })
  80. const payload = unwrapData(await apiRequest<unknown>(url, forceRefresh ? { headers: { 'X-Yaoyao-Cache': 'bypass' } } : {}))
  81. const source = record(payload)
  82. const pagination = record(source.pagination)
  83. const messages = values(source.messages ?? source.items ?? payload).map(message => normalizeChatMessage(message, sessionId, profile))
  84. const returned = Math.max(number(pagination.returned), messages.length)
  85. const total = Math.max(number(pagination.total ?? source.total), safeOffset + returned)
  86. const hasMore = typeof pagination.hasMore === 'boolean'
  87. ? pagination.hasMore
  88. : typeof pagination.has_more === 'boolean'
  89. ? pagination.has_more
  90. : safeOffset + returned < total || returned >= safeLimit
  91. return {
  92. session: source.session ? normalizeSession(source.session, profile) : undefined,
  93. messages,
  94. total,
  95. returned,
  96. hasMore,
  97. offset: safeOffset,
  98. limit: safeLimit,
  99. }
  100. }
  101. export async function createSession(profile: string, title?: string): Promise<SessionSummary> {
  102. const payload = unwrapData(await apiRequest<unknown>('/api/app/sessions', {
  103. method: 'POST',
  104. body: { profile, title: title || null, source: 'web' } as JsonValue,
  105. }))
  106. const source = record(payload)
  107. return normalizeSession(source.session ?? payload, profile)
  108. }
  109. export async function updateSession(
  110. id: string,
  111. patch: { title?: string; archived?: boolean; pinned?: boolean },
  112. profile?: string,
  113. ): Promise<SessionSummary> {
  114. await apiRequest<unknown>(apiUrl(`/api/app/sessions/${encodeURIComponent(id)}`, { profile }), {
  115. method: 'PATCH', body: patch as JsonValue,
  116. })
  117. return getSession(id, profile)
  118. }
  119. export async function deleteSession(id: string, profile?: string): Promise<void> {
  120. await apiRequest(apiUrl(`/api/app/sessions/${encodeURIComponent(id)}`, { profile }), { method: 'DELETE' })
  121. }
  122. export async function requestHistorySync(sessionId:string,profile?:string):Promise<void>{
  123. await apiRequest(apiUrl(`/api/app/sessions/${encodeURIComponent(sessionId)}/sync`,{profile}),{method:'POST',body:{}})
  124. }
  125. export async function getSessionUnread(profile?: string): Promise<Record<string, number>> {
  126. const payload = unwrapData(await apiRequest<unknown>(apiUrl('/api/app/sessions/unread', { profile })))
  127. const source = record(payload)
  128. const sessionRows = values(source.sessions ?? source.items)
  129. if (sessionRows.length) {
  130. const result: Record<string, number> = {}
  131. for (const value of sessionRows) {
  132. const item = record(value)
  133. const id = typeof item.sessionId === 'string'
  134. ? item.sessionId
  135. : typeof item.session_id === 'string' ? item.session_id : ''
  136. if (id) result[id] = Math.max(0, number(item.final_unread_count ?? item.unreadCount ?? item.unread_count ?? item.count))
  137. }
  138. return result
  139. }
  140. const raw = record(source.items ?? source.unread ?? source.counts ?? payload)
  141. const result: Record<string, number> = {}
  142. for (const [sessionId, value] of Object.entries(raw)) {
  143. if (typeof value === 'number' || typeof value === 'string') result[sessionId] = Math.max(0, number(value))
  144. else {
  145. const item = record(value)
  146. const id = typeof item.sessionId === 'string' ? item.sessionId : typeof item.session_id === 'string' ? item.session_id : sessionId
  147. result[id] = Math.max(0, number(item.final_unread_count ?? item.unreadCount ?? item.unread_count ?? item.count))
  148. }
  149. }
  150. return result
  151. }
  152. export async function markSessionRead(sessionId: string, readMessageCount: number, profile?: string): Promise<void> {
  153. await apiRequest(apiUrl(`/api/app/sessions/unread/${encodeURIComponent(sessionId)}`, { profile }), {
  154. method: 'PATCH', body: { readMessageCount: Math.max(0, Math.trunc(readMessageCount)) },
  155. })
  156. }