| 15 | providedIn: 'root' |
| 16 | }) |
| 17 | export class ChatService { |
| 18 | private router = inject(Router); |
| 19 | private magicAiService = inject(MagicAiService); |
| 20 | conversationHistory = linkedSignal<string|undefined, Message[]>({ |
| 21 | source: () => this.magicAiService.agentResponse(), |
| 22 | computation: (agentResponse, prev) => { |
| 23 | if (!agentResponse) { |
| 24 | return prev?.value || []; |
| 25 | } |
| 26 | |
| 27 | const message: Message = { author: 'agent', text: agentResponse }; |
| 28 | if (prev && prev?.value.at(-1)?.author === 'agent') { |
| 29 | const newHistory: Message[] = prev.value.slice(0, -1); |
| 30 | return [...newHistory, message]; |
| 31 | } else if (!prev || prev?.value.length === 0) { |
| 32 | return [message]; |
| 33 | } else { |
| 34 | return [...prev.value, message]; |
| 35 | } |
| 36 | } |
| 37 | }); |
| 38 | |
| 39 | nextIndex = computed(() => this.conversationHistory() |
| 40 | .filter(message => message.author === 'agent').length); |
| 41 | |
| 42 | addUserPrompt(newPrompt: string): void { |
| 43 | if (!this.magicAiService.isStreamComplete()) { |
| 44 | return; |
| 45 | } |
| 46 | |
| 47 | this.magicAiService.prompt.set(newPrompt); |
| 48 | this.router.navigate([`/magic/${this.nextIndex()}`]); |
| 49 | this.addToConversation({ author: 'user', text: newPrompt }); |
| 50 | } |
| 51 | |
| 52 | addToConversation(message: Message): void { |
| 53 | this.conversationHistory.update(history => { |
| 54 | if (!history.length) { |
| 55 | return [message]; |
| 56 | } else if (history[history.length - 1].text === message.text) { |
| 57 | return history; |
| 58 | } else { |
| 59 | return [...history, message] |
| 60 | } |
| 61 | }); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | export interface Message { |
| 66 | author: 'user' | 'agent'; |
nothing calls this directly
no outgoing calls
no test coverage detected