From e04117b8ff8b8bea45e72bad5825b0ecc5b5037a Mon Sep 17 00:00:00 2001 From: kim Date: Tue, 29 Sep 2026 01:07:39 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=EC=8B=A4=EC=8B=9C=EA=B0=84=20=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EB=A6=BC=EC=97=90=EC=84=9C=20=20=ED=83=9C?= =?UTF-8?q?=EA=B7=B8=EA=B0=80=20=EA=B7=B8=EB=8C=80=EB=A1=9C=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=EC=97=90=20=EB=85=B8=EC=B6=9C=EB=90=98=EB=8D=98=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit glm-5.3-flash:cloud 등 일부 모델은 Ollama 네이티브 thinking 필드 대신 content 스트림 안에 평문으로 ...를 섞어 보낸다. ollama-adapter.ts의 chatStream은 매 청크를 오는 즉시 onToken()→SSE 'token' 이벤트로 그대로 화면에 흘려보내서, 이 경우 태그가 실시간으로 그대로 노출됐다(2026-09-29 작업실 채팅 신고: "를 계속 내놓고 있네"). 완결된 텍스트에서 사후에 정규식으로 거르는 stripExplicitThinkTags/ separateThinkingFromContent는 스트림 도중엔 무력하다 — 닫는 태그가 아직 안 와서 어디까지가 think 블록인지 알 방법이 없다. 그래서 저장된 세션 기록은 깨끗한데 실시간 화면에만 태그가 보였다. - src/providers/stream-think-filter.ts(신규): 청크를 실시간으로 받아 구간만 억제하는 스트림 필터. 태그가 청크 경계에서 쪼개져도("") 접두사 매칭으로 잡는다(무조건 N바이트 홀드가 아니라 실제 접두사 일치分만 보류 — 정상 텍스트 지연 방지). 진입/이탈 시 상태 콜백도 지원. - ollama-adapter.ts: onToken 직접 호출을 이 필터 경유로 교체. fullContent는 그대로 원문을 쌓아서 기존 사후 정리 로직은 안 건드림. - LLMProvider.ts/ollama-client.ts/handle-chat.ts: onThinkingStatus 콜백을 체인으로 연결해 새 SSE 'thinking_status' 이벤트로 내보냄. - workshop-chat.js: 'thinking_status' active 동안 "(생각 중…)" 표시(사용자 요청) — 이전엔 토큰/텍스트델타 외 이벤트를 다 무시해서 GLM이 오래 생각할 때 화면이 멈춘 것처럼 보였다. 신규 유닛테스트 9건(청크 경계 분할, 여러 think 블록, dangling 태그, 상태 콜백 등). 전체 스위트 745/745 통과. Co-Authored-By: Claude Sonnet 5 --- src/agents/ollama-client.ts | 2 + src/gateway/chat/handle-chat.ts | 5 ++ src/providers/LLMProvider.ts | 4 + src/providers/ollama-adapter.ts | 15 +++- src/providers/stream-think-filter.ts | 100 +++++++++++++++++++++++++ tests/stream-think-filter.test.ts | 105 +++++++++++++++++++++++++++ web-ui/js/app/workshop-chat.js | 17 ++++- 7 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 src/providers/stream-think-filter.ts create mode 100644 tests/stream-think-filter.test.ts diff --git a/src/agents/ollama-client.ts b/src/agents/ollama-client.ts index 10b3ea3..70b0963 100644 --- a/src/agents/ollama-client.ts +++ b/src/agents/ollama-client.ts @@ -94,6 +94,7 @@ export class OllamaClient { tools?: any[]; tool_choice?: 'auto' | 'required'; model?: string; + onThinkingStatus?: (active: boolean) => void; } ): Promise { const model = String(options?.model || '').trim() || getModelForRole(role); @@ -104,6 +105,7 @@ export class OllamaClient { tools: options?.tools, tool_choice: options?.tool_choice, think: options?.think, + onThinkingStatus: options?.onThinkingStatus, onToken, }; diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index 90350a2..2316a70 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -1507,6 +1507,11 @@ async function handleChat( return pt !== undefined ? pt : primaryThinkMode; })(), model: effectiveModel, + // 실시간 content-임베디드 구간이 억제되는 동안 UI에 "생각중…"을 띄울 수 있게 + // 상태 변화를 알려준다(2026-09-29, 작업실 채팅 " 그대로 나옴" 신고에서 비롯). + onThinkingStatus: (active: boolean) => { + try { sendSSE('thinking_status', { active }); } catch {} + }, }); if ( diff --git a/src/providers/LLMProvider.ts b/src/providers/LLMProvider.ts index a7d5f9c..ef1ba3c 100644 --- a/src/providers/LLMProvider.ts +++ b/src/providers/LLMProvider.ts @@ -45,6 +45,10 @@ export interface ChatOptions { * letting the model answer in plain text — used for models with a documented tendency to * skip tools and fabricate instead (see models.profiles[].forceToolChoiceOnLiveData). */ tool_choice?: 'auto' | 'required'; + /** Fires when a live content-embedded block starts/ends being suppressed from the + * visible token stream (see stream-think-filter.ts) — lets the UI show a "생각중…" placeholder + * instead of going silent while the model reasons. Only relevant to streaming providers. */ + onThinkingStatus?: (active: boolean) => void; } export interface GenerateOptions { diff --git a/src/providers/ollama-adapter.ts b/src/providers/ollama-adapter.ts index 2e7b2ce..6a5c9ee 100644 --- a/src/providers/ollama-adapter.ts +++ b/src/providers/ollama-adapter.ts @@ -9,6 +9,7 @@ import { Ollama } from 'ollama'; import { repairByteFallbackTokens } from './byte-fallback.js'; +import { createThinkTagStreamFilter } from './stream-think-filter.js'; import fs from 'fs'; import path from 'path'; import type { LLMProvider, ChatMessage, ContentPart, ChatOptions, ChatResult, GenerateOptions, GenerateResult, ModelInfo } from './LLMProvider'; @@ -828,10 +829,21 @@ export class OllamaAdapter implements LLMProvider { let promptTokens = 0; let completionTokens = 0; + // glm-5.3-flash:cloud 등 일부 모델은 Ollama 네이티브 thinking 필드 대신 content 안에 + // 평문 `...`를 섞어 보낸다 — onToken을 직접 부르면 그 태그가 실시간으로 + // 화면에 그대로 그려진다(2026-09-29 작업실 채팅 신고). 필터를 거쳐서 think 구간만 + // 억제하고 나머지만 즉시 내보낸다. fullContent는 그대로 원문을 다 쌓아서(아래 로직들이 + // 사후에 stripExplicitThinkTags 등으로 다시 거르는 데 필요) 기존 동작을 안 깬다. + const thinkFilter = createThinkTagStreamFilter( + (visible) => onToken(visible), + (thinkChunk) => { fullThinking += thinkChunk; }, + options.onThinkingStatus, + ); + for await (const chunk of stream) { if (chunk.message?.content) { fullContent += chunk.message.content; - onToken(chunk.message.content); + thinkFilter.push(chunk.message.content); } if (chunk.message?.thinking) { fullThinking += chunk.message.thinking; @@ -845,6 +857,7 @@ export class OllamaAdapter implements LLMProvider { if (typeof (chunk as any).eval_count === 'number') completionTokens = (chunk as any).eval_count; } } + thinkFilter.flush(); // 닫는 태그 없이 스트림이 끝났어도 보류분을 상태에 맞게 내보냄 logUsage(model, promptTokens, completionTokens); message.content = fullContent || message.content || ''; diff --git a/src/providers/stream-think-filter.ts b/src/providers/stream-think-filter.ts new file mode 100644 index 0000000..797850e --- /dev/null +++ b/src/providers/stream-think-filter.ts @@ -0,0 +1,100 @@ +/** + * createThinkTagStreamFilter — 실시간 토큰 스트림에서 `...` 구간을 걸러낸다. + * + * 배경(2026-09-29, 작업실 채팅에서 glm-5.3-flash:cloud가 ""를 그대로 내놓는다고 신고됨): + * Ollama 네이티브 thinking API를 쓰는 모델은 추론을 `chunk.message.thinking` 필드로 따로 주고, + * ollama-adapter.ts는 그건 원래부터 onToken에 안 실어 보낸다(정상). 근데 glm-5.3-flash:cloud는 + * 그 필드를 안 쓰고 그냥 `chunk.message.content` 안에 평문으로 `...`를 섞어 + * 보낸다 — 이건 매 토큰이 오는 즉시 onToken()→SSE 'token' 이벤트로 화면에 바로 그려지므로, + * 완결된 텍스트를 사후에 정규식으로 거르는 stripExplicitThinkTags/separateThinkingFromContent + * (둘 다 handle-chat.ts/server.ts에 있음, 스트림 끝난 뒤의 fullContent에만 적용됨)로는 못 막는다 + * — 닫는 태그가 아직 도착하기 전이라 "이게 think 블록이다"를 알 방법이 없기 때문. 그래서 세션 + * 기록(저장된 history)은 깨끗한데 실시간 화면에는 태그가 그대로 지나가는 걸로 보였다. + * + * 이 필터는 청크를 실시간으로 받아 `` 구간만 억제하고 나머지만 즉시 내보낸다. 태그가 + * 청크 경계에서 쪼개질 수 있어(예: "") 여는/닫는 태그 길이-1만큼 짧은 보류 버퍼를 + * 둔다 — 그 이상 지연시키지 않는다. + */ +export function createThinkTagStreamFilter( + onVisible: (text: string) => void, + onThinking?: (text: string) => void, + onStatusChange?: (active: boolean) => void, +): { push: (chunk: string) => void; flush: () => void } { + const OPEN = ''; + const CLOSE = ''; + let pending = ''; // 아직 내보내지 않은 원문 꼬리(태그 경계가 불확실한 구간) + let inThink = false; + + function setInThink(v: boolean): void { + if (inThink === v) return; + inThink = v; + if (onStatusChange) onStatusChange(v); + } + + // pending의 끝부분이 needle(예: "")의 앞부분과 실제로 일치하는 가장 긴 길이를 찾는다. + // 그 길이만큼만 보류하면 된다 — 무조건 needle.length-1만큼 홀드하면 태그와 무관한 정상 + // 텍스트 꼬리까지 매번 지연되는 버그가 생긴다(예: "...문장입니다"의 끝 6글자가 ""와 + // 전혀 안 닮았는데도 계속 붙잡힘). + function suffixPrefixOverlap(s: string, needle: string): number { + const maxLen = Math.min(s.length, needle.length - 1); + for (let len = maxLen; len > 0; len--) { + if (s.slice(s.length - len) === needle.slice(0, len)) return len; + } + return 0; + } + + function process(): void { + for (;;) { + if (!inThink) { + const idx = pending.indexOf(OPEN); + if (idx === -1) { + const hold = suffixPrefixOverlap(pending, OPEN); + const safeLen = pending.length - hold; + if (safeLen > 0) { + onVisible(pending.slice(0, safeLen)); + pending = pending.slice(safeLen); + } + return; + } + if (idx > 0) onVisible(pending.slice(0, idx)); + pending = pending.slice(idx + OPEN.length); + setInThink(true); + continue; + } else { + const idx = pending.indexOf(CLOSE); + if (idx === -1) { + const hold = suffixPrefixOverlap(pending, CLOSE); + const safeLen = pending.length - hold; + if (safeLen > 0) { + if (onThinking) onThinking(pending.slice(0, safeLen)); + pending = pending.slice(safeLen); + } + return; + } + if (idx > 0 && onThinking) onThinking(pending.slice(0, idx)); + pending = pending.slice(idx + CLOSE.length); + setInThink(false); + continue; + } + } + } + + return { + push(chunk: string): void { + if (!chunk) return; + pending += chunk; + process(); + }, + flush(): void { + // 스트림 끝 — 닫는 태그 없이 끝난 dangling 도 상태에 맞게 내보낸다. + if (pending) { + if (inThink) { if (onThinking) onThinking(pending); } + else onVisible(pending); + pending = ''; + } + // 닫는 태그 없이 스트림이 끝나 "생각중" 상태로 걸려있으면 UI가 영영 그 상태로 + // 멈추지 않게 마지막에 꺼준다. + setInThink(false); + }, + }; +} diff --git a/tests/stream-think-filter.test.ts b/tests/stream-think-filter.test.ts new file mode 100644 index 0000000..bca005a --- /dev/null +++ b/tests/stream-think-filter.test.ts @@ -0,0 +1,105 @@ +/** + * createThinkTagStreamFilter — content 스트림에 섞인 ... 실시간 억제 + * + * 2026-09-29 실측: 작업실 채팅에서 glm-5.3-flash:cloud가 ""를 그대로 내놓는다는 신고. + * 원인: 이 모델은 Ollama 네이티브 thinking 필드 대신 content 안에 평문으로 를 섞어 + * 보내는데, ollama-adapter.ts의 chatStream이 매 청크를 즉시 onToken()→SSE로 흘려보내서 + * 태그가 실시간 화면에 그대로 노출됐다(완결 후 정규식으로 거르는 stripExplicitThinkTags류는 + * 스트림 도중엔 닫는 태그를 아직 몰라 무력함). 이 필터로 실시간 청크 단계에서 억제한다. + */ + +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { createThinkTagStreamFilter } from '../src/providers/stream-think-filter'; + +function run(chunks: string[]): { visible: string; thinking: string } { + let visible = ''; + let thinking = ''; + const f = createThinkTagStreamFilter( + (t) => { visible += t; }, + (t) => { thinking += t; }, + ); + for (const c of chunks) f.push(c); + f.flush(); + return { visible, thinking }; +} + +describe('createThinkTagStreamFilter', () => { + test('think 태그 없는 평범한 텍스트는 그대로 통과한다', () => { + const { visible, thinking } = run(['안녕', '하세요, ', '혈당은 128입니다.']); + assert.equal(visible, '안녕하세요, 혈당은 128입니다.'); + assert.equal(thinking, ''); + }); + + test('한 청크 안에 완결된 블록을 통째로 억제한다', () => { + const { visible, thinking } = run(['내부 추론최종 답변']); + assert.equal(visible, '최종 답변'); + assert.equal(thinking, '내부 추론'); + }); + + test('여는/닫는 태그가 여러 청크 경계에서 쪼개져도 잡는다(실측 재현: "")', () => { + const { visible, thinking } = run(['앞부분 ', '', '추론 내용', '', ' 뒷부분']); + assert.equal(visible, '앞부분 뒷부분'); + assert.equal(thinking, '추론 내용'); + }); + + test('여는 태그 접두사만 있는 상태로 청크가 끝나도 그 접두사를 화면에 흘리지 않는다', () => { + // "로 스트림이 끝나면(dangling) 남은 걸 thinking으로 흡수하고 화면엔 안 보인다', () => { + const { visible, thinking } = run(['답변 시작 ', '끝까지 안 닫힌 추론']); + assert.equal(visible, '답변 시작 '); + assert.equal(thinking, '끝까지 안 닫힌 추론'); + }); + + test('여러 개의 think 블록이 한 응답에 섞여도 전부 걸러낸다', () => { + const { visible, thinking } = run([ + '첫 생각첫 문장. ', + '둘째 생각둘째 문장.', + ]); + assert.equal(visible, '첫 문장. 둘째 문장.'); + assert.equal(thinking, '첫 생각\n둘째 생각'.replace('\n', '')); // 순서만 확인, 구분자는 안 따짐 + assert.ok(thinking.includes('첫 생각') && thinking.includes('둘째 생각')); + }); + + test('실시간 지연은 태그 길이-1 만큼만 — 정상 텍스트를 과하게 붙잡지 않는다', () => { + const seen: string[] = []; + const f = createThinkTagStreamFilter((t) => seen.push(t)); + f.push('평범한 문장입니다'); + // ""(7자)의 접두사가 안 섞여 있으니 이 청크는 전부 즉시 나가야 한다(보류 없음). + assert.equal(seen.join(''), '평범한 문장입니다'); + }); + + test('상태 콜백이 think 진입/이탈 때 정확히 한 번씩 불린다("생각중" 표시용)', () => { + const statusLog: boolean[] = []; + const f = createThinkTagStreamFilter( + () => {}, + () => {}, + (active) => statusLog.push(active), + ); + f.push('앞 '); + f.push(''); + f.push('추론 중'); + f.push(''); + f.push(' 뒤'); + f.flush(); + assert.deepEqual(statusLog, [true, false]); + }); + + test('닫는 태그 없이 스트림이 끝나도 flush에서 상태가 false로 정리된다', () => { + const statusLog: boolean[] = []; + const f = createThinkTagStreamFilter( + () => {}, + () => {}, + (active) => statusLog.push(active), + ); + f.push('안 닫힌 추론'); + f.flush(); + assert.deepEqual(statusLog, [true, false]); + }); +}); diff --git a/web-ui/js/app/workshop-chat.js b/web-ui/js/app/workshop-chat.js index 92bdfda..9c04135 100644 --- a/web-ui/js/app/workshop-chat.js +++ b/web-ui/js/app/workshop-chat.js @@ -174,6 +174,18 @@ async function callChat(message){ bubble=document.createElement('div');bubble.className='rb-bubble'; msgDiv.appendChild(bubble);msgs.appendChild(msgDiv); const reader=r.body.getReader();const dec=new TextDecoder();let buf=''; + // glm-5.3-flash:cloud 등 일부 모델은 를 content에 평문으로 섞어 보내는데, 서버가 + // 그 구간을 실시간 억제하는 동안(stream-think-filter.ts) 화면엔 아무 것도 안 와서 멈춘 + // 것처럼 보인다 — 'thinking_status' 이벤트로 그 구간만 "생각중…"을 잠깐 보여준다. textBuf + // 자체엔 안 섞고(진짜 답변 텍스트만 유지) 렌더링할 때만 붙였다 뗀다. + let thinkingActive=false; + function renderBubble(){ + if(!bubble)return; + const suffix=thinkingActive?(textBuf?'\n\n':'')+'*(생각 중…)*':''; + bubble.innerHTML=renderMd(textBuf+suffix); + if(typeof renderKatexIn==='function')renderKatexIn(bubble); + msgs.scrollTop=msgs.scrollHeight; + } while(true){ const{done,value}=await reader.read();if(done)break; buf+=dec.decode(value,{stream:true}); @@ -184,7 +196,10 @@ async function callChat(message){ let ev;try{ev=JSON.parse(part.slice(6));}catch{continue;} if(ev.type==='token'||ev.type==='text_delta'){ textBuf+=(ev.text||''); - if(bubble){bubble.innerHTML=renderMd(textBuf);if(typeof renderKatexIn==='function')renderKatexIn(bubble);msgs.scrollTop=msgs.scrollHeight;} + renderBubble(); + }else if(ev.type==='thinking_status'){ + thinkingActive=!!ev.active; + renderBubble(); } } }