ChatView.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <script setup lang="ts">
  2. import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
  3. import { useRoute, useRouter } from 'vue-router'
  4. import AppIcon from '@/components/common/AppIcon.vue'
  5. import YaoYaoSidebarIcon from '@/components/common/YaoYaoSidebarIcon.vue'
  6. import ChoiceDialog from '@/components/common/ChoiceDialog.vue'
  7. import type { ChoiceOption } from '@/components/common/types'
  8. import ComposerShell from '@/components/composer/ComposerShell.vue'
  9. import type { ComposerOption, ComposerReference, ComposerSubmit } from '@/components/composer/types'
  10. import PreviewInspector from '@/components/library/PreviewInspector.vue'
  11. import PreviewModal from '@/components/library/PreviewModal.vue'
  12. import ImagePreviewLightbox from '@/components/library/ImagePreviewLightbox.vue'
  13. import type { PreviewMedia } from '@/components/library/ImagePreviewLightbox.vue'
  14. import type { UiLibraryItem } from '@/components/library/types'
  15. import { mediaItemsFromMessages, previewItemFromUrl } from '@/components/library/mediaSequence'
  16. import MessageTimeline from '@/components/messages/MessageTimeline.vue'
  17. import type { UiMessage } from '@/components/messages/types'
  18. import ResourceSidebar from '@/components/app/ResourceSidebar.vue'
  19. import WorkspaceView from '@/components/workspace/WorkspaceView.vue'
  20. import { chatInteraction, chatMessagesToUi, sessionSidebarItem } from '@/components/workspace/viewModels'
  21. import { consumeLibraryItemForComposer, loadComposerFile } from '@/components/workspace/pendingComposer'
  22. import { useAuthStore } from '@/stores/auth'
  23. import { useChatStore } from '@/stores/chat'
  24. import { getSession } from '@/api/sessions'
  25. const auth = useAuthStore()
  26. const chat = useChatStore()
  27. const route = useRoute()
  28. const router = useRouter()
  29. const search = ref('')
  30. const quoted = ref<UiMessage | null>(null)
  31. const preview = ref<UiLibraryItem | null>(null)
  32. const filePreview = ref<UiLibraryItem | null>(null)
  33. const mediaPreviewIndex = ref<number | null>(null)
  34. const modelDialog = ref(false)
  35. const showTools = ref(true)
  36. const queueMode = ref(false)
  37. const actionSessionId = ref('')
  38. const renaming = ref(false)
  39. const renameValue = ref('')
  40. const composer = ref<InstanceType<typeof ComposerShell> | null>(null)
  41. const timeline = ref<InstanceType<typeof MessageTimeline> | null>(null)
  42. const restoringRouteProfile = ref('')
  43. const sessions = computed(() => [...chat.sessions]
  44. .filter(session => !['cron', 'ios_group'].includes(session.source))
  45. .filter(session => !search.value.trim() || `${session.title} ${session.preview || ''}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())))
  46. const agentNames = computed(() => new Map(auth.profiles.map(profile => [
  47. profile.name,
  48. profile.agentName || profile.displayName || profile.name,
  49. ])))
  50. const sidebarItems = computed(() => sessions.value.map(session => sessionSidebarItem(
  51. session,
  52. chat.unreadCounts[session.id] ?? 0,
  53. agentNames.value.get(session.profile || auth.activeProfile?.name || ''),
  54. )))
  55. const messages = computed(() => chatMessagesToUi(chat.messages, profile => profile ? agentNames.value.get(profile) : undefined))
  56. const conversationMediaItems = computed(() => mediaItemsFromMessages(messages.value))
  57. const lightboxMedia = computed(() => conversationMediaItems.value.map(item => ({ url: item.previewUrl || item.downloadUrl || '', name: item.name, type: item.kind as 'image' | 'video' })).filter(item => item.url))
  58. const activeSession = computed(() => chat.activeSession)
  59. const connected = computed(() => ['connected', 'ready'].includes(chat.connectionState))
  60. const interaction = computed(() => chatInteraction(chat.pendingApproval, chat.pendingClarification))
  61. const reference = computed<ComposerReference | null>(() => quoted.value ? { id: quoted.value.id, content: quoted.value.content, author: quoted.value.author } : null)
  62. const forkSourceTitle = computed(() => {
  63. const parentId = activeSession.value?.parentSessionId
  64. if (!parentId) return ''
  65. return chat.sessions.find(session => session.id === parentId && session.profile === activeSession.value?.profile)?.title || parentId
  66. })
  67. const modelOptions = computed<ChoiceOption[]>(() => chat.models.map(model => ({ id: `${model.provider}:${model.id}`, label: model.name || model.id, description: model.provider })))
  68. const selectedModelId = computed(() => chat.selectedModel ? `${chat.selectedModel.provider}:${chat.selectedModel.id}` : '')
  69. const reasoningOptions: ChoiceOption[] = [
  70. { id: '', label: '默认', description: '使用模型或 Profile 的默认强度' },
  71. { id: 'none', label: '关闭', description: '不使用额外推理' },
  72. { id: 'low', label: '低', description: '更快的轻量推理' },
  73. { id: 'medium', label: '中', description: '速度与深度平衡' },
  74. { id: 'high', label: '高', description: '更深入地分析复杂问题' },
  75. { id: 'xhigh', label: '极高', description: '适用于最复杂的任务' },
  76. ]
  77. const reasoningComposerOptions = computed<ComposerOption[]>(() => reasoningOptions.map(option => ({
  78. id: option.id,
  79. label: option.label,
  80. detail: option.description,
  81. })))
  82. const reasoningLabel = computed(() => reasoningOptions.find(option => option.id === (chat.reasoningEffort || ''))?.label || '默认')
  83. function routeProfile(): string {
  84. const value = typeof route.query.profile === 'string' ? route.query.profile : ''
  85. return auth.profiles.some(profile => profile.name === value) ? value : ''
  86. }
  87. function sessionLocation(id: string, profile: string) {
  88. return { path: `/chat/${encodeURIComponent(id)}`, query: { profile } }
  89. }
  90. async function findLegacySessionProfile(sessionId: string): Promise<string> {
  91. for (const profile of auth.profiles) {
  92. try {
  93. const session = await getSession(sessionId, profile.name)
  94. if (session.id === sessionId) return profile.name
  95. } catch { /* Try the next profile: 9119 returns 404 for a foreign session. */ }
  96. }
  97. return auth.activeProfile?.name || ''
  98. }
  99. async function ensureRouteProfile(profile: string): Promise<void> {
  100. if (!profile || auth.activeProfile?.name === profile) return
  101. chat.switchProfile(profile)
  102. restoringRouteProfile.value = profile
  103. auth.selectProfile(profile)
  104. await nextTick()
  105. }
  106. async function refreshSessions() {
  107. const requestedId = typeof route.params.sessionId === 'string' ? route.params.sessionId : ''
  108. const profile = routeProfile() || (requestedId ? await findLegacySessionProfile(requestedId) : auth.activeProfile?.name || '')
  109. if (profile && auth.activeProfile?.name !== profile) {
  110. if (requestedId) await router.replace(sessionLocation(requestedId, profile))
  111. await ensureRouteProfile(profile)
  112. }
  113. // The session route is the authoritative navigation target. A secondary
  114. // unread-count request must never prevent its history from being restored.
  115. await chat.loadSessions(profile)
  116. if (requestedId && chat.activeSessionId !== requestedId) await chat.selectSession(requestedId, profile)
  117. if (requestedId && profile && routeProfile() !== profile) await router.replace(sessionLocation(requestedId, profile))
  118. void chat.loadUnread(profile).catch(() => undefined)
  119. }
  120. async function chooseSession(id: string) {
  121. const session = chat.sessions.find(item => item.id === id)
  122. const profile = session?.profile || auth.activeProfile?.name || 'default'
  123. await router.push(sessionLocation(id, profile))
  124. await ensureRouteProfile(profile)
  125. if (chat.activeProfileName !== profile) await chat.loadSessions(profile)
  126. await chat.selectSession(id, profile)
  127. await chat.markRead(id, profile)
  128. quoted.value = null
  129. }
  130. async function createSession() {
  131. const id = chat.createSession(auth.activeProfile?.name)
  132. await router.push(sessionLocation(id, auth.activeProfile?.name || 'default'))
  133. }
  134. async function send(payload: ComposerSubmit) {
  135. try {
  136. await chat.send(payload.text, payload.files, queueMode.value ? 'queue' : chat.isStreaming ? 'steer' : 'submit')
  137. composer.value?.clearAfterSend()
  138. } catch { /* store exposes the error and the composer keeps its draft */ }
  139. }
  140. function openAttachment(attachment: NonNullable<UiMessage['attachments']>[number]) {
  141. const item = previewItemFromUrl(attachment.name, attachment.url || '', attachment.id, attachment.kind)
  142. item.size = attachment.size
  143. if (item.kind === 'image' || item.kind === 'video') openMedia(item)
  144. else preview.value = item
  145. }
  146. function openMedia(item: UiLibraryItem) {
  147. const index = lightboxMedia.value.findIndex(media => media.url === (item.previewUrl || item.downloadUrl))
  148. mediaPreviewIndex.value = index >= 0 ? index : null
  149. }
  150. function openLocalFile({ name, url }: { name: string; url: string }) {
  151. const item = previewItemFromUrl(name, url)
  152. if (item.kind === 'image' || item.kind === 'video') openMedia(item)
  153. else filePreview.value = item
  154. }
  155. async function addPreviewToComposer(item: UiLibraryItem) {
  156. const file = await loadComposerFile(item)
  157. if (!file || !composer.value) return
  158. composer.value.attachFiles([file])
  159. preview.value = null
  160. filePreview.value = null
  161. mediaPreviewIndex.value = null
  162. await nextTick()
  163. composer.value?.focus()
  164. }
  165. async function addMediaToComposer(media: PreviewMedia) {
  166. await addPreviewToComposer(previewItemFromUrl(media.name, media.url, `preview:${media.url}`, media.type))
  167. }
  168. async function selectModel(id: string) {
  169. const [provider, ...rest] = id.split(':')
  170. const model = chat.models.find(item => item.provider === provider && item.id === rest.join(':'))
  171. if (model) await chat.setModel(model)
  172. modelDialog.value = false
  173. }
  174. function selectReasoning(id: string) {
  175. chat.reasoningEffort = id || undefined
  176. }
  177. function openSessionActions(id: string) {
  178. actionSessionId.value = id
  179. const session = chat.sessions.find(item => item.id === id)
  180. renameValue.value = session?.title || ''
  181. renaming.value = false
  182. }
  183. async function saveRename() {
  184. const session = chat.sessions.find(item => item.id === actionSessionId.value)
  185. if (!session || !renameValue.value.trim()) return
  186. await chat.renameSession(session.id, renameValue.value.trim(), session.profile)
  187. actionSessionId.value = ''
  188. }
  189. async function deleteSession() {
  190. const session = chat.sessions.find(item => item.id === actionSessionId.value)
  191. if (!session) return
  192. await chat.removeSession(session.id, session.profile)
  193. actionSessionId.value = ''
  194. if (route.params.sessionId === session.id) await router.replace('/chat')
  195. }
  196. async function branch() {
  197. const id = await chat.branchSession()
  198. if (id) await router.push(sessionLocation(id, chat.activeProfileName || auth.activeProfile?.name || 'default'))
  199. }
  200. async function revealSourceMessage() {
  201. const messageId = typeof route.query.message === 'string' ? route.query.message : ''
  202. if (!messageId) return
  203. await nextTick()
  204. for (let attempt = 0; attempt < 10; attempt += 1) {
  205. if (timeline.value?.scrollToMessage(messageId)) return
  206. if (!chat.hasMoreBefore) return
  207. await chat.loadOlder()
  208. await nextTick()
  209. }
  210. }
  211. onMounted(async () => {
  212. await refreshSessions()
  213. await Promise.allSettled([chat.loadModels(auth.activeProfile?.name), chat.connect()])
  214. await revealSourceMessage()
  215. const pendingFile = await consumeLibraryItemForComposer()
  216. if (pendingFile) composer.value?.attachFiles([pendingFile])
  217. })
  218. onBeforeUnmount(() => chat.disconnect())
  219. watch(() => auth.activeProfile?.name, async (profile, previous) => {
  220. if (!profile || profile === previous) return
  221. if (restoringRouteProfile.value === profile) {
  222. restoringRouteProfile.value = ''
  223. return
  224. }
  225. chat.switchProfile(profile)
  226. const requestedId = typeof route.params.sessionId === 'string' ? route.params.sessionId : ''
  227. if (requestedId && routeProfile() === profile) {
  228. await Promise.allSettled([chat.loadSessions(profile), chat.loadModels(profile), chat.loadUnread(profile), chat.connect()])
  229. await chat.selectSession(requestedId, profile)
  230. return
  231. }
  232. await router.replace({ path: '/chat', query: { profile } })
  233. await Promise.allSettled([chat.loadSessions(profile), chat.loadModels(profile), chat.loadUnread(profile), chat.connect()])
  234. })
  235. watch(() => chat.activeSessionId, async id => {
  236. const profile = chat.activeProfileName || auth.activeProfile?.name || ''
  237. if (!id || (route.params.sessionId === id && routeProfile() === profile)) return
  238. await router.replace(sessionLocation(id, profile))
  239. })
  240. </script>
  241. <template>
  242. <WorkspaceView sidebar-title="对话" :sidebar-subtitle="`${sessions.length} 个会话`" :inspector-open="!!preview" @close-inspector="preview = null">
  243. <template #sidebar-action>
  244. <button class="sidebar-primary-action" type="button" title="新建聊天" aria-label="新建聊天" @click="createSession">
  245. <YaoYaoSidebarIcon name="add" />
  246. <span>新建聊天</span>
  247. </button>
  248. </template>
  249. <template #sidebar>
  250. <ResourceSidebar
  251. :items="sidebarItems"
  252. :active-id="chat.activeSessionId"
  253. :loading="chat.isLoading"
  254. :search="search"
  255. single-line
  256. :has-more="chat.hasMoreSessions"
  257. :loading-more="chat.isLoadingMoreSessions"
  258. search-placeholder="搜索会话"
  259. empty-title="还没有会话"
  260. empty-description="新建会话后,从输入框开始聊天。"
  261. @search="search = $event"
  262. @load-more="chat.loadMoreSessions(auth.activeProfile?.name)"
  263. @select="chooseSession"
  264. @more="openSessionActions"
  265. />
  266. </template>
  267. <div class="chat-workspace">
  268. <MessageTimeline
  269. ref="timeline"
  270. :messages="messages"
  271. :title="activeSession?.title || '新会话'"
  272. :subtitle="activeSession ? `${activeSession.profile || auth.activeProfile?.name || ''} · ${activeSession.model || chat.selectedModel?.name || '默认模型'}` : '选择会话或直接开始输入'"
  273. :loading="chat.activeRouteState?.isLoadingHistory || chat.isLoading"
  274. :loading-older="chat.activeRouteState?.isLoadingHistory"
  275. :has-older="chat.hasMoreBefore"
  276. :connected="connected"
  277. :synced="chat.historySynced"
  278. :show-tools="showTools"
  279. :show-assistant-identity="false"
  280. :interaction="interaction"
  281. empty-logo
  282. transparent-header
  283. :fork-source-title="forkSourceTitle"
  284. @load-older="chat.loadOlder"
  285. @quote="quoted = $event"
  286. @branch="branch"
  287. @preview="openAttachment"
  288. @preview-file="openLocalFile"
  289. @approve="interaction && chat.respondToApproval(interaction.id, $event)"
  290. @clarify="interaction && chat.respondToClarification(interaction.id, $event)"
  291. >
  292. <template #header-actions>
  293. <button v-if="activeSession" class="icon-button header-session-menu" type="button" title="会话操作" aria-label="会话操作" @click="openSessionActions(activeSession.id)"><AppIcon name="dots" :size="18" /></button>
  294. </template>
  295. </MessageTimeline>
  296. <p v-if="chat.error" class="chat-error" role="alert"><AppIcon name="alert" :size="13" />{{ chat.error }}</p>
  297. <ComposerShell
  298. ref="composer"
  299. mode="chat"
  300. :draft-key="`${auth.user?.id || 'local'}:${auth.activeProfile?.name || 'default'}:${chat.activeSessionId || 'new'}`"
  301. :disabled="chat.connectionState === 'failed'"
  302. :streaming="chat.isStreaming"
  303. :sending="chat.isSending"
  304. :model-label="chat.selectedModel?.name || '选择模型'"
  305. :reasoning-effort="reasoningLabel"
  306. :reasoning-value="chat.reasoningEffort || ''"
  307. :reasoning-options="reasoningComposerOptions"
  308. :context-used="chat.contextUsage?.contextTokens || chat.contextUsage?.totalTokens || 0"
  309. :context-limit="chat.contextUsage?.contextLimit || 262144"
  310. :queue-mode="queueMode || chat.isQueued"
  311. :tool-trace-visible="showTools"
  312. :reference="reference"
  313. :slash-commands="[
  314. { id: 'fork', label: 'fork', detail: '从当前会话创建分支' },
  315. { id: 'compact', label: 'compact', detail: '压缩当前会话上下文' },
  316. { id: 'model', label: 'model', detail: '切换模型' },
  317. ]"
  318. @send="send"
  319. @stop="chat.interrupt"
  320. @model-click="modelDialog = true"
  321. @reasoning-change="selectReasoning"
  322. @settings-click="showTools = !showTools"
  323. @queue-toggle="queueMode = !queueMode"
  324. @clear-reference="quoted = null"
  325. />
  326. </div>
  327. <template #inspector><PreviewInspector v-if="preview" :item="preview" @close="preview = null" @add-to-composer="addPreviewToComposer" /></template>
  328. </WorkspaceView>
  329. <PreviewModal v-if="filePreview" :item="filePreview" :items="conversationMediaItems" @close="filePreview = null" @add-to-composer="addPreviewToComposer" @source="filePreview = null" />
  330. <ImagePreviewLightbox v-model="mediaPreviewIndex" :images="lightboxMedia" @add="addMediaToComposer" />
  331. <ChoiceDialog :open="modelDialog" title="选择模型" :options="modelOptions" :selected-id="selectedModelId" @close="modelDialog = false" @select="selectModel" />
  332. <Teleport to="body">
  333. <Transition name="choice-fade">
  334. <div v-if="actionSessionId" class="session-action-layer" @mousedown.self="actionSessionId = ''">
  335. <section class="session-actions" role="dialog" aria-modal="true" aria-label="会话操作">
  336. <header><strong>会话操作</strong><button class="icon-button" type="button" aria-label="关闭" @click="actionSessionId = ''"><AppIcon name="close" /></button></header>
  337. <template v-if="renaming">
  338. <label>会话名称<input v-model="renameValue" maxlength="120" autofocus @keydown.enter="saveRename" /></label>
  339. <div><button class="quiet-button" type="button" @click="renaming = false">取消</button><button class="solid-button" type="button" @click="saveRename">保存</button></div>
  340. </template>
  341. <template v-else>
  342. <button class="action-row" type="button" @click="renaming = true"><AppIcon name="edit" :size="15" />重命名</button>
  343. <button class="action-row danger" type="button" @click="deleteSession"><AppIcon name="trash" :size="15" />删除会话</button>
  344. </template>
  345. </section>
  346. </div>
  347. </Transition>
  348. </Teleport>
  349. </template>
  350. <style scoped>
  351. .chat-workspace { display: flex; min-width: 0; min-height: 0; flex: 1; flex-direction: column; }
  352. .sidebar-primary-action { display: flex; width: 100%; min-height: 40px; align-items: center; gap: 10px; padding: 0 11px; border: 0; border-radius: 9px; background: transparent; color: var(--text-primary); cursor: pointer; font-size: 12px; font-weight: 610; text-align: left; transition: background-color 120ms ease; }
  353. .sidebar-primary-action:hover, .sidebar-primary-action:focus-visible { background: var(--surface-hover); outline: 0; }
  354. .sidebar-primary-action:focus-visible { box-shadow: inset 0 0 0 1px var(--line-strong); }
  355. .header-session-menu { color: var(--text-muted); background: transparent; }.header-session-menu:hover { color: var(--text-primary); background: var(--surface-soft); }
  356. .chat-error { display: flex; width: min(760px, calc(100% - 32px)); margin: 0 auto 4px; align-items: center; gap: 6px; color: var(--danger); font-size: 9px; }
  357. .session-action-layer { position: fixed; z-index: 205; inset: 0; display: grid; place-items: center; padding: 18px; background: var(--scrim); backdrop-filter: blur(4px); }
  358. .session-actions { width: min(340px, 100%); padding: 12px; border: 1px solid var(--line); border-radius: 15px; background: var(--surface-raised); box-shadow: var(--shadow-float); }.session-actions header { display: flex; min-height: 40px; align-items: center; justify-content: space-between; padding: 0 2px 7px 7px; }.session-actions header strong { font-size: 13px; }.action-row { display: flex; width: 100%; min-height: 42px; align-items: center; gap: 9px; padding: 0 9px; border: 0; border-radius: 9px; background: transparent; color: var(--text-secondary); cursor: pointer; text-align: left; }.action-row:hover { background: var(--surface-soft); color: var(--text-primary); }.action-row.danger { color: var(--danger); }.session-actions label { display: flex; flex-direction: column; gap: 6px; color: var(--text-muted); font-size: 10px; }.session-actions input { height: 38px; padding: 0 9px; border: 1px solid var(--line); border-radius: 9px; outline: 0; background: var(--surface-soft); color: var(--text-primary); }.session-actions input:focus { border-color: var(--line-strong); }.session-actions > div { display: flex; justify-content: flex-end; gap: 7px; margin-top: 13px; }
  359. @media (max-width: 600px) { .session-action-layer { place-items: end center; padding: 0; }.session-actions { width: 100%; border-radius: 17px 17px 0 0; padding-bottom: max(12px, env(safe-area-inset-bottom)); } }
  360. @media (prefers-reduced-motion: reduce) { .sidebar-primary-action { transition: none; } }
  361. </style>