ConversationsView.vue 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. <script setup lang="ts">
  2. import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
  3. import { useRoute, useRouter } from 'vue-router'
  4. import WorkspaceShell from '@/components/app/WorkspaceShell.vue'
  5. import ConversationList from '@/components/workspace/ConversationList.vue'
  6. import FloatingResourceSearch from '@/components/app/FloatingResourceSearch.vue'
  7. import type { SidebarItem } from '@/components/app/types'
  8. import AgentAvatar from '@/components/common/AgentAvatar.vue'
  9. import { createUuid } from '@/utils/id'
  10. import MessageTimeline from '@/components/messages/MessageTimeline.vue'
  11. import ComposerShell from '@/components/composer/ComposerShell.vue'
  12. import type { ComposerSubmit, ComposerReference } from '@/components/composer/types'
  13. import PreviewModal from '@/components/library/PreviewModal.vue'
  14. import ImagePreviewLightbox from '@/components/library/ImagePreviewLightbox.vue'
  15. import { previewItemFromUrl, mediaItemsFromMessages } from '@/components/library/mediaSequence'
  16. import type { UiLibraryItem } from '@/components/library/types'
  17. import type { UiMessage } from '@/components/messages/types'
  18. import AgentIdentityPanel from '@/components/app/AgentIdentityPanel.vue'
  19. import TeamAvatar from '@/components/common/TeamAvatar.vue'
  20. import TeamPresetPicker from '@/components/workspace/TeamPresetPicker.vue'
  21. import { TEAM_PRESETS, type TeamPreset } from '@/components/groups/teamPresets'
  22. import type { WorkspaceMemberRole } from '@shared/workspace'
  23. import AppIcon from '@/components/common/AppIcon.vue'
  24. import { workspaceAvatarMembers, workspaceAvatarState, workspaceConversationItem, workspaceMessagesToUi } from '@/components/workspace/viewModels'
  25. import { useAuthStore } from '@/stores/auth'
  26. import { useThemeStore } from '@/stores/theme'
  27. import { apiRequest } from '@/api/client'
  28. import type { JsonValue } from '@shared/types'
  29. import type {
  30. WorkspaceAgent as Agent,
  31. WorkspaceConversation as Conversation,
  32. WorkspaceMessage as Message,
  33. WorkspaceRun as Run,
  34. WorkspaceInteraction as Interaction,
  35. WorkspaceSource as Source,
  36. WorkspaceFile,
  37. WorkspaceEvent,
  38. } from '@shared/workspace'
  39. const auth = useAuthStore(),
  40. theme = useThemeStore(),
  41. route = useRoute(),
  42. router = useRouter()
  43. const agents = ref<Agent[]>([]),
  44. conversations = ref<Conversation[]>([]),
  45. messages = ref<Message[]>([]),
  46. sources = ref<Source[]>([])
  47. const active = ref<Conversation>(),
  48. run = ref<Run | null>(null),
  49. interactions = ref<Interaction[]>([]),
  50. context = ref<Record<string, unknown> | null>(null)
  51. const text = ref(''),
  52. error = ref(''),
  53. busy = ref(false),
  54. loading = ref(false),
  55. files = ref<WorkspaceFile[]>([]),
  56. mentions = ref<string[]>([]),
  57. older = ref(true)
  58. const searchItems = computed<SidebarItem[]>(() => [false, true].map(archived => {
  59. const items = conversations.value.filter(c => c.archived === archived).map(c => workspaceConversationItem(c, agents.value))
  60. return { id: archived ? 'archived' : 'unarchived', title: archived ? '已归档' : '未归档', children: items, emptyText: archived ? '没有已归档聊天' : '没有未归档聊天' }
  61. }))
  62. const composer = ref<InstanceType<typeof ComposerShell>>()
  63. const timeline = ref<InstanceType<typeof MessageTimeline>>()
  64. const quoted = ref<UiMessage | null>(null)
  65. const preview = ref<UiLibraryItem | null>(null)
  66. const mediaIndex = ref<number | null>(null)
  67. const showThinking = ref(true)
  68. const uiMessages = computed(() => workspaceMessagesToUi(messages.value))
  69. const media = computed(() => mediaItemsFromMessages(uiMessages.value))
  70. const lightboxMedia = computed(() => media.value.filter(item => item.kind === 'image' || item.kind === 'video').map(item => ({ url: item.previewUrl || item.downloadUrl || '', name: item.name, type: item.kind as 'image' | 'video' })))
  71. const reference = computed<ComposerReference | null>(() => quoted.value ? { id: quoted.value.id, content: quoted.value.content, author: quoted.value.author } : null)
  72. const avatarProfile = computed(() => ({ name: editingId.value || 'Agent', displayName: form.name || 'Agent', agentName: form.name || 'Agent', agentAvatar: form.avatar, isDefault: false, isRunning: true }))
  73. function openPreview(file: {name: string; url?: string; kind?: string}) {
  74. const item = previewItemFromUrl(file.name, file.url || '')
  75. const index = lightboxMedia.value.findIndex(m => m.url === (item.previewUrl || item.downloadUrl))
  76. if (index >= 0) mediaIndex.value = index
  77. else preview.value = item
  78. }
  79. let uploadedSources: File[] = [], uploadedReferences: WorkspaceFile[] = []
  80. async function sendFromComposer(payload: ComposerSubmit) {
  81. text.value = quoted.value ? `> ${(quoted.value.author || '我')}: ${quoted.value.content.replace(/\n/g, '\n> ')}\n\n${payload.text}` : payload.text
  82. mentions.value = payload.mentionIds
  83. if (payload.files.length) {
  84. try {
  85. busy.value = true
  86. if (payload.files.length === uploadedSources.length && payload.files.every((f, i) => f === uploadedSources[i])) files.value = uploadedReferences
  87. else {
  88. const data = new FormData()
  89. for (const file of payload.files) data.append('files', file)
  90. files.value = (await apiRequest<{ files: WorkspaceFile[] }>('/api/app/uploads', {method: 'POST', body: data})).files
  91. uploadedSources = [...payload.files]
  92. uploadedReferences = [...files.value]
  93. }
  94. } catch (cause) { error.value = cause instanceof Error ? cause.message : '上传失败'; return }
  95. finally { busy.value = false }
  96. }
  97. if (!payload.files.length) files.value = []
  98. if (await send()) { composer.value?.clearAfterSend(); quoted.value = null; uploadedSources = []; uploadedReferences = [] }
  99. }
  100. const dialog = ref<'agent' | 'group' | 'editAgent' | 'editGroup' | null>(null),
  101. editingId = ref(''),
  102. scroller = ref<HTMLElement>(),
  103. fileInput = ref<HTMLInputElement>(),
  104. dialogElement = ref<HTMLDialogElement>()
  105. const form = reactive({
  106. name: '',
  107. avatar: '',
  108. instructions: '',
  109. source: '',
  110. memberIds: [] as string[],
  111. memberRoles: {} as Record<string, WorkspaceMemberRole>,
  112. administratorId: '',
  113. mode: 'host' as 'host' | 'free',
  114. autoReplyIds: [] as string[],
  115. maxReplyRounds: 3,
  116. })
  117. const selectedPresetId = ref('custom')
  118. const selectedPreset = computed(() => dialog.value === 'group' ? TEAM_PRESETS.find(p => p.id === selectedPresetId.value) : undefined)
  119. function applyPresetRoles(preset: TeamPreset) {
  120. form.memberRoles = Object.fromEntries(preset.roles.flatMap((role, index) => {
  121. const id = form.memberIds[index]
  122. return id ? [[id, { name: role.name, description: role.description }]] : []
  123. }))
  124. form.administratorId = form.memberIds[Math.max(0, preset.roles.findIndex(role => role.host))] ?? ''
  125. }
  126. function choosePreset(preset?: TeamPreset) {
  127. const available = agents.value.filter(a => !a.archived)
  128. if (preset && available.length < preset.roles.length) return
  129. selectedPresetId.value = preset?.id ?? 'custom'
  130. Object.assign(form, { name: preset?.name ?? '', instructions: preset?.instructions ?? '', memberIds: preset ? available.slice(0, preset.roles.length).map(a => a.id) : [], memberRoles: {}, administratorId: '', mode: 'host', autoReplyIds: [], maxReplyRounds: 3 })
  131. if (preset) applyPresetRoles(preset)
  132. }
  133. function assignPresetRole(index: number, id: string) {
  134. if (!selectedPreset.value) return
  135. const next = [...form.memberIds], previous = next[index], occupied = next.indexOf(id)
  136. next[index] = id
  137. if (occupied >= 0 && occupied !== index && previous) next[occupied] = previous
  138. form.memberIds = next
  139. applyPresetRoles(selectedPreset.value)
  140. }
  141. const answers = reactive<Record<string, string>>({})
  142. let cursor = 0,
  143. disposed = false,
  144. timer: ReturnType<typeof setTimeout> | undefined,
  145. generation = 0,
  146. pendingRequestId: string | undefined,
  147. pendingFingerprint = ''
  148. const selected = computed(() => (typeof route.params.id === 'string' ? route.params.id : undefined))
  149. const members = computed(() => agents.value.filter((a) => active.value?.memberIds.includes(a.id)))
  150. const isAgentDialog = computed(() => dialog.value === 'agent' || dialog.value === 'editAgent')
  151. const body = (v: unknown) => v as JsonValue
  152. async function refresh() {
  153. const [a, c] = await Promise.all([
  154. apiRequest<{ agents: Agent[] }>('/api/app/agents'),
  155. apiRequest<{ conversations: Conversation[]; cursor: number }>('/api/app/conversations'),
  156. ])
  157. if (disposed) return
  158. agents.value = a.agents
  159. conversations.value = c.conversations
  160. if (!cursor) cursor = c.cursor
  161. }
  162. async function load(id = selected.value, append = false) {
  163. if (!id) {
  164. generation++
  165. active.value = undefined
  166. messages.value = []
  167. run.value = null
  168. interactions.value = []
  169. context.value = null
  170. return
  171. }
  172. const own = ++generation
  173. if (!append) loading.value = true
  174. try {
  175. const r = await apiRequest<{
  176. conversation: Conversation
  177. messages: Message[]
  178. run: Run | null
  179. interactions: Interaction[]
  180. context: Record<string, unknown> | null
  181. hiddenMessageIds?: string[]
  182. }>(`/api/app/conversations/${id}`)
  183. if (disposed || own !== generation) return
  184. const atBottom = timeline.value?.isFollowingBottom() ?? true
  185. active.value = r.conversation
  186. messages.value = append
  187. ? [...new Map([...messages.value, ...r.messages].map((m) => [m.id, m])).values()].sort(
  188. (a, b) => a.seq - b.seq,
  189. )
  190. : r.messages
  191. messages.value = messages.value.filter(m => m.visible !== false && !r.hiddenMessageIds?.includes(m.id))
  192. run.value = r.run
  193. interactions.value = r.interactions
  194. context.value = r.context
  195. if (!append) older.value = r.messages.length === 100
  196. if (!append || atBottom) {
  197. await nextTick()
  198. if (!append) timeline.value?.scrollToBottom('auto')
  199. await markRead()
  200. }
  201. } catch (e) {
  202. error.value = e instanceof Error ? e.message : '加载失败'
  203. } finally {
  204. if (own === generation) loading.value = false
  205. }
  206. }
  207. async function markRead() {
  208. const c = active.value
  209. if (!c || c.readSeq >= c.lastSeq) return
  210. await apiRequest(`/api/app/conversations/${c.id}/read`, {
  211. method: 'PUT',
  212. body: { seq: c.lastSeq },
  213. })
  214. c.readSeq = c.lastSeq
  215. }
  216. async function poll() {
  217. try {
  218. const r = await apiRequest<{ events: WorkspaceEvent[]; cursor: number }>(
  219. `/api/app/events?after=${cursor}`,
  220. )
  221. if (disposed) return
  222. cursor = r.cursor
  223. if (r.events.length) {
  224. await refresh()
  225. if (r.events.some((e) => e.conversationId === selected.value || e.type === 'agent.changed'))
  226. await load(selected.value, true)
  227. }
  228. } catch (e) {
  229. if (!disposed) error.value = e instanceof Error ? e.message : '连接中断,正在重连'
  230. } finally {
  231. if (!disposed) timer = setTimeout(() => void poll(), 1200)
  232. }
  233. }
  234. async function select(id: string) {
  235. error.value = ''
  236. files.value = []
  237. mentions.value = []
  238. text.value = ''
  239. quoted.value = null
  240. preview.value = null
  241. mediaIndex.value = null
  242. pendingRequestId = undefined
  243. await router.push(`/conversations/${id}`)
  244. }
  245. async function openDialog(kind: NonNullable<typeof dialog.value>) {
  246. error.value = ''
  247. dialog.value = kind
  248. editingId.value = ''
  249. selectedPresetId.value = 'custom'
  250. Object.assign(form, {
  251. name: '',
  252. avatar: '',
  253. instructions: '',
  254. source: '',
  255. memberIds: [],
  256. memberRoles: {},
  257. administratorId: '',
  258. mode: 'host',
  259. autoReplyIds: [],
  260. maxReplyRounds: 3,
  261. })
  262. try {
  263. if (kind === 'agent') {
  264. const s = await apiRequest<{ sources: Source[] }>('/api/app/agents/sources')
  265. sources.value = s.sources
  266. form.source = s.sources[0] ? JSON.stringify([s.sources[0].nodeId, s.sources[0].profile]) : ''
  267. }
  268. if (kind === 'editAgent') {
  269. const a = members.value[0]
  270. if (!a) return
  271. editingId.value = a.id
  272. Object.assign(form, a)
  273. }
  274. if (kind === 'editGroup' && active.value) {
  275. editingId.value = active.value.id
  276. Object.assign(form, active.value, {
  277. memberIds: [...active.value.memberIds],
  278. autoReplyIds: [...active.value.autoReplyIds],
  279. memberRoles: Object.fromEntries(Object.entries(active.value.memberRoles ?? {}).map(([id, role]) => [id, { ...role }])),
  280. })
  281. }
  282. await nextTick()
  283. dialogElement.value?.showModal()
  284. } catch (e) {
  285. error.value = String(e)
  286. dialog.value = null
  287. }
  288. }
  289. function closeDialog() {
  290. dialogElement.value?.close()
  291. dialog.value = null
  292. }
  293. watch(
  294. () => form.memberIds.slice(),
  295. (ids) => {
  296. if (!ids.includes(form.administratorId)) form.administratorId = ids[0] ?? ''
  297. form.autoReplyIds = form.autoReplyIds.filter((id) => ids.includes(id))
  298. form.memberRoles = Object.fromEntries(Object.entries(form.memberRoles).filter(([id]) => ids.includes(id)))
  299. },
  300. )
  301. async function save() {
  302. busy.value = true
  303. error.value = ''
  304. try {
  305. const fields = { name: form.name, ...(isAgentDialog.value ? { avatar: form.avatar } : {}), instructions: form.instructions }
  306. if (dialog.value === 'agent') {
  307. const [nodeId, profile] = JSON.parse(form.source)
  308. const result = await apiRequest<{ agent: Agent }>('/api/app/agents', {
  309. method: 'POST',
  310. body: { ...fields, nodeId, profile },
  311. })
  312. await refresh()
  313. const c = conversations.value.find(
  314. (c) => c.kind === 'direct' && c.memberIds[0] === result.agent.id,
  315. )
  316. if (c) await select(c.id)
  317. } else if (dialog.value === 'editAgent')
  318. await apiRequest(`/api/app/agents/${editingId.value}`, { method: 'PATCH', body: fields })
  319. else {
  320. const payload = {
  321. ...fields,
  322. administratorId: form.administratorId,
  323. mode: form.mode,
  324. autoReplyIds: form.autoReplyIds,
  325. maxReplyRounds: form.maxReplyRounds,
  326. memberIds: form.memberIds,
  327. memberRoles: form.memberRoles,
  328. }
  329. const result = await apiRequest<{ conversation: Conversation }>(
  330. dialog.value === 'group'
  331. ? '/api/app/conversations'
  332. : `/api/app/conversations/${editingId.value}`,
  333. { method: dialog.value === 'group' ? 'POST' : 'PATCH', body: body(payload) },
  334. )
  335. await select(result.conversation.id)
  336. }
  337. closeDialog()
  338. await refresh()
  339. await load()
  340. } catch (e) {
  341. error.value = e instanceof Error ? e.message : '保存失败'
  342. } finally {
  343. busy.value = false
  344. }
  345. }
  346. async function upload(event: Event) {
  347. const picked = (event.target as HTMLInputElement).files
  348. if (!picked?.length) return
  349. busy.value = true
  350. error.value = ''
  351. try {
  352. const data = new FormData()
  353. for (const file of picked) data.append('files', file)
  354. const r = await apiRequest<{ files: WorkspaceFile[] }>('/api/app/uploads', {
  355. method: 'POST',
  356. body: data,
  357. })
  358. files.value = [...files.value, ...r.files].slice(0, 8)
  359. } catch (e) {
  360. error.value = String(e)
  361. } finally {
  362. busy.value = false
  363. ;(event.target as HTMLInputElement).value = ''
  364. }
  365. }
  366. async function send() {
  367. const c = active.value
  368. if (!c || busy.value || (!text.value.trim() && !files.value.length)) return
  369. busy.value = true
  370. error.value = ''
  371. const fingerprint = JSON.stringify([c.id, text.value, mentions.value, files.value.map(f => f.id)])
  372. if (!pendingRequestId || pendingFingerprint !== fingerprint) {
  373. pendingRequestId = createUuid()
  374. pendingFingerprint = fingerprint
  375. }
  376. try {
  377. await apiRequest(`/api/app/conversations/${c.id}/messages`, {
  378. method: 'POST',
  379. body: {
  380. requestId: pendingRequestId,
  381. content: text.value,
  382. mentionIds: mentions.value,
  383. fileIds: files.value.map((f) => f.id),
  384. },
  385. })
  386. text.value = ''
  387. files.value = []
  388. mentions.value = []
  389. pendingRequestId = undefined
  390. pendingFingerprint = ''
  391. await load(c.id, true)
  392. await refresh()
  393. return true
  394. } catch (e) {
  395. error.value = e instanceof Error ? e.message : '发送失败'
  396. } finally {
  397. busy.value = false
  398. }
  399. }
  400. async function action(operation: 'pin' | 'archive', id = active.value?.id) {
  401. const c = conversations.value.find(c => c.id === id)
  402. if (!c) return
  403. try {
  404. if (operation === 'pin')
  405. await apiRequest(`/api/app/conversations/${c.id}`, {
  406. method: 'PATCH',
  407. body: { pinned: !c.pinned },
  408. })
  409. else
  410. await apiRequest(
  411. c.kind === 'direct'
  412. ? `/api/app/agents/${c.memberIds[0]}`
  413. : `/api/app/conversations/${c.id}`,
  414. { method: 'PATCH', body: { archived: !c.archived } },
  415. )
  416. await refresh()
  417. await load()
  418. } catch (e) {
  419. error.value = String(e)
  420. }
  421. }
  422. async function stopMember(id: string) {
  423. if (!active.value) return
  424. try {
  425. await apiRequest(`/api/app/conversations/${active.value.id}/agents/${id}/stop`, { method: 'POST', body: {} })
  426. await load(); await refresh()
  427. } catch (cause) { error.value = cause instanceof Error ? cause.message : '停止失败' }
  428. }
  429. async function control(action: 'stop' | 'reconcile') {
  430. if (!run.value) return
  431. try {
  432. await apiRequest(`/api/app/runs/${run.value.id}/${action}`, { method: 'POST', body: {} })
  433. await load(undefined, true)
  434. } catch (e) {
  435. error.value = String(e)
  436. }
  437. }
  438. async function respond(i: Interaction, answer: string) {
  439. try {
  440. await apiRequest(`/api/app/interactions/${i.id}/respond`, { method: 'POST', body: { answer } })
  441. await load(undefined, true)
  442. } catch (e) {
  443. error.value = String(e)
  444. }
  445. }
  446. async function loadOlder() {
  447. const c = active.value
  448. if (!c) return
  449. try {
  450. const r = await apiRequest<{ messages: Message[] }>(
  451. `/api/app/conversations/${c.id}/messages?before=${messages.value[0]?.seq ?? 0}`,
  452. )
  453. messages.value = [...r.messages, ...messages.value]
  454. older.value = r.messages.length === 100
  455. } catch (e) {
  456. error.value = String(e)
  457. }
  458. }
  459. function rendered(m: Message) {
  460. return m.content.replace(
  461. /(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g,
  462. (whole, label: string, path: string) => {
  463. const file =
  464. m.attachments.find((f) => f.sourcePath === path) ||
  465. m.attachments.find((f) => path.split('/').at(-1) === f.name)
  466. return file
  467. ? `${label}(/api/app/files/${file.id}/${label.startsWith('!') ? 'preview' : 'download'})`
  468. : whole
  469. },
  470. )
  471. }
  472. watch(selected, () => void load())
  473. onMounted(async () => {
  474. try {
  475. await apiRequest('/api/app/capabilities')
  476. await refresh()
  477. await load()
  478. if (!disposed) void poll()
  479. } catch (e) {
  480. error.value = String(e)
  481. }
  482. })
  483. onBeforeUnmount(() => {
  484. disposed = true
  485. generation++
  486. if (timer) clearTimeout(timer)
  487. })
  488. </script>
  489. <template>
  490. <WorkspaceShell
  491. :user-name="auth.user?.username"
  492. :profiles="auth.profiles"
  493. :active-profile="auth.activeProfile"
  494. :is-admin="auth.user?.role === 'admin'"
  495. :upstream-ready="auth.upstreamReady"
  496. :upstream-error="auth.upstreamError"
  497. :theme="theme.resolvedTheme"
  498. :theme-preference="theme.theme"
  499. sidebar-title="聊天"
  500. sidebar-context-title="聊天列表"
  501. @logout="auth.logout"
  502. @select-profile="auth.selectProfile"
  503. @toggle-theme="theme.toggle"
  504. @set-theme="theme.setTheme"
  505. @create-agent="openDialog('agent')"
  506. @create-group="openDialog('group')"
  507. >
  508. <template #sidebar
  509. ><ConversationList :conversations="conversations" :agents="agents" :selected="selected" @select="select" @pin="action('pin', $event)" @archive="action('archive', $event)"
  510. /></template>
  511. <template #mobile-sidebar
  512. ><ConversationList :conversations="conversations" :agents="agents" :selected="selected" @select="select" @pin="action('pin', $event)" @archive="action('archive', $event)"
  513. /></template>
  514. <section class="workspace-chat" aria-label="聊天">
  515. <MessageTimeline ref="timeline" :messages="uiMessages" :title="active?.name || '团队'"
  516. :subtitle="active?.kind === 'group' ? `${members.length} 位成员` : ''"
  517. :loading="loading" :has-older="older && !!active" :connected="!error" :synced="!loading"
  518. :show-tools="showThinking" :allow-branch="false" :thinking="!!active?.activeRunId"
  519. :agent-avatars="Object.fromEntries(agents.map(a => [a.id, a.avatar]))"
  520. :agent-states="Object.fromEntries(members.map(a => [a.id, workspaceAvatarState(active, a.id)]))"
  521. :mention-names="members.map(a => a.name)"
  522. :empty-title="active ? '开始一段新对话' : '还没有聊天'"
  523. :empty-description="active ? '从下方输入框发送消息。' : '创建 Agent,或选择成员新建群聊。'"
  524. :interaction="interactions[0] ? { id: interactions[0].id, kind: interactions[0].kind, prompt: interactions[0].message, options: interactions[0].choices } : null"
  525. @load-older="loadOlder" @quote="quoted = $event" @preview="openPreview" @preview-file="openPreview"
  526. @approve="interactions[0] && respond(interactions[0], $event ? 'once' : 'deny')"
  527. @clarify="interactions[0] && respond(interactions[0], $event)">
  528. <template #header-actions>
  529. <div v-if="active" class="header-actions">
  530. <button class="icon-button" :aria-label="active.pinned ? '取消置顶' : '置顶聊天'" :title="active.pinned ? '取消置顶' : '置顶聊天'" @click="action('pin')"><AppIcon :name="active.pinned ? 'pin-off' : 'pin'" /></button>
  531. <button class="icon-button" aria-label="聊天设置" title="聊天设置" @click="openDialog(active.kind === 'direct' ? 'editAgent' : 'editGroup')"><AppIcon name="settings" /></button>
  532. <button class="icon-button" :aria-label="active.archived ? '恢复聊天' : '归档聊天'" :title="active.archived ? '恢复聊天' : '归档聊天'" @click="action('archive')"><AppIcon name="archive" /></button>
  533. </div>
  534. </template>
  535. </MessageTimeline>
  536. <p v-if="error" class="error" role="alert">{{ error }}<button class="icon-button" @click="error = ''" aria-label="关闭错误"><AppIcon name="close" /></button></p>
  537. <ComposerShell v-if="active" :key="active.id" ref="composer" mode="group" :draft-key="`${auth.user?.id}:${active.id}`"
  538. :disabled="active.archived || loading || active.id !== selected" :sending="busy" stop-while-running :streaming="!!active.activeRunId"
  539. :tool-trace-visible="showThinking" :reference="reference" :context-used="Number(context?.usedTokens || 0)" :context-limit="Number(context?.limitTokens || 0)"
  540. :mention-options="active.kind === 'group' ? members.map(a => ({id:a.id,label:a.name,insertText:`@${a.name} `})) : []"
  541. @send="sendFromComposer" @stop="control('stop')" @tool-trace-toggle="showThinking = !showThinking" @clear-reference="quoted = null" @error="error = $event" />
  542. </section>
  543. <FloatingResourceSearch section="groups" label="搜索聊天" :items="searchItems" tabbed @select="select" />
  544. <PreviewModal v-if="preview" :item="preview" :items="media" @close="preview = null" />
  545. <ImagePreviewLightbox v-model="mediaIndex" :images="lightboxMedia" />
  546. <dialog v-if="dialog" ref="dialogElement" class="editor" @cancel.prevent="closeDialog">
  547. <form @submit.prevent="save">
  548. <header>
  549. <h2>
  550. {{ dialog === 'agent' ? '创建 Agent' : dialog === 'group' ? '创建群聊' : '编辑资料' }}
  551. </h2>
  552. <button type="button" aria-label="关闭" @click="closeDialog">×</button>
  553. </header>
  554. <p v-if="error" class="error" role="alert">{{ error }}</p>
  555. <TeamPresetPicker v-if="dialog === 'group'" :selected="selectedPresetId" :available="agents.filter(a => !a.archived).length" @select="choosePreset" />
  556. <label>名称<input v-model="form.name" required maxlength="100" /></label>
  557. <AgentIdentityPanel v-if="isAgentDialog" :key="`${dialog}:${editingId}`" :profile="avatarProfile" embedded :show-name="false" :show-default-model="false" :show-actions="false" @avatar-change="form.avatar = $event" />
  558. <div v-else class="team-avatar-settings">
  559. <TeamAvatar :name="form.name" :members="workspaceAvatarMembers(form.memberIds, agents, dialog === 'editGroup' ? active : undefined)" :size="64" />
  560. <small>群聊头像由成员头像自动组合,随成员头像更新。</small>
  561. </div>
  562. <label
  563. v-if="dialog === 'agent'"
  564. >基础 Agent<select v-model="form.source" required>
  565. <option
  566. v-for="s in sources"
  567. :key="`${s.nodeId}:${s.profile}`"
  568. :value="JSON.stringify([s.nodeId, s.profile])"
  569. >
  570. {{ s.name }} · {{ s.nodeId === 'local' ? '当前服务' : s.nodeId }}
  571. </option></select
  572. ><small v-if="!sources.length"
  573. >没有可用的基础 Agent,请检查 Web 的 Hermes 连接。</small
  574. ></label
  575. ><label
  576. >{{ isAgentDialog ? '角色提示词与规则' : '群规则'
  577. }}<textarea
  578. v-model="form.instructions"
  579. rows="6"
  580. maxlength="24000"
  581. :placeholder="
  582. isAgentDialog
  583. ? '例如:你是代码审查员。重点检查正确性、边界情况和测试证据。'
  584. : '所有成员共同遵守的协作规则'
  585. "
  586. />
  587. </label>
  588. <fieldset v-if="selectedPreset" class="preset-role-mapping">
  589. <legend>角色分配</legend>
  590. <label v-for="(role, index) in selectedPreset.roles" :key="role.name">
  591. {{ role.name }}{{ role.host ? ' · 管理员' : '' }}
  592. <select :value="form.memberIds[index]" :aria-label="`${role.name}对应的 Agent`" @change="assignPresetRole(index, ($event.target as HTMLSelectElement).value)">
  593. <option v-for="a in agents.filter(a => !a.archived)" :key="a.id" :value="a.id">{{ a.name }}</option>
  594. </select>
  595. <small>{{ role.description }}</small>
  596. </label>
  597. <small>角色分工仅在本群生效,聊天中保留 Agent 的名称和头像。</small>
  598. </fieldset>
  599. <fieldset v-else-if="!isAgentDialog">
  600. <legend>选择成员</legend>
  601. <label
  602. v-for="a in agents.filter((a) =>
  603. !a.archived || (dialog === 'editGroup' && active?.memberIds.includes(a.id)),
  604. )"
  605. :key="a.id"
  606. ><input
  607. v-model="form.memberIds"
  608. type="checkbox"
  609. :value="a.id"
  610. :disabled="busy || (dialog === 'editGroup' && (a.id === active?.administratorId || a.id === form.administratorId)) || (!form.memberIds.includes(a.id) && form.memberIds.length >= 8)"
  611. />{{ a.name }}</label
  612. ><small v-if="dialog === 'group' && agents.filter((a) => !a.archived).length < 2"
  613. >至少需要两个 Agent 才能创建群聊。</small
  614. >
  615. <small v-if="dialog === 'editGroup'">可增减成员,最多 8 位。当前管理员不能移除;如需移除,请先更换管理员并保存。</small>
  616. <button v-for="a in agents.filter(a => active?.activeAgentStates?.[a.id])" :key="`stop:${a.id}`" type="button" @click="stopMember(a.id)">停止 {{ a.name }}</button>
  617. </fieldset>
  618. <fieldset v-if="dialog === 'editGroup' && Object.keys(form.memberRoles).length">
  619. <legend>角色分工</legend>
  620. <p v-for="(role, id) in form.memberRoles" :key="id">{{ agents.find(a => a.id === id)?.name }} · {{ role.name }}<br /><small>{{ role.description }}</small></p>
  621. </fieldset>
  622. <template v-if="!isAgentDialog"
  623. ><label
  624. >管理员<select v-model="form.administratorId" required>
  625. <option
  626. v-for="a in agents.filter((a) => form.memberIds.includes(a.id))"
  627. :key="a.id"
  628. :value="a.id"
  629. >
  630. {{ a.name }}
  631. </option>
  632. </select></label
  633. ><label
  634. >协作方式<select v-model="form.mode">
  635. <option value="host">管理员协调</option>
  636. <option value="free">自由协作</option>
  637. </select></label
  638. >
  639. <fieldset v-if="form.mode === 'free'">
  640. <legend>未 @ 时自动回复</legend>
  641. <label v-for="a in agents.filter((a) => form.memberIds.includes(a.id))" :key="a.id"
  642. ><input v-model="form.autoReplyIds" type="checkbox" :value="a.id" />{{
  643. a.name
  644. }}</label
  645. >
  646. </fieldset>
  647. <label
  648. ><input type="checkbox" :checked="form.maxReplyRounds === -1" @change="form.maxReplyRounds = ($event.target as HTMLInputElement).checked ? -1 : 3" />不限制自动协作轮数</label>
  649. <label v-if="form.maxReplyRounds !== -1">自动协作轮数<input
  650. v-model.number="form.maxReplyRounds"
  651. type="number"
  652. min="1"
  653. max="100"
  654. required /></label
  655. ></template>
  656. <footer>
  657. <button class="quiet-button" type="button" @click="closeDialog">取消</button
  658. ><button class="solid-button" :disabled="busy || (!isAgentDialog && (form.memberIds.length < (dialog === 'group' ? 2 : 1) || form.memberIds.length > 8))">
  659. {{ busy ? '保存中…' : '保存' }}
  660. </button>
  661. </footer>
  662. </form>
  663. </dialog>
  664. </WorkspaceShell>
  665. </template>
  666. <style scoped>
  667. .workspace-chat{display:flex;min-width:0;min-height:0;flex:1;flex-direction:column}.new-actions{display:grid;gap:2px}.new-actions button{display:flex;align-items:center;min-height:40px;padding:0 11px;border:0;border-radius:9px;background:transparent;color:var(--text-primary);text-align:left;font-size:12px;font-weight:610;cursor:pointer}.new-actions button:hover{background:var(--surface-hover)}.header-actions{display:flex;gap:4px;margin-left:auto}.error{display:flex;align-items:center;justify-content:space-between;margin:0 18px 9px;color:var(--danger);font-size:12px}.team-avatar-settings{display:grid;gap:12px}.team-avatar-options{display:flex;gap:10px}.team-avatar-options button{padding:5px;border:1px solid var(--line);border-radius:10px;background:var(--surface-soft);cursor:pointer}.team-avatar-options button[aria-pressed=true]{border-color:var(--accent)}.nodes-overlay{position:fixed;inset:0;z-index:1000;background:var(--scrim);display:grid;place-items:center}.nodes-overlay>div{padding:20px;max-height:85vh;overflow:auto;width:min(520px,90vw);background:var(--surface-raised);border:1px solid var(--line);border-radius:16px}
  668. .editor {
  669. border: 1px solid var(--line);
  670. border-radius: 18px;
  671. width: min(520px, calc(100vw - 48px));
  672. max-height: 85vh;
  673. overflow: auto;
  674. background: var(--surface);
  675. color: var(--text-primary);
  676. padding: 25px;
  677. }
  678. .editor::backdrop {
  679. background: #0006;
  680. }
  681. .editor header,
  682. .editor footer {
  683. display: flex;
  684. align-items: center;
  685. justify-content: space-between;
  686. gap: 12px;
  687. }
  688. .editor h2 {
  689. font-size: 20px;
  690. }
  691. .editor label {
  692. display: flex;
  693. flex-direction: column;
  694. gap: 7px;
  695. margin: 15px 0;
  696. font-size: 13px;
  697. }
  698. .editor input:not([type='checkbox']),
  699. .editor textarea,
  700. .editor select,
  701. .interaction input {
  702. padding: 10px;
  703. border: 1px solid var(--line);
  704. border-radius: 8px;
  705. background: var(--surface-soft);
  706. color: inherit;
  707. font: inherit;
  708. }
  709. .editor fieldset {
  710. border: 1px solid var(--line);
  711. border-radius: 10px;
  712. }
  713. .editor fieldset label {
  714. flex-direction: row;
  715. align-items: center;
  716. }
  717. .editor footer {
  718. justify-content: flex-end;
  719. margin-top: 25px;
  720. }
  721. .status {
  722. margin-top: 8px;
  723. }
  724. </style>