useSessionFiles.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import type { ChatSession } from '@agent-server/chat-ui'
  2. import type { AgentClient } from '@agent-server/client'
  3. import type { FileDto } from '@agent-server/shared'
  4. import { computed, ref, watch, type Ref, type ShallowRef } from 'vue'
  5. /** 本会话的上传与产出文件;收到 file.changed 或上传完成(user.message 带附件)时刷新 */
  6. export function useSessionFiles(client: AgentClient, sessionId: Ref<string | null>, chat: ShallowRef<ChatSession | null>) {
  7. const files = ref<FileDto[]>([])
  8. const loading = ref(false)
  9. let timer: ReturnType<typeof setTimeout> | undefined
  10. let token = 0
  11. async function refresh() {
  12. const id = sessionId.value
  13. const my = ++token
  14. if (!id) {
  15. files.value = []
  16. return
  17. }
  18. loading.value = true
  19. try {
  20. const list = await client.sessions.files(id)
  21. if (my === token) files.value = list
  22. }
  23. catch {
  24. if (my === token) files.value = []
  25. }
  26. finally {
  27. if (my === token) loading.value = false
  28. }
  29. }
  30. function refreshSoon() {
  31. clearTimeout(timer)
  32. timer = setTimeout(() => void refresh(), 500)
  33. }
  34. watch(sessionId, () => void refresh(), { immediate: true })
  35. // 文件卡片数量或最新文件事件变化时刷新(含历史加载完成)
  36. watch(
  37. () => {
  38. const items = chat.value?.state.items ?? []
  39. let sig = ''
  40. for (const i of items) {
  41. if (i.kind === 'file') sig += `${i.fileId}:${i.seq};`
  42. else if (i.kind === 'user' && i.attachments.length) sig += `u${i.seq};`
  43. }
  44. return sig
  45. },
  46. () => refreshSoon(),
  47. )
  48. const uploads = computed(() => sortNewest(files.value.filter(f => f.origin === 'upload')))
  49. const outputs = computed(() => sortNewest(files.value.filter(f => f.origin === 'agent')))
  50. return { files, uploads, outputs, loading, refresh }
  51. }
  52. function sortNewest(list: FileDto[]) {
  53. return [...list].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt))
  54. }