chat.svelte 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <script lang="ts">
  2. import { MessageSquareOff, Send, Square } from '@lucide/svelte';
  3. import * as agentsApi from '$lib/api/agents';
  4. import { GlassPane } from '$lib/components/common/glass-pane';
  5. import { Button } from '$lib/components/controls/button';
  6. import { Textarea } from '$lib/components/controls/textarea';
  7. import type { Agent } from '$lib/types/entities';
  8. let { workspaceId, agent }: { workspaceId: string; agent: Agent } = $props();
  9. let systemPrompt = $state('');
  10. let messages = $state<agentsApi.ChatMessage[]>([]);
  11. let inputText = $state('');
  12. let chatLoading = $state(false);
  13. let chatError = $state<string | null>(null);
  14. let chatAbortController = $state<AbortController | null>(null);
  15. let threadEndEl = $state<HTMLDivElement | undefined>(undefined);
  16. let sessionId = $state<string | undefined>(undefined);
  17. $effect(() => {
  18. void agent.id;
  19. messages = [];
  20. chatError = null;
  21. sessionId = undefined;
  22. });
  23. $effect(() => {
  24. // Access every message's content so this re-runs during streaming.
  25. for (const m of messages) void m.content;
  26. threadEndEl?.scrollIntoView({ block: 'nearest' });
  27. });
  28. const sendChat = async () => {
  29. if (!agent || !inputText.trim() || chatLoading) return;
  30. const userText = inputText.trim();
  31. inputText = '';
  32. chatError = null;
  33. const outMessages: agentsApi.ChatMessage[] = [
  34. ...(systemPrompt.trim() ? [{ role: 'system' as const, content: systemPrompt.trim() }] : []),
  35. ...messages,
  36. { role: 'user', content: userText },
  37. ];
  38. messages.push({ role: 'user', content: userText });
  39. const assistantIdx = messages.length;
  40. messages.push({ role: 'assistant', content: '' });
  41. chatLoading = true;
  42. const ctrl = new AbortController();
  43. chatAbortController = ctrl;
  44. try {
  45. const res = await agentsApi.testChatCompletion(
  46. workspaceId,
  47. agent.id,
  48. {
  49. messages: outMessages,
  50. sessionId,
  51. },
  52. ctrl.signal,
  53. );
  54. if (!res.ok) {
  55. const errBody = (await res.json().catch(() => ({ message: res.statusText }))) as {
  56. message?: string;
  57. };
  58. throw new Error(errBody.message ?? res.statusText);
  59. }
  60. sessionId = res.headers.get(agentsApi.SESSION_ID_HEADER) ?? sessionId;
  61. const reader = res.body!.getReader();
  62. const decoder = new TextDecoder();
  63. let buf = '';
  64. for (;;) {
  65. const { done, value } = await reader.read();
  66. if (done) break;
  67. buf += decoder.decode(value, { stream: true });
  68. const lines = buf.split('\n');
  69. buf = lines.pop() ?? '';
  70. for (const line of lines) {
  71. if (!line.startsWith('data: ')) continue;
  72. const chunk = line.slice(6).trim();
  73. if (chunk === '[DONE]') continue;
  74. try {
  75. const parsed = JSON.parse(chunk) as {
  76. choices?: [{ delta?: { content?: string } }];
  77. };
  78. const delta = parsed.choices?.[0]?.delta?.content ?? '';
  79. if (delta) messages[assistantIdx].content += delta;
  80. } catch {
  81. // skip malformed chunk
  82. }
  83. }
  84. }
  85. } catch (err) {
  86. if (err instanceof Error && err.name === 'AbortError') return;
  87. messages.splice(assistantIdx, 1);
  88. chatError = err instanceof Error ? err.message : 'An error occurred';
  89. } finally {
  90. chatLoading = false;
  91. chatAbortController = null;
  92. }
  93. };
  94. const stopChat = () => {
  95. chatAbortController?.abort();
  96. };
  97. const clearSession = () => {
  98. messages = [];
  99. systemPrompt = '';
  100. chatError = null;
  101. sessionId = undefined;
  102. };
  103. const onChatKeydown = (e: KeyboardEvent) => {
  104. if (e.key === 'Enter' && !e.shiftKey) {
  105. e.preventDefault();
  106. sendChat();
  107. }
  108. };
  109. </script>
  110. <GlassPane class="overflow-hidden bg-black/25">
  111. <div class="bg-white/5 p-4">
  112. <div class="flex items-center justify-between">
  113. <p class="text-lg font-thin">Chat</p>
  114. <Button
  115. class="text-white/50"
  116. size="sm"
  117. title="Clear session"
  118. variant="ghost"
  119. onclick={() => clearSession()}
  120. >
  121. <MessageSquareOff size={18} strokeWidth={2} />
  122. </Button>
  123. </div>
  124. </div>
  125. <!-- Message thread -->
  126. <div class="h-96 overflow-y-auto rounded-lg p-4">
  127. {#each messages as msg, i (i)}
  128. {#if msg.role === 'user'}
  129. <div class="mb-3 flex justify-end">
  130. <div
  131. class="max-w-[80%] rounded-2xl rounded-tr-sm bg-primary/40 px-4 py-2 text-sm text-white/90"
  132. >
  133. {msg.content}
  134. </div>
  135. </div>
  136. {:else if msg.role === 'assistant'}
  137. <div class="mb-3 flex justify-start">
  138. <div
  139. class="max-w-[80%] rounded-2xl rounded-tl-sm border border-white/10 bg-white/5 px-4 py-2 text-sm text-white/80"
  140. >
  141. {#if msg.content}
  142. <pre class="font-sans whitespace-pre-wrap">{msg.content}</pre>
  143. {:else}
  144. <span class="animate-pulse text-white/30">▋</span>
  145. {/if}
  146. </div>
  147. </div>
  148. {/if}
  149. {:else}
  150. <div class="flex h-full items-center justify-center">
  151. <p class="text-sm text-white/50">Send a message to start the conversation.</p>
  152. </div>
  153. {/each}
  154. {#if chatError}
  155. <div class="mt-2 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-300">
  156. {chatError}
  157. </div>
  158. {/if}
  159. <div bind:this={threadEndEl}></div>
  160. </div>
  161. <div class="shrink-0 bg-white/5 px-4 pt-4 pb-2">
  162. <Textarea
  163. class="max-h-40 min-h-16 border-white/10 bg-white/5 pr-10 text-sm text-white/90 placeholder:text-white/30"
  164. rows={2}
  165. bind:value={inputText}
  166. onkeydown={(e) => onChatKeydown(e)}
  167. />
  168. <div class="mt-2 flex items-start justify-between">
  169. <p class="truncate text-xs text-white/30">Enter to send, Shift+Enter for newline.</p>
  170. <Button
  171. disabled={inputText.trim().length === 0}
  172. size="icon"
  173. title={chatLoading ? 'Stop' : 'Send'}
  174. variant="ghost"
  175. onclick={() => {
  176. if (chatLoading) {
  177. stopChat();
  178. } else {
  179. sendChat();
  180. }
  181. }}
  182. >
  183. {#if chatLoading}
  184. <Square size={18} strokeWidth={2} />
  185. {:else}
  186. <Send class="text-primary" size={18} strokeWidth={2} />
  187. {/if}
  188. </Button>
  189. </div>
  190. </div>
  191. </GlassPane>