From 8851e23840dd9abcd5ea52b818563490d34315ee Mon Sep 17 00:00:00 2001 From: overhyeon Date: Wed, 18 Nov 2026 01:12:58 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=B1=97=EB=B4=87=20=EB=8B=B5=EB=B3=80?= =?UTF-8?q?=EC=9D=84=20=EB=B0=9B=EC=9D=80=20=EB=8C=80=EB=A1=9C=20=EB=B6=99?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=20=EC=95=8A=EA=B3=A0=20=EC=9D=BC=EC=A0=95?= =?UTF-8?q?=ED=95=9C=20=EC=86=8D=EB=8F=84=EB=A1=9C=20=ED=92=80=EC=96=B4?= =?UTF-8?q?=EC=84=9C=20=EB=B3=B4=EC=97=AC=EC=A3=BC=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/features/chat/hooks/useChatStream.ts | 63 ++++++---- src/features/chat/utils/typingQueue.ts | 147 +++++++++++++++++++++++ 2 files changed, 186 insertions(+), 24 deletions(-) create mode 100644 src/features/chat/utils/typingQueue.ts diff --git a/src/features/chat/hooks/useChatStream.ts b/src/features/chat/hooks/useChatStream.ts index f8f80763..01c8cfe3 100644 --- a/src/features/chat/hooks/useChatStream.ts +++ b/src/features/chat/hooks/useChatStream.ts @@ -1,5 +1,9 @@ import { useEffect, useRef, useState } from "react"; +import { + createTypingQueue, + type TypingQueue, +} from "@/features/chat/utils/typingQueue"; import { streamChatMessage } from "@/shared/entities/chat/chatStream"; interface ChatUserMessage { @@ -32,11 +36,14 @@ export function useChatStream({ onFailure }: UseChatStreamOptions) { const [isAnswering, setIsAnswering] = useState(false); const nextMessageIdRef = useRef(0); const abortControllerRef = useRef(null); + const typingQueueRef = useRef(null); - // 답변 중에 화면을 떠나면(종료하기·뒤로가기) 연결을 끊는다 — 서버도 학생이 끊으면 중계를 멈춘다 + // 답변 중에 화면을 떠나면(종료하기·뒤로가기) 연결을 끊는다 — 서버도 학생이 끊으면 중계를 멈춘다. + // 아직 화면에 붙이지 못한 글자도 버린다(그릴 화면이 없다) useEffect(() => { return () => { abortControllerRef.current?.abort(); + typingQueueRef.current?.cancel(); }; }, []); @@ -62,6 +69,33 @@ export function useChatStream({ onFailure }: UseChatStreamOptions) { ]); setIsAnswering(true); + // 받은 조각은 대기열에 쌓고, 대기열이 일정한 속도로 꺼내 줄 때 말풍선에 붙인다(utils/typingQueue) + const typingQueue = createTypingQueue((text, opensBubble) => { + if (botMessageId === null) { + const id = nextMessageId(); + botMessageId = id; + setMessages((prev) => [ + ...prev, + { bubbles: [text], id, sender: "bot" }, + ]); + return; + } + const id = botMessageId; + setMessages((prev) => + prev.map((message) => + message.id === id && message.sender === "bot" + ? { + ...message, + bubbles: opensBubble + ? [...message.bubbles, text] + : appendToLastBubble(message.bubbles, text), + } + : message, + ), + ); + }); + typingQueueRef.current = typingQueue; + try { await streamChatMessage( { conversationId, message: question }, @@ -70,35 +104,16 @@ export function useChatStream({ onFailure }: UseChatStreamOptions) { isNewBubblePending = true; }, onDelta: (text) => { - if (botMessageId === null) { - const id = nextMessageId(); - botMessageId = id; - setMessages((prev) => [ - ...prev, - { bubbles: [text], id, sender: "bot" }, - ]); - return; - } - const id = botMessageId; - const opensBubble = isNewBubblePending; + typingQueue.push(text, isNewBubblePending); isNewBubblePending = false; - setMessages((prev) => - prev.map((message) => - message.id === id && message.sender === "bot" - ? { - ...message, - bubbles: opensBubble - ? [...message.bubbles, text] - : appendToLastBubble(message.bubbles, text), - } - : message, - ), - ); }, }, controller.signal, ); + // 다 받았어도 화면에는 아직 글자가 남아 있다 — 다 보여준 뒤에 입력창을 연다 + await typingQueue.finish(); } catch (error) { + typingQueue.cancel(); // 화면을 떠나 끊은 요청 — 그릴 화면이 없다 if (controller.signal.aborted) { return; diff --git a/src/features/chat/utils/typingQueue.ts b/src/features/chat/utils/typingQueue.ts new file mode 100644 index 00000000..f22c1a86 --- /dev/null +++ b/src/features/chat/utils/typingQueue.ts @@ -0,0 +1,147 @@ +// 받은 답변 조각을 바로 붙이지 않고 쌓아 두었다가 일정한 속도로 조금씩 꺼내 주는 대기열. +// AI 게이트웨이가 답변을 40자 안팎씩 0.2초마다 몰아서 보내서, 받는 대로 붙이면 몇 줄씩 뚝뚝 끊겨 보인다. +// 그래서 TICK_MS마다 몇 글자씩만 꺼내 말풍선에 붙인다 — 화면에서는 글자가 흘러가듯 나온다. + +// 몇 ms마다 꺼낼지. 화면 갱신(약 16ms)보다 길게 잡아 렌더링이 밀리지 않게 한다 +const TICK_MS = 30; +// 한 번에 꺼낼 최소 글자 수. 30ms에 2글자 ≈ 초당 66글자로, 눈으로 따라 읽을 만한 속도다 +const MIN_CHARS_PER_TICK = 2; +// 밀린 글자를 몇 번 안에 따라잡을지. 20번 × 30ms ≈ 0.6초 — 답변이 한꺼번에 많이 와도 +// 받은 것보다 1초 넘게 늦게 보이지 않도록, 밀린 만큼 한 번에 꺼내는 양을 늘린다 +const CATCH_UP_TICKS = 20; + +interface PendingBubble { + // 아직 화면에 붙이지 않은 글자. 이모지가 반으로 잘리지 않게 글자(코드 포인트) 단위로 나눠 둔다 + chars: string[]; + // 이 글자들이 새 말풍선에서 시작하는지 — 첫 글자를 꺼낼 때 한 번만 참이다 + opensBubble: boolean; +} + +export interface TypingQueue { + // 받은 조각을 쌓는다. opensBubble이면 앞 말풍선과 섞이지 않게 새 칸으로 쌓는다 + push: (text: string, opensBubble: boolean) => void; + // 스트림이 끝났다 — 남은 글자를 마저 꺼내고, 다 꺼내면 끝나는 Promise를 돌려준다 + finish: () => Promise; + // 실패·화면 떠남 — 남은 글자를 버리고 멈춘다 + cancel: () => void; +} + +export function createTypingQueue( + reveal: (text: string, opensBubble: boolean) => void, +): TypingQueue { + const pending: PendingBubble[] = []; + let timer: ReturnType | null = null; + let isStreamDone = false; + let resolveFinish: (() => void) | null = null; + + function pendingCount() { + return pending.reduce((sum, bubble) => sum + bubble.chars.length, 0); + } + + function stop() { + if (timer !== null) { + clearInterval(timer); + timer = null; + } + } + + function tick() { + const bubble = pending[0]; + if (!bubble) { + stop(); + if (isStreamDone) { + resolveFinish?.(); + } + return; + } + const count = Math.max( + MIN_CHARS_PER_TICK, + Math.ceil(pendingCount() / CATCH_UP_TICKS), + ); + const size = takeSize( + bubble.chars, + count, + isStreamDone || pending.length > 1, + ); + if (size === 0) { + // 굵게·링크 표시가 닫히는 글자를 아직 못 받았다 — 다음 조각을 기다린다 + return; + } + const text = bubble.chars.splice(0, size).join(""); + reveal(text, bubble.opensBubble); + bubble.opensBubble = false; + if (bubble.chars.length === 0) { + pending.shift(); + } + } + + function start() { + if (timer === null) { + timer = setInterval(tick, TICK_MS); + } + } + + return { + cancel() { + pending.length = 0; + stop(); + resolveFinish?.(); + }, + finish() { + isStreamDone = true; + return new Promise((resolve) => { + resolveFinish = resolve; + start(); + }); + }, + push(text, opensBubble) { + const chars = Array.from(text); + const last = pending.at(-1); + if (last && !opensBubble) { + last.chars.push(...chars); + } else { + pending.push({ chars, opensBubble }); + } + start(); + }, + }; +} + +// 이번에 꺼낼 글자 수. 굵게(`**…**`)와 링크(`[제목](주소)`)는 한 번에 꺼낸다 — 한 글자씩 꺼내면 +// 닫는 표시가 오기 전까지 `**`나 `[`가 글자 그대로 보였다가 갑자기 굵어지거나 링크로 바뀌어 번쩍인다. +// 닫는 표시를 아직 못 받았으면 0을 돌려 기다린다. 더 받을 글자가 없으면(isComplete) 있는 그대로 꺼낸다. +function takeSize(chars: string[], count: number, isComplete: boolean): number { + let size = 0; + while (size < count && size < chars.length) { + const rest = chars.slice(size).join(""); + const tokenLength = markdownTokenLength(rest); + if (tokenLength === null) { + size += 1; + continue; + } + if (tokenLength === 0) { + // 닫는 표시가 아직 안 왔다. 앞에 꺼낼 글자가 있으면 거기까지만 꺼낸다 + return size > 0 || !isComplete ? size : chars.length; + } + size += Array.from(rest.slice(0, tokenLength)).length; + } + return size; +} + +// text가 굵게·링크 표시로 시작하면 그 표시 전체의 길이(UTF-16 기준), 닫히지 않았으면 0, 표시가 아니면 null +function markdownTokenLength(text: string): number | null { + if (text.startsWith("**")) { + const close = text.indexOf("**", 2); + return close === -1 ? 0 : close + 2; + } + if (text.startsWith("[")) { + const link = text.match(/^\[[^\]\n]*\]\([^)\n]*\)/); + if (link) { + return link[0].length; + } + // 아직 링크가 되다 만 모양이면(`[제목`, `[제목]`, `[제목](/no`) 뒤 글자를 기다린다. + // `[취소] 영화 상영회`처럼 링크가 아닌 대괄호는 그냥 글자다 + return /^\[[^\]\n]*(\](\([^)\n]*)?)?$/.test(text) ? 0 : null; + } + return null; +}