Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conversation.component.ts 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { MatCardModule } from '@angular/material/card';
  4. import { MatButtonModule } from '@angular/material/button';
  5. import { MatIconModule } from '@angular/material/icon';
  6. import { MatInputModule } from '@angular/material/input';
  7. import { MatFormFieldModule } from '@angular/material/form-field';
  8. import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
  9. import { FormsModule } from '@angular/forms';
  10. import { Subscription } from 'rxjs';
  11. import { ConversationService } from '../services/conversation.service';
  12. import { SessionService } from '../services/session.service';
  13. import { ChatMessage } from '../models/conversation.model';
  14. import { Session } from '../models/session.model';
  15. @Component({
  16. selector: 'app-conversation',
  17. standalone: true,
  18. imports: [
  19. CommonModule,
  20. MatCardModule,
  21. MatButtonModule,
  22. MatIconModule,
  23. MatInputModule,
  24. MatFormFieldModule,
  25. MatProgressSpinnerModule,
  26. FormsModule
  27. ],
  28. template: `
  29. <div class="conversation-container">
  30. <!-- 消息区域 -->
  31. <div class="messages-container" #messagesContainer>
  32. <div *ngFor="let message of messages" class="message-wrapper">
  33. <div class="message" [class.user]="message.role === 'user'" [class.assistant]="message.role === 'assistant'">
  34. <div class="message-header">
  35. <mat-icon class="message-icon">{{ message.role === 'user' ? 'person' : 'smart_toy' }}</mat-icon>
  36. <span class="message-role">{{ message.role === 'user' ? '用户' : 'AI助手' }}</span>
  37. <span class="message-time">{{ message.timestamp | date:'HH:mm' }}</span>
  38. </div>
  39. <div class="message-content">
  40. <div [innerHTML]="formatContent(message.content)"></div>
  41. <mat-spinner *ngIf="message.loading" diameter="20" class="loading-spinner"></mat-spinner>
  42. </div>
  43. </div>
  44. </div>
  45. <div *ngIf="messages.length === 0" class="empty-state">
  46. <mat-icon>forum</mat-icon>
  47. <h3>开始对话</h3>
  48. <p>选择或创建一个会话来开始对话</p>
  49. </div>
  50. </div>
  51. <!-- 输入区域 -->
  52. <div class="input-container" *ngIf="activeSession">
  53. <mat-form-field appearance="outline" class="input-field">
  54. <mat-label>输入消息...</mat-label>
  55. <textarea
  56. matInput
  57. [(ngModel)]="userInput"
  58. (keydown.enter)="onSendMessage($event)"
  59. placeholder="输入消息,按Enter发送,Shift+Enter换行"
  60. rows="3"
  61. #messageInput
  62. ></textarea>
  63. </mat-form-field>
  64. <button
  65. mat-raised-button
  66. color="primary"
  67. class="send-button"
  68. (click)="sendMessage()"
  69. [disabled]="!userInput.trim()"
  70. >
  71. <mat-icon *ngIf="!isLoading">send</mat-icon>
  72. <mat-spinner *ngIf="isLoading" diameter="20"></mat-spinner>
  73. </button>
  74. </div>
  75. <div *ngIf="!activeSession" class="no-session">
  76. <p>请先选择或创建一个会话</p>
  77. </div>
  78. </div>
  79. `,
  80. styles: [`
  81. .conversation-container {
  82. height: 100%;
  83. display: flex;
  84. flex-direction: column;
  85. min-height: 0;
  86. }
  87. .messages-container {
  88. flex: 1;
  89. overflow-y: auto;
  90. padding: 20px;
  91. background: #fafafa;
  92. min-height: 0;
  93. }
  94. .message-wrapper {
  95. margin-bottom: 20px;
  96. }
  97. .message {
  98. max-width: 80%;
  99. padding: 12px 16px;
  100. border-radius: 18px;
  101. position: relative;
  102. }
  103. .message.user {
  104. background: #007bff;
  105. color: white;
  106. margin-left: auto;
  107. border-bottom-right-radius: 4px;
  108. }
  109. .message.assistant {
  110. background: white;
  111. color: #333;
  112. border: 1px solid #e0e0e0;
  113. margin-right: auto;
  114. border-bottom-left-radius: 4px;
  115. }
  116. .message-header {
  117. display: flex;
  118. align-items: center;
  119. margin-bottom: 8px;
  120. font-size: 12px;
  121. opacity: 0.8;
  122. }
  123. .message-icon {
  124. font-size: 16px;
  125. height: 16px;
  126. width: 16px;
  127. margin-right: 6px;
  128. }
  129. .message-role {
  130. font-weight: 500;
  131. margin-right: 8px;
  132. }
  133. .message-time {
  134. margin-left: auto;
  135. }
  136. .message-content {
  137. line-height: 1.5;
  138. white-space: pre-wrap;
  139. }
  140. .user .message-content {
  141. color: white;
  142. }
  143. .loading-spinner {
  144. display: inline-block;
  145. margin-left: 8px;
  146. }
  147. .input-container {
  148. display: flex;
  149. gap: 12px;
  150. padding: 16px;
  151. border-top: 1px solid #e0e0e0;
  152. background: white;
  153. flex-shrink: 0;
  154. }
  155. .input-field {
  156. flex: 1;
  157. }
  158. .send-button {
  159. align-self: flex-end;
  160. height: 56px;
  161. min-width: 56px;
  162. }
  163. .empty-state {
  164. text-align: center;
  165. padding: 60px 20px;
  166. color: #666;
  167. }
  168. .empty-state mat-icon {
  169. font-size: 64px;
  170. height: 64px;
  171. width: 64px;
  172. margin-bottom: 16px;
  173. color: #ccc;
  174. }
  175. .no-session {
  176. padding: 20px;
  177. text-align: center;
  178. color: #666;
  179. background: #f5f5f5;
  180. }
  181. `]
  182. })
  183. export class ConversationComponent implements OnInit, OnDestroy, AfterViewChecked {
  184. @ViewChild('messagesContainer') private messagesContainer!: ElementRef;
  185. @ViewChild('messageInput') private messageInput!: ElementRef;
  186. messages: ChatMessage[] = [];
  187. userInput = '';
  188. isLoading = false;
  189. activeSession: Session | null = null;
  190. private subscriptions: Subscription = new Subscription();
  191. private currentStreamSubscription: Subscription | null = null;
  192. private shouldScroll = false;
  193. constructor(
  194. private conversationService: ConversationService,
  195. private sessionService: SessionService
  196. ) {}
  197. ngOnInit() {
  198. // 订阅活动会话变化
  199. this.subscriptions.add(
  200. this.sessionService.activeSession$.subscribe(session => {
  201. console.log('🔍 [ConversationComponent] 活动会话变化:', session?.id);
  202. // 会话切换时取消当前正在进行的流式请求
  203. if (this.activeSession && this.activeSession.id !== session?.id) {
  204. console.log('🔍 [ConversationComponent] 会话切换,取消当前流式请求');
  205. this.cancelCurrentStream();
  206. }
  207. this.activeSession = session;
  208. if (session) {
  209. this.loadMessages(session.id);
  210. } else {
  211. this.messages = [];
  212. }
  213. })
  214. );
  215. // 订阅新消息
  216. this.subscriptions.add(
  217. this.conversationService.newMessage$.subscribe(message => {
  218. if (message) {
  219. this.messages.push(message);
  220. this.shouldScroll = true;
  221. }
  222. })
  223. );
  224. // 订阅流式更新
  225. this.subscriptions.add(
  226. this.conversationService.streamUpdate$.subscribe(update => {
  227. if (update.type === 'text') {
  228. // 更新最后一条消息的内容
  229. const lastMessage = this.messages[this.messages.length - 1];
  230. if (lastMessage && lastMessage.role === 'assistant') {
  231. lastMessage.content += update.data;
  232. this.shouldScroll = true;
  233. }
  234. } else if (update.type === 'done') {
  235. // 标记加载完成
  236. const lastMessage = this.messages[this.messages.length - 1];
  237. if (lastMessage) {
  238. lastMessage.loading = false;
  239. }
  240. // 重置加载状态并聚焦输入框
  241. this.isLoading = false;
  242. this.focusInput();
  243. } else if (update.type === 'error') {
  244. // 处理错误情况
  245. const lastMessage = this.messages[this.messages.length - 1];
  246. if (lastMessage && lastMessage.role === 'assistant') {
  247. lastMessage.content += '\n\n[错误: ' + update.data + ']';
  248. lastMessage.loading = false;
  249. }
  250. // 重置加载状态并聚焦输入框
  251. this.isLoading = false;
  252. this.focusInput();
  253. }
  254. })
  255. );
  256. }
  257. ngAfterViewChecked() {
  258. if (this.shouldScroll) {
  259. this.scrollToBottom();
  260. this.shouldScroll = false;
  261. }
  262. }
  263. ngOnDestroy() {
  264. this.subscriptions.unsubscribe();
  265. this.cancelCurrentStream();
  266. }
  267. // 取消当前的流式请求
  268. private cancelCurrentStream() {
  269. if (this.currentStreamSubscription) {
  270. console.log('🔍 [ConversationComponent] 取消当前的流式请求');
  271. this.currentStreamSubscription.unsubscribe();
  272. this.currentStreamSubscription = null;
  273. }
  274. // 重置加载状态
  275. if (this.isLoading) {
  276. this.isLoading = false;
  277. }
  278. }
  279. loadMessages(sessionId: string) {
  280. this.messages = [];
  281. // 实际应该从服务加载历史消息
  282. // 暂时为空
  283. }
  284. onSendMessage(event: any) {
  285. if (event.key === 'Enter' && !event.shiftKey) {
  286. event.preventDefault();
  287. this.sendMessage();
  288. }
  289. }
  290. sendMessage() {
  291. if (!this.userInput.trim() || !this.activeSession) return;
  292. // 取消之前可能仍在进行的流式请求(允许打断之前的回答)
  293. this.cancelCurrentStream();
  294. const userMessage: ChatMessage = {
  295. id: Date.now().toString(),
  296. role: 'user',
  297. content: this.userInput,
  298. timestamp: new Date(),
  299. sessionID: this.activeSession.id
  300. };
  301. // 添加用户消息
  302. this.messages.push(userMessage);
  303. this.shouldScroll = true;
  304. // 添加AI响应占位
  305. const aiMessage: ChatMessage = {
  306. id: (Date.now() + 1).toString(),
  307. role: 'assistant',
  308. content: '',
  309. timestamp: new Date(),
  310. sessionID: this.activeSession.id,
  311. loading: true
  312. };
  313. this.messages.push(aiMessage);
  314. this.shouldScroll = true;
  315. // 发送到服务
  316. this.isLoading = true;
  317. this.currentStreamSubscription = this.conversationService.sendMessage(
  318. this.activeSession.id,
  319. this.userInput
  320. ).subscribe({
  321. next: () => {
  322. // 流式连接已建立,但传输仍在继续
  323. // isLoading状态将在流式完成时在streamUpdate$中重置
  324. },
  325. error: (error) => {
  326. console.error('发送消息失败:', error);
  327. aiMessage.content = '抱歉,发送消息时出现错误: ' + error.message;
  328. aiMessage.loading = false;
  329. this.isLoading = false;
  330. this.currentStreamSubscription = null;
  331. this.focusInput();
  332. },
  333. complete: () => {
  334. // 流式完成已在streamUpdate$中处理
  335. this.currentStreamSubscription = null;
  336. }
  337. });
  338. // 清空输入框
  339. this.userInput = '';
  340. // 聚焦输入框
  341. this.focusInput();
  342. }
  343. formatContent(content: string): string {
  344. // 简单的格式化,可扩展为Markdown渲染
  345. return content.replace(/\n/g, '<br>');
  346. }
  347. private scrollToBottom() {
  348. try {
  349. this.messagesContainer.nativeElement.scrollTop =
  350. this.messagesContainer.nativeElement.scrollHeight;
  351. } catch (err) {
  352. console.error('滚动失败:', err);
  353. }
  354. }
  355. private focusInput() {
  356. // 延迟聚焦以确保DOM已更新
  357. setTimeout(() => {
  358. if (this.messageInput?.nativeElement) {
  359. this.messageInput.nativeElement.focus();
  360. }
  361. }, 100);
  362. }
  363. }