( input: ChatInputType, token: string, stream: boolean = false // Default to non-streaming for better performance )
| 2 | import authenticatedFetch from '@/lib/authenticatedFetch'; |
| 3 | |
| 4 | export interface ChatStreamHandlers { |
| 5 | /** Assistant text as it arrives. */ |
| 6 | onText?: (delta: string) => void; |
| 7 | /** A tool the agent just invoked, with what it is acting on when known. */ |
| 8 | onTool?: (name: string, target?: string) => void; |
| 9 | /** Turn-level failure reported by the backend. */ |
| 10 | onError?: (message: string) => void; |
| 11 | } |
| 12 | |
| 13 | export interface ChatStreamOptions extends ChatStreamHandlers { |
| 14 | /** Aborts the request; the backend stops the agent when the client hangs up. */ |
| 15 | signal?: AbortSignal; |
| 16 | /** Attached images as `data:<mime>;base64,<data>` URLs. */ |
| 17 | images?: string[]; |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Runs one agent turn and returns the assembled assistant text. |
| 22 | * |
| 23 | * The backend streams newline-delimited JSON events rather than raw text, so |
| 24 | * the caller can show which tool is running and which files changed while the |
| 25 | * turn is still in flight. |
| 26 | */ |
| 27 | export const startChatStream = async ( |
| 28 | input: ChatInputType, |
| 29 | token: string, |
| 30 | { onText, onTool, onError, signal, images }: ChatStreamOptions = {} |
| 31 | ): Promise<string> => { |
| 32 | if (!token) { |
| 33 | throw new Error('Not authenticated'); |
| 34 | } |
| 35 | |
| 36 | const { chatId, message, model } = input; |
| 37 | const response = await authenticatedFetch('/api/chat', { |
| 38 | method: 'POST', |
| 39 | headers: { |
| 40 | 'Content-Type': 'application/json', |
| 41 | Authorization: `Bearer ${token}`, |
| 42 | }, |
| 43 | body: JSON.stringify({ chatId, message, model, images }), |
| 44 | signal, |
| 45 | }); |
| 46 | |
| 47 | if (!response.ok) { |
| 48 | throw new Error( |
| 49 | `Network response was not ok: ${response.status} ${response.statusText}` |
| 50 | ); |
| 51 | } |
| 52 | |
| 53 | const reader = response.body?.getReader(); |
| 54 | if (!reader) { |
| 55 | throw new Error('No response body to read'); |
| 56 | } |
| 57 | |
| 58 | const decoder = new TextDecoder(); |
| 59 | let buffer = ''; |
| 60 | let content = ''; |
| 61 |
no test coverage detected