diff --git a/src/assets/js/main.js b/src/assets/js/main.js index 3a3f7e9..7840afb 100644 --- a/src/assets/js/main.js +++ b/src/assets/js/main.js @@ -23,16 +23,41 @@ async function sendGen() { async function readResponse(response) { const reader = response.body.getReader(); const decoder = new TextDecoder('utf-8'); - let done = false; try { - while (!done) { - const { value, done: readerDone } = await reader.read(); - done = readerDone; - const chunk = decoder.decode(value, { stream: true }); - outputArea.innerHTML += chunk; - outputArea.scrollTop = outputArea.scrollHeight; + // Recursive function to read the stream + function read() { + reader.read().then(({ value, done }) => { + if (done) { + console.log("Stream complete"); + return; + } + + // Decode the stream chunk and split into lines + const chunk = decoder.decode(value, { stream: true }); + const lines = chunk.split(/\r?\n/); // Split by newlines + + // Process each line + for (const line of lines) { + if (line.trim()) { // Skip empty lines + try { + const json = JSON.parse(line); // Parse each line as JSON + if (json.response) { + textbox.value += json.response; // Append response text to the textbox + } + } catch (err) { + console.error("Failed to parse JSON:", err, line); + } + } + } + + // Continue reading + read(); + }); } + + // Start reading + read(); } catch (error) { outputArea.innerHTML = `Error: ${error.message}`; }