()
| 46 | } |
| 47 | |
| 48 | function startRun() { |
| 49 | const prompt = promptEl.value.trim(); |
| 50 | if (!prompt) return; |
| 51 | |
| 52 | clearPhases(); |
| 53 | setStatus("运行中..."); |
| 54 | runBtn.disabled = true; |
| 55 | |
| 56 | if (currentController) { |
| 57 | currentController.abort(); |
| 58 | } |
| 59 | currentController = new AbortController(); |
| 60 | |
| 61 | fetch("/api/chat/stream", { |
| 62 | method: "POST", |
| 63 | headers: { "Content-Type": "application/json" }, |
| 64 | body: JSON.stringify({ input: prompt }), |
| 65 | signal: currentController.signal, |
| 66 | }) |
| 67 | .then((response) => { |
| 68 | if (!response.ok) { |
| 69 | appendPhaseLine(`请求失败: ${response.status}`, "error"); |
| 70 | setStatus("请求失败"); |
| 71 | runBtn.disabled = false; |
| 72 | return; |
| 73 | } |
| 74 | |
| 75 | const reader = response.body.getReader(); |
| 76 | const decoder = new TextDecoder("utf-8"); |
| 77 | let buffer = ""; |
| 78 | const uiState = { currentPhase: null, textStarted: false }; |
| 79 | |
| 80 | function pump() { |
| 81 | reader |
| 82 | .read() |
| 83 | .then(({ done, value }) => { |
| 84 | if (done) { |
| 85 | setStatus("完成"); |
| 86 | runBtn.disabled = false; |
| 87 | return; |
| 88 | } |
| 89 | buffer += decoder.decode(value, { stream: true }); |
| 90 | let idx; |
| 91 | while ((idx = buffer.indexOf("\n\n")) >= 0) { |
| 92 | const raw = buffer.slice(0, idx); |
| 93 | buffer = buffer.slice(idx + 2); |
| 94 | handleSSEChunk(raw, uiState); |
| 95 | } |
| 96 | pump(); |
| 97 | }) |
| 98 | .catch((err) => { |
| 99 | if (err.name !== "AbortError") { |
| 100 | appendPhaseLine(`流式读取出错: ${err}`, "error"); |
| 101 | setStatus("出错"); |
| 102 | runBtn.disabled = false; |
| 103 | } |
| 104 | }); |
| 105 | } |
no test coverage detected