ConversationsView.vue 26 KB

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