ConversationsView.vue 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. <script setup lang="ts">
  2. import { useUnreadStore } from '@/stores/unread'
  3. import type { ComputerBackend } from '@shared/managedBrowser'
  4. import { WORKSPACE_PATCH_CAPABILITY } from '@shared/workspaceMessagePatch'
  5. import { setApiCsrfToken } from '@/api/client'
  6. import { publishServerIdentity } from '@/api/serverIdentity'
  7. import type { ServerIdentity } from '@shared/serverIdentity'
  8. import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
  9. import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router'
  10. import WorkspaceShell from '@/components/app/WorkspaceShell.vue'
  11. import ConversationList from '@/components/workspace/ConversationList.vue'
  12. import BotProfileDialog from '@/components/workspace/BotProfileDialog.vue'
  13. import WorkspaceBotPanel from '@/components/workspace/WorkspaceBotPanel.vue'
  14. import WorkspaceKnowledgePanel from '@/components/workspace/WorkspaceKnowledgePanel.vue'
  15. import type { WorkspaceProject } from '@shared/workspaceKnowledge'
  16. import LocalVmWorkspace from '@/components/workspace/LocalVmWorkspace.vue'
  17. import ComputerPanel from '@/components/workspace/ComputerPanel.vue'
  18. import TaskPlan from '@/components/workspace/TaskPlan.vue'
  19. import type { AgentAssignment } from '@shared/agentTasks'
  20. import type { WorkspaceSendReceipt, WorkspaceTask } from '@shared/workspace'
  21. import { workspaceHasUnread } from '@shared/workspace'
  22. import type { WorkspaceLifecycleAction, WorkspaceLifecyclePreview } from '@shared/workspaceLifecycle'
  23. import FloatingResourceSearch from '@/components/app/FloatingResourceSearch.vue'
  24. import type { SidebarItem } from '@/components/app/types'
  25. import AgentAvatar from '@/components/common/AgentAvatar.vue'
  26. import { createUuid } from '@/utils/id'
  27. import MessageTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
  28. import { WorkspaceTranscriptStore, transcriptKey, type WorkspaceDetail, type WorkspaceSnapshot } from '@/components/workspace/transcriptStore'
  29. import ComposerShell from '@/components/composer/ComposerShell.vue'
  30. import type { ComposerSubmit, ComposerReference } from '@/components/composer/types'
  31. import PreviewModal from '@/components/library/PreviewModal.vue'
  32. import ImagePreviewLightbox from '@/components/library/ImagePreviewLightbox.vue'
  33. import { previewItemFromUrl, mediaItemsFromMessages } from '@/components/library/mediaSequence'
  34. import type { UiLibraryItem } from '@/components/library/types'
  35. import type { UiMessage } from '@/components/messages/types'
  36. import AgentIdentityPanel from '@/components/app/AgentIdentityPanel.vue'
  37. import TeamAvatar from '@/components/common/TeamAvatar.vue'
  38. import TeamPresetPicker from '@/components/workspace/TeamPresetPicker.vue'
  39. import { TEAM_PRESETS, type TeamPreset } from '@/components/groups/teamPresets'
  40. import type { WorkspaceMemberRole } from '@shared/workspace'
  41. import AppIcon from '@/components/common/AppIcon.vue'
  42. import { workspaceAgentActivity, workspaceAvatarMembers, workspaceAvatarState, workspaceConversationItem, workspaceMessagesToUi } from '@/components/workspace/viewModels'
  43. import { useAuthStore } from '@/stores/auth'
  44. import { useThemeStore } from '@/stores/theme'
  45. import { apiRequest, ApiError } from '@/api/client'
  46. import { encodeAgentAvatar, randomAgentIdentity } from '@shared/agentIdentity'
  47. import type { JsonValue } from '@shared/types'
  48. import {
  49. type WorkspaceAgent as Agent,
  50. type WorkspaceConversation as Conversation,
  51. type WorkspaceMessage as Message,
  52. type WorkspaceRun as Run,
  53. type WorkspaceInteraction as Interaction,
  54. type WorkspaceSource as Source,
  55. type WorkspaceFile,
  56. type WorkspaceEvent,
  57. workspaceHasUnfinishedOutput,
  58. } from '@shared/workspace'
  59. const auth = useAuthStore(),
  60. theme = useThemeStore(),
  61. route = useRoute(),
  62. router = useRouter()
  63. const agents = ref<Agent[]>([]),
  64. conversations = ref<Conversation[]>([]),
  65. messages = shallowRef<Message[]>([]),
  66. sources = ref<Source[]>([])
  67. const active = ref<Conversation>(),
  68. run = ref<Run | null>(null),
  69. interactions = ref<Interaction[]>([]),
  70. context = ref<Record<string, unknown> | null>(null)
  71. const thinking = computed(() =>
  72. (!!run.value && ['queued', 'running', 'waiting', 'uncertain'].includes(run.value.status))
  73. || workspaceHasUnfinishedOutput(messages.value))
  74. const activeTask = ref<WorkspaceTask | null>(null), tasks = ref<WorkspaceTask[]>([]), assignments = ref<AgentAssignment[]>([])
  75. const deliveryMode = ref(false)
  76. const knowledgePanel = ref<InstanceType<typeof WorkspaceKnowledgePanel>>()
  77. const knowledgeRevision = ref(0)
  78. const knowledgeEnabled = ref(false), projects = ref<WorkspaceProject[]>([]), directProjectId = ref(''), requestedRounds = ref<number | undefined>(), coordinatorId = ref('')
  79. const coordinators = computed(() => members.value.filter(a => !a.temporaryGoalId && !a.archived && !a.remoteAgentId))
  80. const canRequestGoal = computed(() => active.value?.kind === 'group' && !active.value.archived && !activeTask.value?.goal
  81. && (active.value.collaborationMode === 'discussion' ? coordinators.value.length > 0 : members.value.some(a => a.id === active.value?.administratorId && !a.temporaryGoalId && !a.archived && !a.remoteAgentId)))
  82. const taskFiles = new Map<string,File[]>()
  83. const taskQuotes = new Map<string,UiMessage | null>()
  84. const composerKey = computed(() => `${auth.user?.id}:${active.value?.id}${activeTask.value ? `:${activeTask.value.id}` : ''}`)
  85. watch(composerKey, () => { deliveryMode.value = false; directProjectId.value = ''; requestedRounds.value = undefined; coordinatorId.value = '' })
  86. async function knowledgeChanged() { await refresh(); projects.value = (await apiRequest<{ projects: WorkspaceProject[] }>('/api/app/workspace/projects')).projects }
  87. const text = ref(''),
  88. error = ref(''),
  89. busy = ref(false),
  90. loading = ref(false),
  91. files = ref<WorkspaceFile[]>([]),
  92. mentions = ref<string[]>([]),
  93. older = ref(true)
  94. const respondingInteractionId = ref(''), interactionError = ref('')
  95. watch(() => `${route.params.id}:${interactions.value[0]?.id}`, () => { interactionError.value = '' })
  96. const agentActivity = computed(() => workspaceAgentActivity(conversations.value))
  97. const searchItems = computed<SidebarItem[]>(() => [false, true].map(archived => {
  98. const items = conversations.value.filter(c => c.archived === archived).map(c => workspaceConversationItem(c, agents.value, agentActivity.value))
  99. return { id: archived ? 'archived' : 'unarchived', title: archived ? '已归档' : '未归档', children: items, emptyText: archived ? '没有已归档聊天' : '没有未归档聊天' }
  100. }))
  101. const archivedIds = computed(() => new Set(conversations.value.filter(c => c.archived).map(c => c.id)))
  102. const lifecycleId = ref(''), searchActionError = ref(''), lifecycleError = ref(''), lifecycleAction = ref<WorkspaceLifecycleAction>()
  103. const composer = ref<InstanceType<typeof ComposerShell>>()
  104. const timeline = ref<InstanceType<typeof MessageTimeline>>()
  105. const quoted = ref<UiMessage | null>(null)
  106. const preview = ref<UiLibraryItem | null>(null)
  107. const mediaIndex = ref<number | null>(null)
  108. const showThinking = ref(false)
  109. const transcriptStore = new WorkspaceTranscriptStore()
  110. const renderedMessages = new WeakMap<Message, UiMessage>()
  111. const uiMessages = computed(() => messages.value.filter(m => m.visible !== false).map(message => {
  112. let rendered = renderedMessages.get(message)
  113. if (!rendered) { rendered = workspaceMessagesToUi([message])[0]!; renderedMessages.set(message, rendered) }
  114. return rendered
  115. }))
  116. const loadingOlder = ref(false)
  117. const media = computed(() => mediaItemsFromMessages(uiMessages.value))
  118. 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' })))
  119. const reference = computed<ComposerReference | null>(() => quoted.value ? { id: quoted.value.id, content: quoted.value.content, author: quoted.value.author } : null)
  120. const avatarProfile = computed(() => ({ name: editingId.value || '机器人', displayName: form.name || '机器人', agentName: form.name || '机器人', agentAvatar: form.avatar, isDefault: false, isRunning: true }))
  121. function openPreview(file: {name: string; url?: string; kind?: string}) {
  122. let path = file.url || ''
  123. try { path = decodeURIComponent(new URL(path, window.location.origin).pathname) } catch { /* preserve the supplied URL */ }
  124. const attachment = messages.value.flatMap(message => message.attachments).find(candidate =>
  125. path === candidate.sourcePath || path === `/api/app/files/${candidate.id}/download`
  126. || path === `/api/app/files/${candidate.id}/preview`)
  127. // A Markdown label such as “报告” has no extension. The archived file's name
  128. // determines its viewer; the label is not reliable file-type metadata.
  129. const mime = attachment?.mimeType.toLowerCase().split(';')[0] || ''
  130. const textual = mime.startsWith('text/') || ['application/json', 'application/xml', 'application/yaml', 'application/x-yaml'].includes(mime)
  131. const item = previewItemFromUrl(attachment?.name || file.name, file.url || '', undefined, textual ? 'text' : undefined)
  132. const index = lightboxMedia.value.findIndex(m => m.url === (item.previewUrl || item.downloadUrl))
  133. if (index >= 0) mediaIndex.value = index
  134. else preview.value = item
  135. }
  136. let uploadedSources: File[] = [], uploadedReferences: WorkspaceFile[] = []
  137. async function sendFromComposer(payload: ComposerSubmit) {
  138. const sourceComposer = composer.value, token = sourceComposer?.submissionToken()
  139. const scope = composerKey.value, ownerEpoch = accountEpoch
  140. text.value = quoted.value ? `> ${(quoted.value.author || '我')}: ${quoted.value.content.replace(/\n/g, '\n> ')}\n\n${payload.text}` : payload.text
  141. mentions.value = payload.mentionIds
  142. if (payload.files.length) {
  143. try {
  144. busy.value = true
  145. if (payload.files.length === uploadedSources.length && payload.files.every((f, i) => f === uploadedSources[i])) files.value = uploadedReferences
  146. else {
  147. const data = new FormData()
  148. for (const file of payload.files) data.append('files', file)
  149. const uploaded = await apiRequest<{ files: WorkspaceFile[] }>('/api/app/uploads', {method: 'POST', body: data})
  150. if (scope !== composerKey.value || ownerEpoch !== accountEpoch) return
  151. files.value = uploaded.files
  152. uploadedSources = [...payload.files]
  153. uploadedReferences = [...files.value]
  154. }
  155. } catch (cause) { error.value = cause instanceof Error ? cause.message : '上传失败'; return }
  156. finally { if (ownerEpoch === accountEpoch) busy.value = false }
  157. }
  158. if (scope !== composerKey.value || ownerEpoch !== accountEpoch) return
  159. if (!payload.files.length) files.value = []
  160. if (await send()) {
  161. const cleared = sourceComposer?.clearAfterSend(token)
  162. if (cleared && composer.value === sourceComposer && composerKey.value === scope && accountEpoch === ownerEpoch) {
  163. quoted.value = null; uploadedSources = []; uploadedReferences = []
  164. }
  165. }
  166. }
  167. const dialog = ref<'agent' | 'group' | 'editAgent' | 'editGroup' | null>(null),
  168. editingId = ref(''),
  169. editingConversationId = ref(''),
  170. scroller = ref<HTMLElement>(),
  171. fileInput = ref<HTMLInputElement>(),
  172. dialogElement = ref<HTMLDialogElement>()
  173. const editingConversation = computed(() => conversations.value.find(c => c.id === editingConversationId.value) ?? (active.value?.id === editingConversationId.value ? active.value : undefined))
  174. const editingBot = computed(() => agents.value.find(agent => agent.id === editingId.value))
  175. const isRemoteAgent=computed(()=>dialog.value==='editAgent' && !!agents.value.find(a=>a.id===editingId.value)?.remoteAgentId)
  176. const form = reactive({
  177. name: '',
  178. avatar: '',
  179. instructions: '',
  180. description: '',
  181. job: '',
  182. antiJobs: [] as string[],
  183. voice: '' as ''|'concise'|'casual'|'rigorous'|'custom',
  184. voiceCustom: '',
  185. actBias: '' as ''|'ask_first'|'ask_key_then_act'|'act_now',
  186. execution: 'profile' as 'profile'|'computer',
  187. canManageTeam: true,
  188. canCollaborate: true,
  189. memoryEnabled: true,
  190. approvalPolicy: 'ask' as 'ask'|'allow'|'deny',
  191. source: '',
  192. memberIds: [] as string[],
  193. memberRoles: {} as Record<string, WorkspaceMemberRole>,
  194. administratorId: '',
  195. mode: 'discussion' as 'discussion' | 'host' | 'free',
  196. autoReplyIds: [] as string[],
  197. maxReplyRounds: 3,
  198. })
  199. const selectedPresetId = ref('custom')
  200. const selectedPreset = computed(() => dialog.value === 'group' ? TEAM_PRESETS.find(p => p.id === selectedPresetId.value) : undefined)
  201. function applyPresetRoles(preset: TeamPreset) {
  202. form.memberRoles = Object.fromEntries(preset.roles.flatMap((role, index) => {
  203. const id = form.memberIds[index]
  204. return id ? [[id, { name: role.name, description: role.description }]] : []
  205. }))
  206. form.administratorId = form.memberIds[Math.max(0, preset.roles.findIndex(role => role.host))] ?? ''
  207. }
  208. function choosePreset(preset?: TeamPreset) {
  209. const available = agents.value.filter(a => !a.archived && !a.temporaryGoalId)
  210. if (preset && available.length < preset.roles.length) return
  211. selectedPresetId.value = preset?.id ?? 'custom'
  212. Object.assign(form, { name: preset?.name ?? '', instructions: preset?.instructions ?? '', job: '', antiJobs: [], voice: '', voiceCustom: '', actBias: '', memberIds: preset ? available.slice(0, preset.roles.length).map(a => a.id) : [], memberRoles: {}, administratorId: '', mode: knowledgeEnabled.value ? 'discussion' : 'host', autoReplyIds: [], maxReplyRounds: 3 })
  213. if (preset) applyPresetRoles(preset)
  214. }
  215. function assignPresetRole(index: number, id: string) {
  216. if (!selectedPreset.value) return
  217. const next = [...form.memberIds], previous = next[index], occupied = next.indexOf(id)
  218. next[index] = id
  219. if (occupied >= 0 && occupied !== index && previous) next[occupied] = previous
  220. form.memberIds = next
  221. applyPresetRoles(selectedPreset.value)
  222. }
  223. const answers = reactive<Record<string, string>>({})
  224. let cursor = 0,
  225. disposed = false,
  226. timer: ReturnType<typeof setTimeout> | undefined,
  227. generation = 0,
  228. pendingRequestId: string | undefined,
  229. pendingFingerprint = ''
  230. const selected = computed(() => (typeof route.params.id === 'string' ? route.params.id : undefined))
  231. const selectedTask = computed(() => typeof route.query.taskId === 'string' ? route.query.taskId : '')
  232. const shell=ref<InstanceType<typeof WorkspaceShell>>(),vmWorkspace=ref<InstanceType<typeof LocalVmWorkspace>>(),desktopViewer=ref<InstanceType<typeof ComputerPanel>>()
  233. const computerOpen=ref(false),dockView=ref<'computer'|'inspector'>(),twoDesktops=ref(false),desktopAgent=ref<Agent>(),desktopBackend=ref<ComputerBackend>(),desktopHost=ref('')
  234. async function resolveDeviceHost(){try{return (await window.yaoyaoDesktop?.deviceHost?.())?.deviceHost??null}catch{return null}}
  235. const creatingTask=ref(false)
  236. const CREATE_TASK_VALUE='__create_task__'
  237. function toggleDock(view:'computer'|'inspector'){dockView.value=dockView.value===view?undefined:view}
  238. async function openComputer(agent:Agent,backend?:ComputerBackend,host?:string){
  239. if(window.yaoyaoDesktop?.openComputer){try{await window.yaoyaoDesktop.openComputer(agent.id,{backend,host})}catch(cause){error.value=cause instanceof Error?cause.message:'无法打开电脑窗口'}return}
  240. if(computerOpen.value&&desktopViewer.value){
  241. if(desktopAgent.value?.id===agent.id&&desktopBackend.value===backend&&desktopHost.value===(host??''))return
  242. try{await desktopViewer.value.releaseControl();computerOpen.value=false;await nextTick()}catch(cause){error.value=cause instanceof Error?cause.message:'请先交还当前电脑';return}
  243. }
  244. desktopAgent.value=agent;desktopBackend.value=backend;desktopHost.value=host??'';computerOpen.value=true
  245. }
  246. async function openBrowserCard(card:NonNullable<UiMessage['browserCard']>){
  247. // Only the structured server message supplies this target; markdown links and
  248. // model-authored text never become computer-control instructions.
  249. if(!messages.value.some(message=>message.browserCard?.id===card.id&&message.browserCard.agentId===card.agentId))return
  250. const agent=agents.value.find(agent=>agent.id===card.agentId&&!agent.archived)
  251. if(!agent){error.value='此浏览器所属机器人已不可用,或你已没有访问权限';return}
  252. await openComputer(agent,'managed-browser')
  253. }
  254. async function leaveComputer(){
  255. if(twoDesktops.value&&vmWorkspace.value&&!await vmWorkspace.value.close())return false
  256. if(computerOpen.value&&desktopViewer.value){try{await desktopViewer.value.releaseControl();computerOpen.value=false}catch{return false}}
  257. return true
  258. }
  259. onBeforeRouteUpdate(leaveComputer);onBeforeRouteLeave(leaveComputer)
  260. const computerCandidates=computed(()=>agents.value.filter(agent=>!agent.archived&&(active.value?.memberIds.includes(agent.id)||(!!agent.temporaryGoalId&&agent.temporaryGoalId===activeTask.value?.goal?.id))))
  261. const members = computed(() => agents.value.filter((a) => active.value?.memberIds.includes(a.id)))
  262. const activeHeaderAgent = computed(() => active.value?.kind === 'direct' ? agents.value.find(agent => agent.id === active.value?.memberIds[0]) : undefined)
  263. const activeHeaderTitle = computed(() => activeHeaderAgent.value?.name || active.value?.name || 'Bot 模式')
  264. const activeHeaderAvatarName = computed(() => active.value ? activeHeaderAgent.value?.name || active.value.name : '')
  265. const activeHeaderAvatar = computed(() => activeHeaderAgent.value?.avatar || active.value?.avatar || '')
  266. const activeHeaderAvatarMembers = computed(() => active.value?.kind === 'group' ? workspaceAvatarMembers(active.value.memberIds, agents.value, active.value) : [])
  267. const thinkingIdentity = computed(() => {
  268. const streamingAgentId = [...uiMessages.value].reverse().find(message => message.role === 'assistant' && message.status === 'streaming')?.profile
  269. const agentId = activeHeaderAgent.value?.id || run.value?.activeAgentId || streamingAgentId
  270. || active.value?.activeAgentId || Object.entries(active.value?.activeAgentStates ?? {}).find(([, state]) => state === 'running')?.[0]
  271. || active.value?.memberIds[0]
  272. const agent = agents.value.find(agent => agent.id === agentId)
  273. return { name: agent?.name || active.value?.name || '机器人', avatar: agent?.avatar || (active.value?.kind === 'direct' ? active.value.avatar : '') || '' }
  274. })
  275. const isAgentDialog = computed(() => dialog.value === 'agent' || dialog.value === 'editAgent')
  276. const body = (v: unknown) => v as JsonValue
  277. async function refresh() {
  278. const startedAtCursor = transcriptStore.cursor
  279. const owner = auth.user?.id
  280. const [a, c] = await Promise.all([
  281. apiRequest<{ agents: Agent[] }>('/api/app/agents'),
  282. apiRequest<{ conversations: Conversation[]; cursor: number }>('/api/app/conversations'),
  283. ])
  284. if (disposed || auth.user?.id !== owner || transcriptStore.cursor !== startedAtCursor) return
  285. agents.value = a.agents
  286. const localConversations = new Map(conversations.value.map(row => [row.id, row]))
  287. transcriptStore.conversations = c.conversations.map(conversation => {
  288. const local = localConversations.get(conversation.id)
  289. return local && local.unreadVersion === conversation.unreadVersion && [...pendingReads].some(key => key.startsWith(`${conversation.id}:`))
  290. ? { ...conversation, unread: local.unread, unreadCount: local.unreadCount } : conversation
  291. })
  292. transcriptStore.agents = agents.value
  293. conversations.value = transcriptStore.conversations
  294. if (!cursor) { cursor = c.cursor; transcriptStore.cursor = c.cursor }
  295. }
  296. async function load(id = selected.value, append = false, signal?: AbortSignal) {
  297. if (!id) {
  298. generation++
  299. active.value = undefined
  300. messages.value = []
  301. run.value = null
  302. interactions.value = []
  303. context.value = null
  304. activeTask.value = null;tasks.value = [];assignments.value = []
  305. return
  306. }
  307. const own = ++generation
  308. const owner = auth.user?.id, epoch = accountEpoch
  309. const current = () => !disposed && own === generation && !signal?.aborted
  310. && auth.user?.id === owner && accountEpoch === epoch
  311. const previousComposer = composerKey.value
  312. const previousFiles = composer.value?.filesSnapshot() ?? []
  313. const previousQuote = quoted.value
  314. const requestedTask = selectedTask.value || (active.value?.id === id ? activeTask.value?.id : undefined)
  315. const cached = !append ? transcriptStore.get(id, requestedTask) : undefined
  316. const readToken = transcriptStore.beginRead()
  317. if (!append) loading.value = !cached
  318. if (active.value?.id !== id) {
  319. active.value = conversations.value.find(c => c.id === id)
  320. messages.value = cached?.messages ?? [];run.value = null;interactions.value = [];context.value = null
  321. activeTask.value = null;tasks.value = [];assignments.value = [];quoted.value = null;older.value = false
  322. }
  323. try {
  324. const incoming = cached ?? await apiRequest<WorkspaceDetail>(`/api/app/conversations/${id}?limit=50&toolDetails=lazy${requestedTask ? `&taskId=${encodeURIComponent(requestedTask)}` : ''}`, { signal })
  325. if (!current()) return
  326. const r = cached ?? transcriptStore.finishRead(readToken, incoming)
  327. if (cached && transcriptStore.staleDetails.has(transcriptKey(id, cached.task?.id))) {
  328. queueMicrotask(() => { if (current() && active.value?.id === id) void load(id, true, signal) })
  329. }
  330. const atBottom = timeline.value?.isFollowingBottom() ?? true
  331. active.value = r.conversation
  332. if (r.task) transcriptStore.selectedTasks.set(id, r.task.id)
  333. activeTask.value = r.task ?? null;tasks.value = r.tasks ?? [];assignments.value = r.assignments ?? []
  334. messages.value = r.messages
  335. run.value = r.run
  336. interactions.value = r.interactions
  337. context.value = r.context
  338. if (previousComposer !== composerKey.value) {
  339. taskFiles.set(previousComposer,previousFiles)
  340. taskQuotes.set(previousComposer,previousQuote)
  341. if (activeTask.value && !requestedTask) {
  342. const legacy = `hermes-yaoyao:composer:group:${auth.user?.id}:${active.value.id}`
  343. const current = `hermes-yaoyao:composer:group:${composerKey.value}`
  344. try {
  345. const draft = localStorage.getItem(legacy)
  346. if (draft && !localStorage.getItem(current)) { localStorage.setItem(current,draft);localStorage.removeItem(legacy) }
  347. } catch { /* Leave the original draft intact when browser storage is unavailable. */ }
  348. }
  349. await nextTick()
  350. if (!current()) return
  351. const saved = taskFiles.get(composerKey.value)
  352. if (saved?.length) await composer.value?.attachFiles(saved)
  353. if (!current()) return
  354. quoted.value = taskQuotes.get(composerKey.value) ?? null
  355. }
  356. if (!append) older.value = r.hasOlder ?? r.messages.length === 50
  357. if (!append || atBottom) {
  358. await nextTick()
  359. if (!current()) return
  360. if (!append && typeof route.query.unread!=='string') timeline.value?.scrollToBottom('auto')
  361. if(typeof route.query.unread==='string')void locateUnread(route.query.unread)
  362. }
  363. } catch (e) {
  364. if (current() && requestedTask && e instanceof ApiError && e.status === 404) {
  365. try {
  366. const available = await apiRequest<{tasks:WorkspaceTask[]}>(`/api/app/conversations/${id}/tasks`, { signal })
  367. const fallback = available.tasks[0]
  368. if (current() && fallback && fallback.id !== requestedTask) {
  369. await router.replace({query:{...route.query,taskId:fallback.id}})
  370. return
  371. }
  372. } catch { /* A deleted conversation still reports its original error. */ }
  373. }
  374. if (current()) error.value = e instanceof Error ? e.message : '加载失败'
  375. } finally {
  376. transcriptStore.cancelRead(readToken)
  377. if (own === generation) loading.value = false
  378. }
  379. }
  380. let unreadNavigation=0
  381. async function locateUnread(id:string){
  382. const own=++unreadNavigation,conversation=selected.value,task=selectedTask.value,path=route.path
  383. const current=()=>!disposed&&own===unreadNavigation&&route.path===path&&active.value?.id===conversation&&selected.value===conversation
  384. &&selectedTask.value===task&&route.query.unread===id
  385. try{
  386. for(let i=0;i<100&&current();i++){
  387. await nextTick();if(!current()||timeline.value?.scrollToMessage(id))return
  388. if(!older.value||loadingOlder.value)return
  389. await loadOlder()
  390. }
  391. }finally{
  392. // A removed/unavailable target must not keep all visible messages unread.
  393. if(current()){const query={...route.query};delete query.unread;await router.replace({query})}
  394. }
  395. }
  396. watch(()=>route.query.unread,id=>{
  397. if(typeof id==='string'&&!loading.value&&active.value?.id===selected.value)void locateUnread(id)
  398. },{flush:'post'})
  399. const unread=useUnreadStore()
  400. const pendingReads = new Set<string>()
  401. async function markVisible(ids:string[]) {
  402. const c=active.value;if(!c||loading.value||computerOpen.value||typeof route.query.unread==='string')return
  403. const key=`${c.id}:${ids.join(',')}`;if(pendingReads.has(key))return
  404. const complete=new Set(messages.value.filter(m=>m.role==='assistant'&&m.status==='complete'&&m.visible!==false).map(m=>m.id))
  405. pendingReads.add(key);try{await unread.visible('bot',c.id,undefined,ids.filter(id=>complete.has(id)))}catch{}finally{pendingReads.delete(key)}
  406. }
  407. async function selectTask(event:Event){
  408. const select=event.currentTarget as HTMLSelectElement,value=select.value
  409. if(value!==CREATE_TASK_VALUE){await router.push({query:{...route.query,taskId:value}});return}
  410. select.value=activeTask.value?.id??''
  411. if(!active.value||active.value.kind!=='group'||creatingTask.value)return
  412. const conversationId=active.value.id
  413. creatingTask.value=true;error.value=''
  414. try{
  415. const result=await apiRequest<{task:WorkspaceTask}>(`/api/app/conversations/${conversationId}/tasks`,{method:'POST',body:{}})
  416. if(active.value?.id!==conversationId)return
  417. tasks.value=[result.task,...tasks.value.filter(task=>task.id!==result.task.id)]
  418. await router.push({query:{...route.query,taskId:result.task.id}})
  419. }catch(cause){error.value=cause instanceof Error?cause.message:'新建话题失败'}finally{creatingTask.value=false}
  420. }
  421. async function stopTask() {
  422. if (!active.value || !activeTask.value) return
  423. try {
  424. await apiRequest(`/api/app/conversations/${active.value.id}/tasks/${activeTask.value.id}/stop`,{method:'POST',body:{}})
  425. await load(undefined,true)
  426. } catch(cause) {error.value=cause instanceof Error?cause.message:'停止任务失败'}
  427. }
  428. async function resumeTask() {
  429. if (!active.value || !activeTask.value) return
  430. try {
  431. await apiRequest(`/api/app/conversations/${active.value.id}/tasks/${activeTask.value.id}/resume`,{method:'POST',body:{requestId:createUuid()}})
  432. await load(undefined,true)
  433. } catch(cause) {error.value=cause instanceof Error?cause.message:'恢复任务失败'}
  434. }
  435. async function saveGoalCriteria(goalId: string, expectedRevision: number, acceptanceCriteria: string[]) {
  436. const conversationId = active.value?.id
  437. if (!conversationId || activeTask.value?.id !== goalId) throw new Error('话题已切换,请重新打开目标')
  438. const result = await apiRequest<{goal: NonNullable<WorkspaceTask['goal']>}>(`/api/app/conversations/${conversationId}/tasks/${goalId}/plan`, {
  439. method: 'PATCH', body: { requestId: createUuid(), expectedRevision, acceptanceCriteria },
  440. })
  441. if (active.value?.id === conversationId && activeTask.value?.id === goalId) {
  442. activeTask.value.goal = result.goal
  443. await load(conversationId, true)
  444. }
  445. }
  446. function openTaskLink(event: MouseEvent) {
  447. if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
  448. const anchor=(event.target as Element)?.closest?.('a[href]')
  449. if (!anchor) return
  450. try {
  451. const url=new URL(anchor.getAttribute('href') || '',window.location.origin)
  452. if(url.origin!==window.location.origin || !/^\/conversations\/[^/]+$/.test(url.pathname) || !url.searchParams.get('taskId'))return
  453. event.preventDefault();event.stopPropagation()
  454. void router.push(url.pathname+url.search)
  455. } catch { /* Leave other links to their normal handler. */ }
  456. }
  457. let patchEvents = false
  458. let eventSource: EventSource | undefined
  459. let eventFrame: number | undefined
  460. let eventQueue: WorkspaceEvent[] = []
  461. let recoveryAbort: AbortController | undefined
  462. function cancelRecovery() {
  463. recoveryAbort?.abort(); recoveryAbort = undefined
  464. if (timer) clearTimeout(timer)
  465. timer = undefined
  466. }
  467. function presentDetail(detail: WorkspaceDetail) {
  468. const atBottom = timeline.value?.isFollowingBottom() ?? true
  469. active.value = detail.conversation
  470. messages.value = detail.messages
  471. activeTask.value = detail.task ?? null; tasks.value = detail.tasks ?? []
  472. run.value = detail.run; interactions.value = detail.interactions
  473. context.value = detail.context; assignments.value = detail.assignments ?? []
  474. older.value = detail.hasOlder ?? false
  475. }
  476. function flushEvents() {
  477. eventFrame = undefined
  478. try { for (const event of eventQueue) {
  479. transcriptStore.apply(event)
  480. if (event.type === 'project.changed') { const project = event.data as WorkspaceProject; projects.value = [...projects.value.filter(p => p.id !== project.id), project] }
  481. if (/^(memory|project|collaboration)\./.test(event.type)) knowledgeRevision.value++
  482. } }
  483. catch { eventQueue = []; eventSource?.close(); void recoverEvents(); return }
  484. eventQueue = []
  485. cursor = transcriptStore.cursor
  486. agents.value = transcriptStore.agents
  487. conversations.value = transcriptStore.conversations
  488. if (selected.value) {
  489. const detail = transcriptStore.get(selected.value, selectedTask.value || activeTask.value?.id)
  490. if (detail) presentDetail(detail)
  491. else if (!conversations.value.some(c => c.id === selected.value)) void router.replace('/conversations')
  492. else if (activeTask.value && !transcriptStore.details.has(transcriptKey(selected.value, activeTask.value.id))) {
  493. void router.replace(`/conversations/${selected.value}`); void load(selected.value, true)
  494. }
  495. }
  496. }
  497. async function hydrateWorkspace(signal: AbortSignal) {
  498. const owner = auth.user?.id, epoch = accountEpoch
  499. const capabilities = await apiRequest<{ features: string[]; csrfToken?: string }>('/api/app/capabilities', { signal })
  500. if (signal.aborted || disposed || accountEpoch !== epoch || auth.user?.id !== owner) return
  501. patchEvents = capabilities.features.includes(WORKSPACE_PATCH_CAPABILITY)
  502. knowledgeEnabled.value = capabilities.features.includes('bot-file-memory-v1')
  503. if (capabilities.csrfToken) setApiCsrfToken(capabilities.csrfToken)
  504. const readToken = transcriptStore.beginRead()
  505. try {
  506. const query = new URLSearchParams({ details: 'selected', toolDetails: 'lazy' })
  507. if (selected.value) query.set('conversationId', selected.value)
  508. if (selectedTask.value) query.set('taskId', selectedTask.value)
  509. const snapshot = await apiRequest<WorkspaceSnapshot & { serverIdentity?: ServerIdentity; projects?: WorkspaceProject[] }>(`/api/app/workspace/snapshot?${query}`, { signal })
  510. if (signal.aborted || disposed || accountEpoch !== epoch || auth.user?.id !== owner) return
  511. transcriptStore.hydrate(snapshot)
  512. agents.value = snapshot.agents; conversations.value = transcriptStore.conversations; cursor = snapshot.cursor
  513. projects.value = snapshot.projects ?? []
  514. publishServerIdentity(snapshot.serverIdentity)
  515. } finally { transcriptStore.cancelRead(readToken) }
  516. }
  517. function connectEvents() {
  518. eventSource?.close()
  519. if (disposed) return
  520. if (!navigator.onLine) { suspendEvents(); return }
  521. const source = new EventSource(`/api/app/events/stream?after=${cursor}&toolDetails=lazy${patchEvents ? '&format=patch-v1' : ''}`)
  522. eventSource = source
  523. source.addEventListener('workspace', event => {
  524. if (disposed || eventSource !== source) return
  525. try {
  526. eventQueue.push(JSON.parse((event as MessageEvent).data))
  527. if (eventFrame === undefined) eventFrame = requestAnimationFrame(flushEvents)
  528. } catch { source.close(); error.value = '消息同步失败,正在恢复'; void recoverEvents() }
  529. })
  530. source.addEventListener('ready', event => {
  531. if (eventSource !== source) return
  532. flushEvents(); error.value = ''
  533. publishServerIdentity(JSON.parse((event as MessageEvent).data).serverIdentity)
  534. })
  535. source.addEventListener('reset', () => { if (!disposed && eventSource === source) { source.close(); void recoverEvents() } })
  536. source.onerror = () => {
  537. if (disposed || eventSource !== source) return
  538. error.value = '连接中断,正在重连'
  539. void apiRequest('/api/app/capabilities').catch(cause => {
  540. if (cause instanceof ApiError && [401, 403].includes(cause.status)) {
  541. source.close()
  542. error.value = cause.message
  543. }
  544. })
  545. }
  546. }
  547. function suspendEvents() {
  548. cancelRecovery()
  549. eventSource?.close(); eventSource = undefined
  550. error.value = '网络已断开,恢复连接后将自动同步'
  551. }
  552. function resumeEvents() {
  553. if (!disposed && auth.user?.id) void recoverEvents()
  554. }
  555. async function recoverEvents(initial = false) {
  556. cancelRecovery()
  557. if (disposed || !auth.user?.id) return
  558. if (!navigator.onLine) { suspendEvents(); return }
  559. const controller = new AbortController(), owner = auth.user.id, epoch = accountEpoch
  560. recoveryAbort = controller
  561. const current = () => !disposed && !controller.signal.aborted && recoveryAbort === controller
  562. && accountEpoch === epoch && auth.user?.id === owner
  563. eventSource?.close(); eventSource = undefined; eventQueue = []
  564. if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
  565. eventFrame = undefined
  566. try {
  567. await hydrateWorkspace(controller.signal)
  568. if (!current()) return
  569. const detail = !initial && selected.value ? transcriptStore.get(selected.value, selectedTask.value || activeTask.value?.id) : undefined
  570. if (detail) {
  571. presentDetail(detail)
  572. if (transcriptStore.staleDetails.has(transcriptKey(detail.conversation.id, detail.task?.id))) await load(detail.conversation.id, true, controller.signal)
  573. } else await load(selected.value, false, controller.signal)
  574. if (current()) connectEvents()
  575. }
  576. catch (cause) {
  577. if (!current()) return
  578. if (!navigator.onLine) { suspendEvents(); return }
  579. error.value = cause instanceof Error ? cause.message : '连接中断'
  580. if (cause instanceof ApiError && [401, 403].includes(cause.status)) return
  581. timer = setTimeout(() => void recoverEvents(), 1500)
  582. } finally { if (recoveryAbort === controller) recoveryAbort = undefined }
  583. }
  584. async function select(id: string) {
  585. error.value = ''
  586. files.value = []
  587. mentions.value = []
  588. text.value = ''
  589. preview.value = null
  590. mediaIndex.value = null
  591. pendingRequestId = undefined
  592. await router.push(`/conversations/${id}`)
  593. }
  594. function openConversationSettings(id: string) {
  595. const conversation = conversations.value.find(c => c.id === id)
  596. if (conversation) void openDialog(conversation.kind === 'direct' ? 'editAgent' : 'editGroup', conversation)
  597. }
  598. async function openDialog(kind: NonNullable<typeof dialog.value>, conversation = active.value) {
  599. error.value = ''
  600. dialog.value = kind
  601. editingId.value = ''
  602. editingConversationId.value = kind === 'editAgent' || kind === 'editGroup' ? conversation?.id ?? '' : ''
  603. selectedPresetId.value = 'custom'
  604. Object.assign(form, {
  605. name: '',
  606. avatar: kind === 'agent' ? encodeAgentAvatar(randomAgentIdentity('new-agent', '机器人')) : '',
  607. instructions: '',
  608. description: '',
  609. execution: 'profile' as 'profile'|'computer',
  610. canManageTeam: true,
  611. canCollaborate: true,
  612. memoryEnabled: true,
  613. approvalPolicy: 'ask',
  614. source: '',
  615. memberIds: [],
  616. memberRoles: {},
  617. administratorId: '',
  618. mode: knowledgeEnabled.value ? 'discussion' : 'host',
  619. autoReplyIds: [],
  620. maxReplyRounds: 3,
  621. })
  622. try {
  623. if (kind === 'agent' || kind === 'editAgent') {
  624. const s = await apiRequest<{ sources: Source[]; errors?: string[] }>('/api/app/agents/sources')
  625. if (!s.sources.length && s.errors?.length) throw new Error('基础机器人服务暂不可用,请联系管理员检查 Hermes 连接后重试。')
  626. sources.value = s.sources
  627. form.source = s.sources[0] ? JSON.stringify([s.sources[0].nodeId, s.sources[0].profile]) : ''
  628. }
  629. if (kind === 'editAgent') {
  630. const a = agents.value.find(a => a.id === conversation?.memberIds[0])
  631. if (!a) throw new Error('机器人不存在,请刷新后重试')
  632. Object.assign(form, a)
  633. form.description ??= ''; form.job ??= ''; form.antiJobs ??= []; form.voice ??= ''; form.voiceCustom ??= ''; form.actBias ??= ''
  634. form.source=JSON.stringify([a.nodeId,a.profile])
  635. if(a.remoteAgentId){
  636. const remote=(await apiRequest<{agents:Agent[]}>(`/api/app/nodes/${a.nodeId}/agents`)).agents.find(candidate=>candidate.id===a.remoteAgentId)
  637. if(remote)Object.assign(form,remote)
  638. }
  639. form.approvalPolicy = a.approvalPolicy ?? 'ask'
  640. editingId.value = a.id
  641. }
  642. if (kind === 'editGroup' && conversation) {
  643. editingId.value = conversation.id
  644. Object.assign(form, conversation, {
  645. mode: conversation.collaborationMode ?? conversation.mode,
  646. memberIds: [...conversation.memberIds],
  647. autoReplyIds: [...conversation.autoReplyIds],
  648. memberRoles: Object.fromEntries(Object.entries(conversation.memberRoles ?? {}).map(([id, role]) => [id, { ...role }])),
  649. })
  650. }
  651. await nextTick()
  652. dialogElement.value?.showModal()
  653. } catch (e) {
  654. error.value = String(e)
  655. dialog.value = null
  656. }
  657. }
  658. function closeDialog() {
  659. dialogElement.value?.close()
  660. dialog.value = null
  661. editingConversationId.value = ''
  662. }
  663. function saveBotProfile(draft: Pick<typeof form, 'name'|'avatar'|'instructions'|'source'|'canManageTeam'|'canCollaborate'|'memoryEnabled'|'approvalPolicy'> & Partial<Pick<typeof form, 'description'|'job'|'antiJobs'|'voice'|'voiceCustom'|'actBias'>>) {
  664. Object.assign(form, draft)
  665. form.description ??= ''; form.job ??= ''; form.antiJobs ??= []; form.voice ??= ''; form.voiceCustom ??= ''; form.actBias ??= ''
  666. void save()
  667. }
  668. watch(
  669. () => form.memberIds.slice(),
  670. (ids) => {
  671. if (!ids.includes(form.administratorId)) form.administratorId = ids[0] ?? ''
  672. form.autoReplyIds = form.autoReplyIds.filter((id) => ids.includes(id))
  673. form.memberRoles = Object.fromEntries(Object.entries(form.memberRoles).filter(([id]) => ids.includes(id)))
  674. },
  675. )
  676. async function save() {
  677. busy.value = true
  678. error.value = ''
  679. try {
  680. const fields = { name: form.name, ...(isAgentDialog.value ? { avatar: form.avatar, description: form.description.trim(), canManageTeam: form.canManageTeam, approvalPolicy: form.approvalPolicy, execution:form.execution, ...(knowledgeEnabled.value ? { canCollaborate: form.canCollaborate, memoryEnabled: form.memoryEnabled } : {}) } : {}), instructions: form.instructions }
  681. const personaClears = { job: form.job.trim() ? form.job.trim() : null, antiJobs: form.antiJobs.length ? form.antiJobs : null, voice: form.voice || null, voiceCustom: form.voice === 'custom' && form.voiceCustom.trim() ? form.voiceCustom : null, actBias: form.actBias || null }
  682. const personaCreates = Object.fromEntries(Object.entries(personaClears).filter(([, value]) => value !== null && value !== undefined))
  683. if (isRemoteAgent.value) {
  684. await apiRequest(`/api/app/agents/${editingId.value}`, { method: 'PATCH', body: { approvalPolicy: form.approvalPolicy } })
  685. } else if (dialog.value === 'agent') {
  686. const [nodeId, profile] = JSON.parse(form.source)
  687. const result = await apiRequest<{ agent: Agent }>('/api/app/agents', {
  688. method: 'POST',
  689. body: { ...fields, ...personaCreates, nodeId, profile, computer: 'auto', envs: {vm:true,cloud:true,desktop:true}, execution:'profile' },
  690. })
  691. await refresh()
  692. const c = conversations.value.find(
  693. (c) => c.kind === 'direct' && c.memberIds[0] === result.agent.id,
  694. )
  695. if (c) await select(c.id)
  696. } else if (dialog.value === 'editAgent')
  697. await apiRequest(`/api/app/agents/${editingId.value}`, { method: 'PATCH', body: { ...fields, ...personaClears, ...(form.source?{nodeId:JSON.parse(form.source)[0],profile:JSON.parse(form.source)[1]}:{}) } })
  698. else {
  699. const payload = {
  700. ...fields,
  701. administratorId: form.administratorId || form.memberIds[0],
  702. mode: form.mode === 'discussion' ? 'free' : form.mode,
  703. ...(knowledgeEnabled.value ? { collaborationMode: form.mode } : {}),
  704. autoReplyIds: form.autoReplyIds,
  705. maxReplyRounds: form.maxReplyRounds,
  706. memberIds: form.memberIds,
  707. memberRoles: form.memberRoles,
  708. }
  709. const result = await apiRequest<{ conversation: Conversation }>(
  710. dialog.value === 'group'
  711. ? '/api/app/conversations'
  712. : `/api/app/conversations/${editingId.value}`,
  713. { method: dialog.value === 'group' ? 'POST' : 'PATCH', body: body(payload) },
  714. )
  715. await select(result.conversation.id)
  716. }
  717. closeDialog()
  718. await refresh()
  719. await load()
  720. } catch (e) {
  721. error.value = e instanceof Error ? e.message : '保存失败'
  722. } finally {
  723. busy.value = false
  724. }
  725. }
  726. async function upload(event: Event) {
  727. const picked = (event.target as HTMLInputElement).files
  728. if (!picked?.length) return
  729. busy.value = true
  730. error.value = ''
  731. try {
  732. const data = new FormData()
  733. for (const file of picked) data.append('files', file)
  734. const r = await apiRequest<{ files: WorkspaceFile[] }>('/api/app/uploads', {
  735. method: 'POST',
  736. body: data,
  737. })
  738. files.value = [...files.value, ...r.files].slice(0, 8)
  739. } catch (e) {
  740. error.value = String(e)
  741. } finally {
  742. busy.value = false
  743. ;(event.target as HTMLInputElement).value = ''
  744. }
  745. }
  746. let draftRevision = 0, accountEpoch = 0
  747. watch([text, files, mentions], () => { draftRevision++ }, { deep: true, flush: 'sync' })
  748. const sendRefreshes = new Map<string, ReturnType<typeof setTimeout>>()
  749. function reconcileSend(receipt: WorkspaceSendReceipt, scope: string, id: string, owner: string | undefined) {
  750. clearTimeout(sendRefreshes.get(scope))
  751. sendRefreshes.set(scope, setTimeout(() => {
  752. sendRefreshes.delete(scope)
  753. if (disposed || auth.user?.id !== owner || composerKey.value !== scope) return
  754. if (receipt.cursor !== undefined && transcriptStore.cursor >= receipt.cursor && eventSource?.readyState === EventSource.OPEN) return
  755. void load(id, true).catch(() => { error.value = '消息已发送,正在恢复同步' })
  756. }, receipt.cursor === undefined ? 0 : 2000))
  757. }
  758. async function send() {
  759. const c = active.value
  760. if (!c || busy.value || (!text.value.trim() && !files.value.length)) return
  761. busy.value = true
  762. error.value = ''
  763. const owner = auth.user?.id, epoch = accountEpoch, revision = draftRevision, scope = composerKey.value, taskId = activeTask.value?.id
  764. const submittedText = text.value, submittedFiles = files.value, submittedMentions = [...mentions.value]
  765. const mode = deliveryMode.value && !activeTask.value?.goal ? 'goal' : 'chat'
  766. const fingerprint = JSON.stringify([c.id, activeTask.value?.id, text.value, mentions.value, files.value.map(f => f.id), mode, directProjectId.value, requestedRounds.value, coordinatorId.value])
  767. if (!pendingRequestId || pendingFingerprint !== fingerprint) {
  768. pendingRequestId = createUuid()
  769. pendingFingerprint = fingerprint
  770. }
  771. try {
  772. const deviceHost = await resolveDeviceHost()
  773. const receipt = await apiRequest<WorkspaceSendReceipt>(`/api/app/conversations/${c.id}/messages`, {
  774. method: 'POST',
  775. body: {
  776. requestId: pendingRequestId,
  777. mode,
  778. ...(knowledgeEnabled.value ? { ...(c.kind === 'direct' && directProjectId.value ? { projectId: directProjectId.value } : {}), ...(requestedRounds.value && c.collaborationMode === 'discussion' ? { rounds: requestedRounds.value } : {}), ...(deliveryMode.value && c.collaborationMode === 'discussion' ? { coordinatorId: coordinatorId.value || coordinators.value[0]?.id } : {}) } : {}),
  779. ...(activeTask.value ? { taskId: activeTask.value.id } : {}),
  780. content: text.value,
  781. mentionIds: mentions.value,
  782. fileIds: files.value.map((f) => f.id),
  783. deviceHost,
  784. },
  785. })
  786. if (disposed || accountEpoch !== epoch || auth.user?.id !== owner) return true
  787. busy.value = false
  788. if (draftRevision === revision && composerKey.value === scope && text.value === submittedText && files.value === submittedFiles
  789. && JSON.stringify(mentions.value) === JSON.stringify(submittedMentions)) {
  790. text.value = ''; files.value = []; mentions.value = []
  791. pendingRequestId = undefined; pendingFingerprint = ''; deliveryMode.value = false
  792. }
  793. flushEvents()
  794. transcriptStore.acceptReceipt(receipt)
  795. conversations.value = transcriptStore.conversations
  796. const accepted = transcriptStore.get(c.id, taskId)
  797. if (accepted && composerKey.value === scope) presentDetail(accepted)
  798. reconcileSend(receipt, scope, c.id, owner)
  799. return true
  800. } catch (e) {
  801. if (accountEpoch === epoch) error.value = e instanceof Error ? e.message : '发送失败'
  802. } finally {
  803. if (accountEpoch === epoch) busy.value = false
  804. }
  805. }
  806. async function action(operation: 'pin' | 'archive', id = active.value?.id) {
  807. const c = conversations.value.find(c => c.id === id)
  808. if (!c) return
  809. if (operation === 'archive') return changeLifecycle(c.archived ? 'restore' : 'archive', c.id)
  810. try {
  811. await apiRequest(`/api/app/conversations/${c.id}`, {
  812. method: 'PATCH',
  813. body: { pinned: !c.pinned },
  814. })
  815. await refresh()
  816. await load()
  817. } catch (e) {
  818. error.value = String(e)
  819. }
  820. }
  821. async function changeLifecycle(operation: WorkspaceLifecycleAction, id: string, fromSearch = false) {
  822. const conversation = conversations.value.find(c => c.id === id)
  823. if (!conversation || lifecycleId.value) return
  824. const actionError = fromSearch ? searchActionError : lifecycleError
  825. actionError.value = ''
  826. lifecycleId.value = id
  827. lifecycleAction.value = operation
  828. try {
  829. const path = `/api/app/conversations/${id}/lifecycle`
  830. let confirmationToken: string | undefined
  831. if (operation !== 'restore') {
  832. const preview = await apiRequest<WorkspaceLifecyclePreview>(path)
  833. const managed = preview.groups.filter(group => group.administrator)
  834. if (managed.length) throw new Error(`此 Bot 是群聊${managed.map(group => `「${group.name}」`).join('、')}的管理者,请先转交管理权,再归档或删除。`)
  835. const verb = operation === 'delete' ? '永久删除' : '归档'
  836. const target = preview.kind === 'direct' ? 'Bot' : '群聊'
  837. let message = `${verb} ${target}「${preview.name}」${operation === 'delete' ? '及其聊天记录' : ''}?`
  838. if (preview.groups.length) message += `\n此 Bot 已加入群聊:${preview.groups.map(group => `「${group.name}」`).join('、')}。确认后会先从这些群聊移除,再${verb}。`
  839. message += operation === 'delete'
  840. ? `\n此操作无法撤销,${preview.kind === 'group' ? '成员 Bot 和' : ''}文件库中的文件会保留。`
  841. : '\n聊天记录会保留,可在搜索的“已归档”中取消归档。'
  842. if (!confirm(message)) return
  843. confirmationToken = preview.confirmationToken
  844. }
  845. await apiRequest(path, { method: 'POST', body: { action: operation, ...(confirmationToken ? { confirmationToken } : {}) } })
  846. if (operation === 'delete') {
  847. conversations.value = conversations.value.filter(c => c.id !== id)
  848. if (conversation.kind === 'direct') agents.value = agents.value.filter(a => a.id !== conversation.memberIds[0])
  849. if (selected.value === id) await router.replace('/conversations')
  850. }
  851. await refresh()
  852. if (selected.value === id) await load()
  853. } catch (cause) {
  854. actionError.value = cause instanceof Error ? cause.message : '操作失败,请重试'
  855. } finally {
  856. lifecycleId.value = ''
  857. lifecycleAction.value = undefined
  858. }
  859. }
  860. async function stopMember(id: string) {
  861. if (!editingConversation.value) return
  862. try {
  863. await apiRequest(`/api/app/conversations/${editingConversation.value.id}/agents/${id}/stop`, { method: 'POST', body: {} })
  864. await load(); await refresh()
  865. } catch (cause) { error.value = cause instanceof Error ? cause.message : '停止失败' }
  866. }
  867. async function control(action: 'stop' | 'reconcile') {
  868. const targetId = run.value?.id ?? active.value?.activeRunId ?? activeTask.value?.activeRunId
  869. if (!targetId) return
  870. try {
  871. await apiRequest(`/api/app/runs/${targetId}/${action}`, { method: 'POST', body: {} })
  872. await load(undefined, true)
  873. } catch (e) {
  874. error.value = String(e)
  875. }
  876. }
  877. async function respond(i: Interaction, answer: string) {
  878. if (respondingInteractionId.value) return
  879. respondingInteractionId.value = i.id
  880. interactionError.value = ''
  881. try {
  882. await apiRequest(`/api/app/interactions/${i.id}/respond`, { method: 'POST', body: { answer } })
  883. await load(undefined, true)
  884. } catch (e) {
  885. interactionError.value = e instanceof Error ? e.message : '审批答复失败,请重试'
  886. } finally { respondingInteractionId.value = '' }
  887. }
  888. async function loadOlder() {
  889. const c = active.value
  890. if (!c || loadingOlder.value) return
  891. loadingOlder.value = true
  892. const readToken = transcriptStore.beginRead()
  893. const taskId = activeTask.value?.id, own = generation
  894. try {
  895. const r = await apiRequest<{ messages: Message[]; cursor?: number }>(
  896. `/api/app/conversations/${c.id}/messages?limit=50&toolDetails=lazy&before=${messages.value[0]?.seq ?? 0}${activeTask.value ? `&taskId=${activeTask.value.id}` : ''}`,
  897. )
  898. if (own !== generation || active.value?.id !== c.id || activeTask.value?.id !== taskId) return
  899. const current = transcriptStore.get(c.id, taskId)
  900. if (!current) return
  901. const detail = transcriptStore.finishRead(readToken, { ...current, messages: r.messages, cursor: r.cursor })
  902. detail.hasOlder = r.messages.length === 50
  903. messages.value = detail.messages; older.value = detail.hasOlder
  904. } catch (e) {
  905. error.value = String(e)
  906. } finally { transcriptStore.cancelRead(readToken); loadingOlder.value = false }
  907. }
  908. function rendered(m: Message) {
  909. return m.content.replace(
  910. /(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g,
  911. (whole, label: string, path: string) => {
  912. const file =
  913. m.attachments.find((f) => f.sourcePath === path) ||
  914. m.attachments.find((f) => path.split('/').at(-1) === f.name)
  915. return file
  916. ? `${label}(/api/app/files/${file.id}/${label.startsWith('!') ? 'preview' : 'download'})`
  917. : whole
  918. },
  919. )
  920. }
  921. watch([selected,selectedTask], () => {
  922. taskFiles.set(composerKey.value, composer.value?.filesSnapshot() ?? [])
  923. taskQuotes.set(composerKey.value, quoted.value)
  924. files.value = [];mentions.value = [];text.value = ''
  925. pendingRequestId = undefined;uploadedSources = [];uploadedReferences = []
  926. void load()
  927. })
  928. watch(() => auth.user?.id, (owner, previous) => {
  929. if (owner === previous) return
  930. knowledgePanel.value?.close(); knowledgeEnabled.value = false; projects.value = []; knowledgeRevision.value++
  931. accountEpoch++; busy.value = false
  932. generation++
  933. cancelRecovery()
  934. text.value = ''; files.value = []; mentions.value = []; quoted.value = null
  935. pendingRequestId = undefined; pendingFingerprint = ''; uploadedSources = []; uploadedReferences = []
  936. eventSource?.close(); eventSource = undefined; eventQueue = []
  937. if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
  938. eventFrame = undefined; cursor = 0
  939. transcriptStore.hydrate({ agents: [], conversations: [], details: [], cursor: 0 })
  940. transcriptStore.selectedTasks.clear()
  941. agents.value = []; conversations.value = []; messages.value = []; active.value = undefined
  942. tasks.value = []; activeTask.value = null; run.value = null; interactions.value = []; context.value = null
  943. taskFiles.clear(); taskQuotes.clear()
  944. if (owner) void recoverEvents()
  945. })
  946. onMounted(async () => {
  947. window.addEventListener('offline', suspendEvents)
  948. window.addEventListener('online', resumeEvents)
  949. void auth.refreshProfileAvatars().catch(() => undefined)
  950. await recoverEvents(true)
  951. })
  952. onBeforeUnmount(() => {
  953. window.removeEventListener('offline', suspendEvents)
  954. window.removeEventListener('online', resumeEvents)
  955. for (const timer of sendRefreshes.values()) clearTimeout(timer)
  956. sendRefreshes.clear()
  957. disposed = true
  958. eventSource?.close()
  959. if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
  960. generation++
  961. cancelRecovery()
  962. })
  963. </script>
  964. <template>
  965. <WorkspaceShell ref="shell" :server-name="auth.serverIdentity?.displayName"
  966. :user-name="auth.user?.username"
  967. :user-avatar="auth.user?.avatar"
  968. :profiles="auth.profiles"
  969. :active-profile="auth.activeProfile"
  970. :is-admin="auth.user?.role === 'admin'"
  971. :upstream-ready="auth.upstreamReady"
  972. :upstream-error="auth.upstreamError"
  973. :theme="theme.resolvedTheme"
  974. :theme-preference="theme.theme"
  975. sidebar-title="聊天"
  976. sidebar-context-title="聊天列表"
  977. @logout="auth.logout"
  978. @toggle-theme="theme.toggle"
  979. @set-theme="theme.setTheme"
  980. @create-agent="openDialog('agent')"
  981. @create-group="openDialog('group')"
  982. @bot-settings-changed="knowledgeChanged"
  983. >
  984. <template #sidebar
  985. ><ConversationList :conversations="conversations" :agents="agents" :selected="selected" @select="select" @settings="openConversationSettings" @pin="action('pin', $event)" @archive="action('archive', $event)" @delete="changeLifecycle('delete', $event)"
  986. /></template>
  987. <template #mobile-sidebar
  988. ><ConversationList :conversations="conversations" :agents="agents" :selected="selected" @select="select" @settings="openConversationSettings" @pin="action('pin', $event)" @archive="action('archive', $event)" @delete="changeLifecycle('delete', $event)"
  989. /></template>
  990. <div v-show="!twoDesktops" class="conversation-with-computer">
  991. <section class="workspace-chat" aria-label="聊天" @click.capture="openTaskLink">
  992. <MessageTimeline @visible-messages="markVisible" ref="timeline" :identity="`${selected}:${activeTask?.id ?? ''}`" :loading-older="loadingOlder" :messages="uiMessages" :title="activeHeaderTitle"
  993. :subtitle="active?.kind === 'group' ? `${members.length} 位成员` : ''"
  994. :header-avatar-name="activeHeaderAvatarName" :header-avatar="activeHeaderAvatar" :header-avatar-kind="active?.kind === 'group' ? 'team' : 'agent'"
  995. :header-avatar-members="activeHeaderAvatarMembers" :header-avatar-state="activeHeaderAgent ? workspaceAvatarState(active, activeHeaderAgent.id) : 'idle'" :header-avatar-activity-key="active?.lastSeq"
  996. :loading="loading" :has-older="older && !!active"
  997. :show-tools="showThinking" :allow-branch="false" :thinking="thinking" :thinking-identity="thinkingIdentity"
  998. :agent-avatars="Object.fromEntries(agents.map(a => [a.id, a.avatar]))"
  999. :agent-states="Object.fromEntries(members.map(a => [a.id, workspaceAvatarState(active, a.id)]))"
  1000. :mention-names="members.map(a => a.name)"
  1001. :empty-title="active ? '开始一段新对话' : '还没有聊天'"
  1002. :empty-description="active ? '从下方输入框发送消息。' : '创建机器人,或选择成员新建群聊。'"
  1003. :interaction="interactions[0] ? { id: interactions[0].id, kind: interactions[0].kind, prompt: interactions[0].message, options: interactions[0].choices } : null"
  1004. :interaction-busy="!!respondingInteractionId" :interaction-error="interactionError"
  1005. :approval-agent-name="agents.find(agent => agent.id === interactions[0]?.agentId)?.name"
  1006. @load-older="loadOlder" @quote="quoted = $event" @preview="openPreview" @preview-file="openPreview"
  1007. @browser-control="openBrowserCard"
  1008. @approval-choice="interactions[0] && respond(interactions[0], $event)"
  1009. @clarify="interactions[0] && respond(interactions[0], $event)">
  1010. <template #header-leading><button v-if="active" class="workspace-list-back icon-button" aria-label="返回 Bot 列表" @click="router.push('/conversations')"><AppIcon name="chevron-left" /></button></template>
  1011. <template #header-actions>
  1012. <div v-if="active" class="header-actions">
  1013. <button v-if="knowledgeEnabled" type="button" class="icon-button" aria-label="记忆与协作" title="记忆与协作" @click="knowledgePanel?.open(active.kind === 'group' ? 'collaboration' : 'agent', active.memberIds[0], active.projectId)"><AppIcon name="users" /></button>
  1014. <button v-if="active.kind==='direct'" type="button" class="icon-button" aria-label="电脑与定时任务" title="电脑与定时任务" :aria-pressed="dockView==='computer'" @click="toggleDock('computer')"><AppIcon name="monitor"/></button>
  1015. <span v-if="active.kind === 'group' && tasks.length" class="task-picker-shell">
  1016. <select class="task-picker" aria-label="当前话题" :aria-busy="creatingTask" :disabled="creatingTask" :value="activeTask?.id" @change="selectTask">
  1017. <option v-for="task in tasks" :key="task.id" :value="task.id">{{ !task.messageCount && task.titleSource === 'automatic' ? '新话题' : task.title }}</option>
  1018. <option :value="CREATE_TASK_VALUE">新建话题</option>
  1019. </select>
  1020. <AppIcon name="chevron-down" :size="14"/>
  1021. </span>
  1022. <button class="icon-button" :aria-label="active.kind === 'direct' ? '编辑资料' : '群聊设置'" :title="active.kind === 'direct' ? '编辑资料' : '群聊设置'" @click="openDialog(active.kind === 'direct' ? 'editAgent' : 'editGroup')"><AppIcon :name="active.kind === 'direct' ? 'edit' : 'settings'" /></button>
  1023. <button type="button" class="icon-button" aria-label="Inspector" title="Inspector" :aria-pressed="dockView==='inspector'" @click="toggleDock('inspector')"><AppIcon name="bug"/></button>
  1024. </div>
  1025. </template>
  1026. </MessageTimeline>
  1027. <p v-if="error" class="error" role="alert">{{ error }}<button class="icon-button" @click="error = ''" aria-label="关闭错误"><AppIcon name="close" /></button></p>
  1028. <ComposerShell v-if="active" :key="composerKey" ref="composer" mode="group" :draft-key="composerKey"
  1029. v-model:delivery-mode="deliveryMode" :delivery-available="active.kind === 'group' && !activeTask?.goal"
  1030. :delivery-disabled="!canRequestGoal || busy || loading || !!activeTask?.activeRunId"
  1031. :delivery-disabled-reason="!canRequestGoal ? '负责人需要是本机上未归档的 Bot' : ''"
  1032. :disabled="active.archived || loading || active.id !== selected" :sending="busy" stop-while-running :streaming="!!active.activeRunId"
  1033. :tool-trace-visible="showThinking" :reference="reference" :context-used="Number(context?.usedTokens || 0)" :context-limit="Number(context?.limitTokens || 0)"
  1034. :mention-options="active.kind === 'group' ? members.map(a => ({id:a.id,label:a.name,insertText:`@${a.name} `})) : []"
  1035. @send="sendFromComposer" @stop="control('stop')" @tool-trace-toggle="showThinking = !showThinking" @clear-reference="quoted = null" @error="error = $event">
  1036. <template #activity>
  1037. <p v-if="run?.status === 'queued'" class="task-queue-status" role="status">正在等待可用机器人</p>
  1038. <p v-else-if="active.collaborationWaiting" class="task-queue-status" role="status"><button @click="knowledgePanel?.open('collaboration', active.memberIds[0])">等待同伴回复 · 查看协作</button></p>
  1039. </template>
  1040. <template #before-input>
  1041. <div v-if="knowledgeEnabled" class="knowledge-shortcuts composer-knowledge">
  1042. <label v-if="active.kind === 'direct' && projects.some(p => p.memberIds.includes(active!.memberIds[0]!))">当前项目<select v-model="directProjectId"><option value="">不关联项目</option><option v-for="project in projects.filter(p => !p.archived && p.memberIds.includes(active!.memberIds[0]!))" :key="project.id" :value="project.id">{{ project.name }}</option></select></label>
  1043. <label v-if="active.collaborationMode === 'discussion' && !deliveryMode">讨论轮数<select v-model="requestedRounds"><option :value="undefined">按消息要求</option><option v-for="n in 12" :key="n" :value="n">{{ n }} 轮</option></select></label>
  1044. <label v-if="deliveryMode && active.collaborationMode === 'discussion'">交付负责人<select v-model="coordinatorId"><option value="">{{ coordinators[0]?.name ?? '请先授权负责人' }}</option><option v-for="agent in coordinators" :key="agent.id" :value="agent.id">{{ agent.name }}</option></select></label>
  1045. </div>
  1046. <TaskPlan :key="activeTask?.id" :goal="activeTask?.goal" :assignments="assignments" :agents="agents" :save-criteria="saveGoalCriteria" @stop="stopTask" @resume="resumeTask" />
  1047. </template>
  1048. </ComposerShell>
  1049. </section>
  1050. <WorkspaceBotPanel v-if="dockView&&active" :conversation-id="active.id" :task-id="activeTask?.id" :mode="dockView" :active="!twoDesktops" :agents="computerCandidates" :is-admin="auth.user?.role === 'admin'" @close="dockView=undefined" @changed="refresh()" @settings="shell?.openLocalVm()" @desktop="openComputer" @workspace="desktopAgent=$event;twoDesktops=true" />
  1051. </div>
  1052. <ComputerPanel ref="desktopViewer" v-if="computerOpen&&desktopAgent" :agents="[desktopAgent]" :backend="desktopBackend" :host="desktopHost" auto-take @changed="load()" @close="computerOpen=false" />
  1053. <LocalVmWorkspace ref="vmWorkspace" v-if="twoDesktops&&desktopAgent" :agents="agents.filter(a=>a.execution==='computer'&&!a.archived&&!a.computerEnvironmentId)" :primary="desktopAgent.id" @close="twoDesktops=false" />
  1054. <FloatingResourceSearch section="groups" label="搜索聊天" :items="searchItems" tabbed @open="searchActionError = ''" @select="select">
  1055. <template #item-actions="{ item }">
  1056. <div v-if="archivedIds.has(item.id)" class="search-lifecycle-actions">
  1057. <button type="button" class="search-restore" :aria-label="`取消归档:${item.title}`" :disabled="!!lifecycleId" @click="changeLifecycle('restore', item.id, true)">{{ lifecycleId === item.id && lifecycleAction === 'restore' ? '恢复中…' : '取消归档' }}</button>
  1058. <button type="button" class="search-delete" :aria-label="`删除聊天:${item.title}`" :disabled="!!lifecycleId" :aria-busy="lifecycleId === item.id && lifecycleAction === 'delete'" @click="changeLifecycle('delete', item.id, true)">
  1059. <AppIcon name="trash" :size="15" />{{ lifecycleId === item.id && lifecycleAction === 'delete' ? '删除中…' : '删除' }}
  1060. </button>
  1061. </div>
  1062. </template>
  1063. <template #footer><p v-if="searchActionError" class="search-delete-error" role="alert">{{ searchActionError }}</p></template>
  1064. </FloatingResourceSearch>
  1065. <Teleport to="body"><div v-if="lifecycleError" class="lifecycle-error" role="alert"><span>{{ lifecycleError }}</span><button type="button" aria-label="关闭聊天操作提示" @click="lifecycleError = ''"><AppIcon name="close" :size="16" /></button></div></Teleport>
  1066. <PreviewModal v-if="preview" :item="preview" :items="media" @close="preview = null" />
  1067. <ImagePreviewLightbox v-model="mediaIndex" :images="lightboxMedia" />
  1068. <BotProfileDialog v-if="dialog === 'editAgent' && editingBot" :key="editingBot.id" :agent="editingBot" :draft="form" :sources="sources" :profiles="auth.profiles" :agents="agents" :conversations="conversations" :conversation-id="editingConversationId" :is-admin="auth.user?.role === 'admin'" :knowledge-enabled="knowledgeEnabled" :busy="busy" :error="error" @close="closeDialog" @save="saveBotProfile" @changed="knowledgeChanged" />
  1069. <Teleport to="body"><dialog v-if="dialog && dialog !== 'editAgent'" ref="dialogElement" class="editor" aria-labelledby="conversation-editor-title" @cancel.prevent="closeDialog">
  1070. <form @submit.prevent="save">
  1071. <header>
  1072. <h2 id="conversation-editor-title">
  1073. {{ dialog === 'agent' ? '创建机器人' : dialog === 'group' ? '创建群聊' : '群聊设置' }}
  1074. </h2>
  1075. <button type="button" class="icon-button" aria-label="关闭" @click="closeDialog"><AppIcon name="close" :size="18" /></button>
  1076. </header>
  1077. <div class="editor-content">
  1078. <p v-if="error" class="error" role="alert">{{ error }}</p>
  1079. <label>名称<input v-model="form.name" :readonly="isRemoteAgent" required maxlength="100" /></label>
  1080. <details v-if="dialog === 'group'" class="group-options">
  1081. <summary>从团队模板选择(可选)</summary>
  1082. <TeamPresetPicker :selected="selectedPresetId" :available="agents.filter(a => !a.archived && !a.temporaryGoalId).length" @select="choosePreset" />
  1083. </details>
  1084. <p v-if="isRemoteAgent">引用的机器人配置由远端管理,请在远端修改名称、头像和角色规则。</p>
  1085. <AgentIdentityPanel v-if="isAgentDialog && !isRemoteAgent" :key="`${dialog}:${editingId}`" :profile="avatarProfile" embedded :show-name="false" :show-default-model="false" :show-actions="false" @avatar-change="form.avatar = $event" />
  1086. <div v-else-if="dialog === 'editGroup'" class="team-avatar-settings">
  1087. <TeamAvatar :name="form.name" :members="workspaceAvatarMembers(form.memberIds, agents, dialog === 'editGroup' ? editingConversation : undefined)" :size="64" />
  1088. <small>群聊头像由成员头像自动组合,随成员头像更新。</small>
  1089. </div>
  1090. <label
  1091. v-if="isAgentDialog&&!isRemoteAgent"
  1092. >基础机器人<select v-model="form.source" required>
  1093. <option
  1094. v-for="s in sources"
  1095. :key="`${s.nodeId}:${s.profile}`"
  1096. :value="JSON.stringify([s.nodeId, s.profile])"
  1097. >
  1098. {{ s.name }} · {{ s.nodeId === 'local' ? '当前服务' : s.nodeId }}
  1099. </option></select
  1100. ><small v-if="!sources.length"
  1101. >{{ auth.isBotOnly ? '暂无可用的已分配机器人,请联系管理员分配或检查连接。' : '没有可用的基础机器人,请检查 Web 的 Hermes 连接。' }}</small
  1102. ></label
  1103. ><label v-if="isAgentDialog"
  1104. >角色提示词与规则<textarea
  1105. v-model="form.instructions"
  1106. :readonly="isRemoteAgent"
  1107. rows="6"
  1108. maxlength="24000"
  1109. :placeholder="
  1110. isAgentDialog
  1111. ? '例如:你是代码审查员。重点检查正确性、边界情况和测试证据。'
  1112. : '所有成员共同遵守的协作规则'
  1113. "
  1114. />
  1115. </label>
  1116. <template v-if="knowledgeEnabled && isAgentDialog && !isRemoteAgent">
  1117. <label class="team-management-permission"><span><input v-model="form.memoryEnabled" type="checkbox" />自动记录长期事实</span></label>
  1118. <button v-if="editingId" type="button" @click="knowledgePanel?.open('agent', editingId)">查看此 Bot 的记忆</button>
  1119. </template>
  1120. <fieldset v-if="selectedPreset" class="preset-role-mapping">
  1121. <legend>角色分配</legend>
  1122. <label v-for="(role, index) in selectedPreset.roles" :key="role.name">
  1123. {{ role.name }}{{ role.host ? ' · 管理员' : '' }}
  1124. <select :value="form.memberIds[index]" :aria-label="`${role.name}对应的机器人`" @change="assignPresetRole(index, ($event.target as HTMLSelectElement).value)">
  1125. <option v-for="a in agents.filter(a => !a.archived && !a.temporaryGoalId)" :key="a.id" :value="a.id">{{ a.name }}</option>
  1126. </select>
  1127. <small>{{ role.description }}</small>
  1128. </label>
  1129. <small>角色分工仅在本群生效,聊天中保留机器人的名称和头像。</small>
  1130. </fieldset>
  1131. <fieldset v-else-if="!isAgentDialog">
  1132. <legend>选择成员</legend>
  1133. <label
  1134. v-for="a in agents.filter((a) =>
  1135. !a.temporaryGoalId && (!a.archived || (dialog === 'editGroup' && editingConversation?.memberIds.includes(a.id))),
  1136. )"
  1137. :key="a.id"
  1138. ><input
  1139. v-model="form.memberIds"
  1140. type="checkbox"
  1141. :value="a.id"
  1142. :disabled="busy || (form.mode !== 'discussion' && dialog === 'editGroup' && (a.id === editingConversation?.administratorId || a.id === form.administratorId)) || (!form.memberIds.includes(a.id) && form.memberIds.length >= 8)"
  1143. />{{ a.name }}</label
  1144. ><small v-if="dialog === 'group' && agents.filter((a) => !a.archived && !a.temporaryGoalId).length < 2"
  1145. >至少需要两个机器人才能创建群聊。</small
  1146. >
  1147. <small v-if="dialog === 'editGroup'">可增减成员,最多 8 位。当前管理员不能移除;如需移除,请先更换管理员并保存。</small>
  1148. <button v-for="a in agents.filter(a => editingConversation?.activeAgentStates?.[a.id])" :key="`stop:${a.id}`" type="button" @click="stopMember(a.id)">停止 {{ a.name }}</button>
  1149. </fieldset>
  1150. <fieldset v-if="dialog === 'editGroup' && Object.keys(form.memberRoles).length">
  1151. <legend>角色分工</legend>
  1152. <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>
  1153. </fieldset>
  1154. <template v-if="!isAgentDialog"
  1155. ><label v-if="form.mode !== 'discussion'"
  1156. >负责人<select v-model="form.administratorId" required>
  1157. <option
  1158. v-for="a in agents.filter((a) => form.memberIds.includes(a.id))"
  1159. :key="a.id"
  1160. :value="a.id"
  1161. >
  1162. {{ a.name }}
  1163. </option>
  1164. </select></label
  1165. >
  1166. <label>群规则(可选)<textarea v-model="form.instructions" rows="3" maxlength="24000" placeholder="例如:回答简洁,重要结论注明来源" /></label>
  1167. <button v-if="knowledgeEnabled" type="button" @click="knowledgePanel?.open('projects', form.memberIds[0], editingConversation?.projectId)">关联项目与共享记忆</button>
  1168. <p v-if="dialog === 'group'" class="group-help">创建后即可聊天。需要交付具体结果时,再开启交付目标。</p>
  1169. <details class="group-options">
  1170. <summary>高级协作设置</summary>
  1171. <label
  1172. >协作方式<select v-model="form.mode">
  1173. <option v-if="knowledgeEnabled" value="discussion">平等讨论</option>
  1174. <option value="host">管理员协调</option>
  1175. <option value="free">自由协作</option>
  1176. </select></label
  1177. >
  1178. <fieldset v-if="form.mode === 'free'">
  1179. <legend>未 @ 时自动回复</legend>
  1180. <label v-for="a in agents.filter((a) => form.memberIds.includes(a.id))" :key="a.id"
  1181. ><input v-model="form.autoReplyIds" type="checkbox" :value="a.id" />{{
  1182. a.name
  1183. }}</label
  1184. >
  1185. </fieldset>
  1186. <label v-if="form.mode !== 'discussion'"
  1187. ><input type="checkbox" :checked="form.maxReplyRounds === -1" @change="form.maxReplyRounds = ($event.target as HTMLInputElement).checked ? -1 : 3" />不限制自动协作轮数</label>
  1188. <label v-if="form.mode !== 'discussion' && form.maxReplyRounds !== -1">自动协作轮数<input
  1189. v-model.number="form.maxReplyRounds"
  1190. type="number"
  1191. min="1"
  1192. max="100"
  1193. required /></label
  1194. >
  1195. </details>
  1196. </template>
  1197. </div>
  1198. <footer>
  1199. <button class="quiet-button" type="button" @click="closeDialog">取消</button
  1200. ><button v-if="!isRemoteAgent" class="solid-button" :disabled="busy || (!isAgentDialog && (form.memberIds.length < (dialog === 'group' ? 2 : 1) || form.memberIds.length > 8))">
  1201. {{ busy ? '保存中…' : '保存' }}
  1202. </button>
  1203. </footer>
  1204. </form>
  1205. </dialog></Teleport>
  1206. <WorkspaceKnowledgePanel v-if="knowledgeEnabled" ref="knowledgePanel" :agents="agents" :conversations="conversations" :conversation-id="active?.id" :revision="knowledgeRevision" @changed="knowledgeChanged" />
  1207. </WorkspaceShell>
  1208. </template>
  1209. <style scoped>
  1210. .knowledge-shortcuts{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:8px 12px}.knowledge-shortcuts button,.knowledge-shortcuts select{min-height:44px;padding:7px 12px;border:1px solid var(--line);border-radius:9px;background:var(--surface);color:var(--text-primary);font:inherit;font-size:13px;cursor:pointer}.knowledge-shortcuts button:hover{background:var(--surface-hover)}.knowledge-shortcuts button:focus-visible,.knowledge-shortcuts select:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.knowledge-shortcuts label{display:flex;align-items:center;gap:8px;font-size:13px}.composer-knowledge{max-width:760px;margin:auto}
  1211. .conversation-with-computer{display:flex;height:100%;min-width:0;min-height:0}.conversation-with-computer>.workspace-chat{flex:1;min-width:0}
  1212. .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}
  1213. .editor {
  1214. border: 1px solid var(--line);
  1215. border-radius: 18px;
  1216. width: min(520px, calc(100vw - 48px));
  1217. max-height: 85vh;
  1218. overflow: hidden;
  1219. background: var(--surface);
  1220. color: var(--text-primary);
  1221. padding: 25px;
  1222. }
  1223. .editor::backdrop {
  1224. background: #0006;
  1225. }
  1226. .editor form{display:flex;flex-direction:column;max-height:calc(85dvh - 32px);min-height:0}
  1227. .editor-content{min-height:0;overflow:auto;padding:0 4px;scrollbar-gutter:stable}
  1228. .editor header,.editor footer{flex-shrink:0}
  1229. .editor header{min-height:44px}
  1230. .editor .remote-picker,.editor footer button{min-height:44px;padding:8px 14px;border:1px solid var(--line);border-radius:10px;background:var(--surface);color:var(--text-primary);font:inherit;font-size:13px;cursor:pointer}
  1231. .editor .remote-picker:hover,.editor footer .quiet-button:hover{background:var(--surface-hover)}
  1232. .editor footer .solid-button{background:var(--text-primary);color:var(--surface);border-color:var(--text-primary)}
  1233. .editor footer button:disabled{opacity:.5;cursor:default}
  1234. .editor .remote-picker:focus-visible,.editor footer button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
  1235. .editor header,
  1236. .editor footer {
  1237. display: flex;
  1238. align-items: center;
  1239. justify-content: space-between;
  1240. gap: 12px;
  1241. }
  1242. .editor h2 {
  1243. font-size: 20px;
  1244. margin: 12px 0;
  1245. }
  1246. .editor label {
  1247. display: flex;
  1248. flex-direction: column;
  1249. gap: 7px;
  1250. margin: 15px 0;
  1251. font-size: 13px;
  1252. }
  1253. .task-picker-shell{position:relative;display:inline-flex;align-items:center;max-width:210px;min-width:0}.task-picker-shell>.app-icon{position:absolute;right:11px;pointer-events:none;color:var(--text-muted)}.task-picker{width:100%;min-width:0;max-width:210px;min-height:38px;appearance:none;border:1px solid var(--line);border-radius:999px;background:var(--surface);color:var(--text-primary);padding:6px 34px 6px 14px;font:inherit;font-size:12px;font-weight:520;text-overflow:ellipsis;cursor:pointer;box-shadow:0 1px 2px color-mix(in srgb,var(--text-primary) 5%,transparent);transition:border-color 140ms ease,background-color 140ms ease,box-shadow 140ms ease}.task-picker:hover{border-color:var(--line-strong);background:var(--surface-hover)}.task-picker:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.task-picker:disabled{cursor:wait;opacity:.55}
  1254. .task-queue-status{min-width:0;overflow:hidden;margin:0;font-size:12px;line-height:20px;color:var(--text-muted);text-overflow:ellipsis;white-space:nowrap}.task-queue-status button{padding:0;border:0;background:transparent;color:inherit;font:inherit;cursor:pointer}.task-queue-status button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
  1255. .group-options{margin:12px 0;border-top:1px solid var(--line)}.group-options summary{min-height:44px;align-content:center;cursor:pointer;font-size:13px;color:var(--text-secondary)}.group-options summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.group-help{font-size:13px;line-height:1.6;color:var(--text-secondary)}
  1256. @media(max-width:720px){.task-picker-shell,.task-picker{max-width:118px}.task-picker{min-height:44px;padding-left:12px}}
  1257. .team-management-permission > span {
  1258. display: flex;
  1259. align-items: center;
  1260. gap: 8px;
  1261. min-height: 44px;
  1262. }
  1263. .team-management-permission small {
  1264. color: var(--text-muted);
  1265. line-height: 1.6;
  1266. }
  1267. .editor input:not([type='checkbox']),
  1268. .editor textarea,
  1269. .editor select,
  1270. .interaction input {
  1271. padding: 10px;
  1272. border: 1px solid var(--line);
  1273. border-radius: 8px;
  1274. background: var(--surface-soft);
  1275. color: inherit;
  1276. font: inherit;
  1277. }
  1278. .editor fieldset {
  1279. border: 1px solid var(--line);
  1280. border-radius: 10px;
  1281. }
  1282. .editor fieldset label {
  1283. flex-direction: row;
  1284. align-items: center;
  1285. }
  1286. .editor footer {
  1287. justify-content: flex-end;
  1288. margin-top: 12px;
  1289. }
  1290. .status {
  1291. margin-top: 8px;
  1292. }
  1293. .workspace-list-back{display:none}@media(max-width:900px){.workspace-list-back{display:grid}}
  1294. .search-delete{display:inline-flex;flex:0 0 auto;align-items:center;justify-content:center;gap:5px;min-width:64px;min-height:44px;margin-right:4px;padding:6px 9px;border:0;border-radius:8px;background:transparent;color:var(--danger);font:12px var(--font-ui);cursor:pointer}
  1295. .search-delete:hover:not(:disabled){background:var(--surface-hover)}
  1296. .search-delete:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
  1297. .search-delete:disabled{opacity:.5;cursor:wait}
  1298. .search-delete-error{margin:0;padding:10px 16px 14px;color:var(--danger);font-size:12px;line-height:1.5}
  1299. .search-lifecycle-actions{display:flex;flex:0 0 auto;align-items:center;gap:2px}
  1300. .search-restore{min-height:44px;padding:6px 8px;border:0;border-radius:8px;background:transparent;color:var(--text-secondary);font:12px var(--font-ui);cursor:pointer;white-space:nowrap}
  1301. .search-restore:hover:not(:disabled){background:var(--surface-hover)}
  1302. .search-restore:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
  1303. .search-restore:disabled{opacity:.5;cursor:wait}
  1304. .lifecycle-error{position:fixed;z-index:220;left:50%;bottom:max(24px,env(safe-area-inset-bottom));transform:translateX(-50%);display:flex;align-items:flex-start;gap:12px;width:max-content;max-width:min(520px,calc(100vw - 32px));padding:14px 16px;border:1px solid var(--line);border-radius:12px;background:var(--surface-raised);box-shadow:var(--shadow-float);color:var(--danger);font-size:13px;line-height:1.6}
  1305. .lifecycle-error button{display:grid;place-items:center;flex:0 0 28px;width:28px;height:28px;border:0;border-radius:6px;background:transparent;color:var(--text-secondary);cursor:pointer}
  1306. .lifecycle-error button:hover{background:var(--surface-hover)}
  1307. .lifecycle-error button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
  1308. </style>