Spaces:
Sleeping
Sleeping
add: sse integration
Browse filesFiles changed (6)
29 unmodified lines30313233343512 unmodified lines4849505129 unmodified linesreturn $request;}protected function throwIfRagFailed(ClientResponse $response): void{if ($response->failed()) {12 unmodified linesreturn is_string($chatMode) && strtolower($chatMode) === 'direct';}}29 unmodified lines303132333435363738394041424312 unmodified lines565758596061626364656629 unmodified linesreturn $request;}protected function ragStreamRequest(?string $token = null): PendingRequest{return $this->ragRequest($token)->accept('text/event-stream')->timeout(120)->withOptions(['stream' => true]);}protected function throwIfRagFailed(ClientResponse $response): void{if ($response->failed()) {12 unmodified linesreturn is_string($chatMode) && strtolower($chatMode) === 'direct';}protected function isStreamChatMode(): bool{$chatMode = config('services.rag.chat_mode', 'rest');return is_string($chatMode) && strtolower($chatMode) === 'stream';}}
2 unmodified lines34567891011121371 unmodified lines8586878889903 unmodified lines9495969798991002 unmodified lines1031041051061071082 unmodified lines1111121131141151166 unmodified lines123124125126127128155 unmodified lines2842852862872882892 unmodified linesnamespace App\Http\Controllers;use App\Exceptions\RagApiException;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Support\Str;use Inertia\Inertia;use Inertia\Response;class MahasiswaController extends Controller{71 unmodified lines'backendMessage' => $backendMessage,'currentSession' => $currentSession,'isDirectChatMode' => $this->isDirectChatMode(),'messages' => $messages,'pendingInitialChat' => $request->session()->pull($this->pendingInitialChatKey($sessionId)),'selectedCourseId' => is_string($currentSession['course_id'] ?? null)3 unmodified lines]);}public function storeMessage(Request $request, string $sessionId): RedirectResponse{/** @var array{content: string, course_id: string} $payload */$payload = $request->validate([2 unmodified lines]);$userMessage = $this->localUserMessage($payload['content']);try {$assistantMessage = $this->sendConfiguredChatMessage($sessionId,2 unmodified lines$this->authToken($request),);} catch (RagApiException $exception) {return back()->withErrors(['message' => $exception->getMessage()])->withInput();6 unmodified lines]);}return to_route('mahasiswa.show', ['sessionId' => $sessionId]);}155 unmodified linesreturn $response->json();}/*** @return array{uuid_id: string, role: string, content: string, sources: array<int, mixed>, created_at: string}*/2 unmodified lines345678910111213141571 unmodified lines878889909192933 unmodified lines9798991001011021032 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331342 unmodified lines1371381391401411421431441451461471481491501516 unmodified lines158159160161162163164165166167168169155 unmodified lines3253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583592 unmodified linesnamespace App\Http\Controllers;use App\Exceptions\RagApiException;use Illuminate\Http\JsonResponse;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Support\Str;use Inertia\Inertia;use Inertia\Response;use Symfony\Component\HttpFoundation\StreamedResponse;class MahasiswaController extends Controller{71 unmodified lines'backendMessage' => $backendMessage,'currentSession' => $currentSession,'isDirectChatMode' => $this->isDirectChatMode(),'isStreamChatMode' => $this->isStreamChatMode(),'messages' => $messages,'pendingInitialChat' => $request->session()->pull($this->pendingInitialChatKey($sessionId)),'selectedCourseId' => is_string($currentSession['course_id'] ?? null)3 unmodified lines]);}public function storeMessage(Request $request, string $sessionId): JsonResponse|RedirectResponse|StreamedResponse{/** @var array{content: string, course_id: string} $payload */$payload = $request->validate([2 unmodified lines]);$userMessage = $this->localUserMessage($payload['content']);if ($this->isStreamChatMode()) {try {return $this->streamChatMessage($sessionId,$payload['content'],$this->authToken($request),);} catch (RagApiException $exception) {if ($request->expectsJson() || $request->accepts('text/event-stream')) {return response()->json(['errors' => ['message' => [$exception->getMessage()],],'message' => $exception->getMessage(),], 422);}return back()->withErrors(['message' => $exception->getMessage()])->withInput();}}try {$assistantMessage = $this->sendConfiguredChatMessage($sessionId,2 unmodified lines$this->authToken($request),);} catch (RagApiException $exception) {if ($request->expectsJson()) {return response()->json(['errors' => ['message' => [$exception->getMessage()],],'message' => $exception->getMessage(),], 422);}return back()->withErrors(['message' => $exception->getMessage()])->withInput();6 unmodified lines]);}if ($request->expectsJson()) {return response()->json(['assistantMessage' => $assistantMessage,]);}return to_route('mahasiswa.show', ['sessionId' => $sessionId]);}155 unmodified linesreturn $response->json();}private function streamChatMessage(string $sessionId, string $content, ?string $token = null): StreamedResponse{$response = $this->ragStreamRequest($token)->asJson()->post('/chats/sessions/'.$this->encodePathSegment($sessionId).'/stream', ['content' => $content,]);$this->throwIfRagFailed($response);$stream = $response->toPsrResponse()->getBody();return response()->stream(function () use ($stream): void {while (! $stream->eof()) {echo $stream->read(1024);if (ob_get_level() > 0) {ob_flush();}flush();}}, 200, ['Cache-Control' => 'no-cache, no-transform','Content-Type' => 'text/event-stream; charset=utf-8','X-Accel-Buffering' => 'no',]);}/*** @return array{uuid_id: string, role: string, content: string, sources: array<int, mixed>, created_at: string}*/
36 unmodified lines3738394041424336 unmodified lines'rag' => ['base_url' => env('RAG_API_BASE_URL'),'chat_mode' => env('RAG_CHAT_API_MODE', 'rest'),],];36 unmodified lines3738394041424336 unmodified lines'rag' => ['base_url' => env('RAG_API_BASE_URL'),'chat_mode' => env('RAG_CHAT_API_MODE', 'stream'),],];
47 unmodified lines48495047 unmodified linesuuid_id: createLocalMessageId('local'),};}47 unmodified lines48495051525354555657585960616247 unmodified linesuuid_id: createLocalMessageId('local'),};}export function createLocalAssistantMessage(content = '',): ChatMessageResponse {return {content,created_at: new Date().toISOString(),role: 'assistant',sources: [],uuid_id: createLocalMessageId('local-assistant'),};}
15 unmodified lines161718192021222 unmodified lines2526272829303132333435364 unmodified lines4142434445462 unmodified lines49505152535462 unmodified lines1171181191201211221234 unmodified lines12812913013113213313413513613725 unmodified lines1631641651661671681691701711721731742 unmodified lines1771781791801811826 unmodified lines18919019119219319462 unmodified lines2572582592602612621 unmodified line26426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931082 unmodified lines39339439539639739839915 unmodified linesChatSessionResponse,CourseResponse,} from '@/lib/rag';import { createLocalUserMessage } from '@/lib/rag';import { destroy as destroyMahasiswaSession } from '@/routes/mahasiswa';import { store as storeMahasiswaMessage } from '@/routes/mahasiswa/messages';2 unmodified linescourseId: string;};type MahasiswaChatProps = {backendMessage?: string | null;chatSessions: ChatSessionResponse[];courses: CourseResponse[];currentSession?: ChatSessionResponse | null;isDirectChatMode?: boolean;messages: ChatMessageResponse[];pendingInitialChat?: PendingInitialChat | null;selectedCourseId?: string | null;4 unmodified linesreturn ['human', 'student', 'user'].includes(role.toLowerCase());}function firstError(errors: Record<string, string | string[]>,): string | undefined {2 unmodified linesreturn Array.isArray(message) ? message[0] : message;}function formatMessageTime(value: string): string {const date = new Date(value);62 unmodified lines<div className="student-message-bubble"><p className="student-message-content">{!isUser && shouldAnimateTyping ? (<TypingText key={message.uuid_id} text={message.content} />) : (message.content)}4 unmodified lines{(message.sources?.length ?? 0) > 0 && (<div className="student-message-sources">{message.sources?.map((source) => (<spanclassName="student-message-source"key={`${message.uuid_id}-${source.document_id}`}>{source.filename}</span>25 unmodified lines];}export default function MahasiswaChat({backendMessage: initialBackendMessage,chatSessions,courses,currentSession,isDirectChatMode = false,messages: initialMessages,pendingInitialChat,selectedCourseId: initialSelectedCourseId,2 unmodified linesconst pendingInitialChatRef = useRef(pendingInitialChat ?? undefined);const isWaitingForDirectAssistantRef = useRef(false);const hasStartedPendingInitialChatRef = useRef(false);const knownMessageIdsRef = useRef(new Set(initialMessages.map((message) => message.uuid_id)),);6 unmodified linesconst [localBackendMessage, setLocalBackendMessage] = useState<string>();const [animatedAssistantMessageId, setAnimatedAssistantMessageId] =useState<string>();const [isProcessing, setIsProcessing] = useState(Boolean(pendingInitialChat),);62 unmodified linesreturn () => window.cancelAnimationFrame(scrollFrame);}, [messages, isProcessing]);const sendMessage = useCallback((content: string,1 unmodified lineoptimisticUserMessage?: ChatMessageResponse,): void => {setLocalBackendMessage(undefined);router.post(storeMahasiswaMessage.url(sessionId),{content,course_id: courseId,},{onError: (errors) => {isWaitingForDirectAssistantRef.current = false;if (optimisticUserMessage) {setOptimisticMessages((currentMessages) =>currentMessages.filter((message) =>message.uuid_id !==optimisticUserMessage.uuid_id,),);}pendingInitialChatRef.current = undefined;setQuestion(content);setLocalBackendMessage(firstError(errors));},onFinish: () => setIsProcessing(false),onStart: () => {isWaitingForDirectAssistantRef.current =isDirectChatMode;setIsProcessing(true);},onSuccess: () => {pendingInitialChatRef.current = undefined;setOptimisticMessages([]);setQuestion('');},preserveScroll: true,},);},[isDirectChatMode, sessionId],);useEffect(() => {82 unmodified lines/>))}{isProcessing && (<article className="student-message student-message--assistant"><span className="student-message-avatar student-message-avatar--assistant"><Bot className="size-4" />15 unmodified lines161718192021222 unmodified lines25262728293031323334353637383940414243444546474849505152534 unmodified lines585960616263646566672 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050162 unmodified lines5645655665675685695705715725734 unmodified lines57857958058158258358458558658725 unmodified lines6136146156166176186196206216226236246256266276282 unmodified lines6316326336346356366376386396406416426 unmodified lines64965065165265365465565662 unmodified lines7197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838841 unmodified line88688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098182 unmodified lines106410651066106710681069107015 unmodified linesChatSessionResponse,CourseResponse,} from '@/lib/rag';import { createLocalAssistantMessage, createLocalUserMessage } from '@/lib/rag';import { destroy as destroyMahasiswaSession } from '@/routes/mahasiswa';import { store as storeMahasiswaMessage } from '@/routes/mahasiswa/messages';2 unmodified linescourseId: string;};type StoreMessageJsonResponse = {assistantMessage?: ChatMessageResponse;};type StreamPayloadResult = {done: boolean;finalMessage?: ChatMessageResponse;};class BackendResponseError extends Error {constructor(message: string) {super(message);this.name = 'BackendResponseError';}}type MahasiswaChatProps = {backendMessage?: string | null;chatSessions: ChatSessionResponse[];courses: CourseResponse[];currentSession?: ChatSessionResponse | null;isDirectChatMode?: boolean;isStreamChatMode?: boolean;messages: ChatMessageResponse[];pendingInitialChat?: PendingInitialChat | null;selectedCourseId?: string | null;4 unmodified linesreturn ['human', 'student', 'user'].includes(role.toLowerCase());}function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);}function firstError(errors: Record<string, string | string[]>,): string | undefined {2 unmodified linesreturn Array.isArray(message) ? message[0] : message;}function firstPayloadError(value: unknown): string | undefined {if (typeof value === 'string') {return value;}if (Array.isArray(value)) {for (const item of value) {const message = firstPayloadError(item);if (message) {return message;}}return undefined;}if (!isRecord(value)) {return undefined;}for (const item of Object.values(value)) {const message = firstPayloadError(item);if (message) {return message;}}return undefined;}function backendMessageFromPayload(payload: unknown): string | undefined {if (!isRecord(payload)) {return undefined;}if (typeof payload.message === 'string') {return payload.message;}if (typeof payload.error === 'string') {return payload.error;}if (typeof payload.detail === 'string') {return payload.detail;}return (firstPayloadError(payload.errors) ?? firstPayloadError(payload.detail));}function csrfToken(): string | undefined {return (document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.getAttribute('content') ?? undefined);}async function storeChatMessage(sessionId: string,content: string,courseId: string,): Promise<StoreMessageJsonResponse> {const token = csrfToken();const response = await fetch(storeMahasiswaMessage.url(sessionId), {body: JSON.stringify({content,course_id: courseId,}),credentials: 'same-origin',headers: {Accept: 'application/json','Content-Type': 'application/json','X-Requested-With': 'XMLHttpRequest',...(token ? { 'X-CSRF-TOKEN': token } : {}),},method: 'POST',});const payload: unknown = await response.json().catch(() => undefined);if (!response.ok) {throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);}if (!isRecord(payload)) {return {};}return {assistantMessage: isRecord(payload.assistantMessage)? (payload.assistantMessage as ChatMessageResponse): undefined,};}function isChatMessageResponse(value: unknown): value is ChatMessageResponse {return (isRecord(value) &&typeof value.uuid_id === 'string' &&typeof value.role === 'string' &&typeof value.content === 'string' &&typeof value.created_at === 'string');}function parseStreamPayload(value: string): unknown {try {return JSON.parse(value);} catch {return value;}}function streamStatusFromPayload(payload: unknown): string | undefined {if (!isRecord(payload)) {return undefined;}for (const key of ['event', 'type', 'status']) {const value = payload[key];if (typeof value === 'string') {return value.toLowerCase();}}return undefined;}function isDoneStatus(value: string | undefined): boolean {return ['complete','completed','done','end','finish','finished','success',].includes(value ?? '');}function isStreamDone(value: string,eventName: string | undefined,payload: unknown,): boolean {const trimmedValue = value.trim();const normalizedEventName = eventName?.toLowerCase();if (trimmedValue === '' ||trimmedValue === '[DONE]' ||trimmedValue === '</stream>' ||isDoneStatus(normalizedEventName) ||isDoneStatus(streamStatusFromPayload(payload))) {return true;}return (isRecord(payload) &&(payload.complete === true ||payload.completed === true ||payload.done === true ||payload.finished === true ||payload.status === 'done'));}function streamTextFromPayload(payload: unknown): string | undefined {if (typeof payload === 'string') {return payload;}if (!isRecord(payload)) {return undefined;}for (const key of ['answer','chunk','content','delta','output','response','text','token',]) {const value = payload[key];if (typeof value === 'string') {return value;}}const choices = payload.choices;if (Array.isArray(choices)) {for (const choice of choices) {const message = streamTextFromPayload(choice);if (message) {return message;}}}for (const key of ['data', 'delta', 'message', 'result']) {const message = streamTextFromPayload(payload[key]);if (message) {return message;}}return undefined;}function finalMessageFromPayload(payload: unknown,): ChatMessageResponse | undefined {if (isChatMessageResponse(payload)) {return payload;}if (!isRecord(payload)) {return undefined;}for (const key of ['assistantMessage', 'data', 'message', 'result']) {const message = finalMessageFromPayload(payload[key]);if (message) {return message;}}return undefined;}function parseSseFrame(frame: string): { data: string; eventName?: string } {const dataLines: string[] = [];let eventName: string | undefined;for (const line of frame.split('\n')) {if (line.startsWith('event:')) {eventName = line.slice('event:'.length).trim();continue;}if (line.startsWith('data:')) {dataLines.push(line.slice('data:'.length).trimStart());}}return {data: dataLines.length > 0 ? dataLines.join('\n') : frame.trim(),eventName,};}function handleStreamPayload(data: string,eventName: string | undefined,onDelta: (delta: string) => void,): StreamPayloadResult {const payload = parseStreamPayload(data);const finalMessage = finalMessageFromPayload(payload);if (isStreamDone(data, eventName, payload)) {return { done: true, finalMessage };}if (eventName === 'error') {throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);}if (isRecord(payload) && ('error' in payload || 'errors' in payload)) {throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);}if (finalMessage) {return {done: false,finalMessage,};}const delta = streamTextFromPayload(payload);if (delta) {onDelta(delta);}return { done: false };}async function streamChatMessage(sessionId: string,content: string,courseId: string,onDelta: (delta: string) => void,): Promise<StoreMessageJsonResponse> {const token = csrfToken();const response = await fetch(storeMahasiswaMessage.url(sessionId), {body: JSON.stringify({content,course_id: courseId,}),credentials: 'same-origin',headers: {Accept: 'text/event-stream','Content-Type': 'application/json','X-Requested-With': 'XMLHttpRequest',...(token ? { 'X-CSRF-TOKEN': token } : {}),},method: 'POST',});if (!response.ok) {const payload: unknown = await response.json().catch(() => undefined);throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);}if (!response.body) {return {};}const reader = response.body.getReader();const decoder = new TextDecoder();let buffer = '';let finalMessage: ChatMessageResponse | undefined;let shouldStop = false;const processFrame = (frame: string): void => {const { data, eventName } = parseSseFrame(frame);if (!data) {return;}const result = handleStreamPayload(data, eventName, onDelta);finalMessage = result.finalMessage ?? finalMessage;shouldStop = shouldStop || result.done;};const processRawData = (data: string): void => {const result = handleStreamPayload(data, undefined, onDelta);finalMessage = result.finalMessage ?? finalMessage;shouldStop = shouldStop || result.done;};while (true) {if (shouldStop) {await reader.cancel();break;}const { done, value } = await reader.read();if (done) {break;}const chunk = decoder.decode(value, { stream: true });if (buffer !== '' ||chunk.includes('data:') ||chunk.includes('event:')) {buffer += chunk.replace(/\r\n/g, '\n');let boundaryIndex = buffer.indexOf('\n\n');while (boundaryIndex !== -1) {const frame = buffer.slice(0, boundaryIndex);buffer = buffer.slice(boundaryIndex + 2);processFrame(frame);if (shouldStop) {await reader.cancel();break;}boundaryIndex = buffer.indexOf('\n\n');}if (shouldStop) {break;}continue;}processRawData(chunk);}const remaining = `${buffer}${decoder.decode()}`.trim();if (remaining) {if (remaining.includes('data:') || remaining.includes('event:')) {processFrame(remaining);} else {processRawData(remaining);}}return {assistantMessage: finalMessage,};}function formatMessageTime(value: string): string {const date = new Date(value);62 unmodified lines<div className="student-message-bubble"><p className="student-message-content">{!isUser && shouldAnimateTyping ? (<TypingTextkey={message.uuid_id}text={message.content}/>) : (message.content)}4 unmodified lines{(message.sources?.length ?? 0) > 0 && (<div className="student-message-sources">{message.sources?.map((source, index) => (<spanclassName="student-message-source"key={`${message.uuid_id}-${source.document_id}-${index}`}>{source.filename}</span>25 unmodified lines];}const STREAM_TYPING_CHARS_PER_TICK = 2;const STREAM_TYPING_INTERVAL_MS = 14;export default function MahasiswaChat({backendMessage: initialBackendMessage,chatSessions,courses,currentSession,isDirectChatMode = false,isStreamChatMode = false,messages: initialMessages,pendingInitialChat,selectedCourseId: initialSelectedCourseId,2 unmodified linesconst pendingInitialChatRef = useRef(pendingInitialChat ?? undefined);const isWaitingForDirectAssistantRef = useRef(false);const hasStartedPendingInitialChatRef = useRef(false);const streamingAssistantMessageRef = useRef<ChatMessageResponse | undefined>(undefined);const streamingTextQueueRef = useRef('');const streamingTypingTimerRef = useRef<number | undefined>(undefined);const streamingTypingWaitersRef = useRef<Array<() => void>>([]);const knownMessageIdsRef = useRef(new Set(initialMessages.map((message) => message.uuid_id)),);6 unmodified linesconst [localBackendMessage, setLocalBackendMessage] = useState<string>();const [animatedAssistantMessageId, setAnimatedAssistantMessageId] =useState<string>();const [streamingAssistantMessageId, setStreamingAssistantMessageId] =useState<string>();const [isProcessing, setIsProcessing] = useState(Boolean(pendingInitialChat),);62 unmodified linesreturn () => window.cancelAnimationFrame(scrollFrame);}, [messages, isProcessing]);const resolveStreamingTypingWaiters = useCallback((): void => {const waiters = streamingTypingWaitersRef.current;streamingTypingWaitersRef.current = [];for (const resolve of waiters) {resolve();}}, []);const setStreamingAssistantContent = useCallback((content: string): void => {const currentStreamingMessage =streamingAssistantMessageRef.current ??createLocalAssistantMessage();const nextStreamingMessage = {...currentStreamingMessage,content,};streamingAssistantMessageRef.current = nextStreamingMessage;setStreamingAssistantMessageId(nextStreamingMessage.uuid_id);setOptimisticMessages((currentMessages) => {if (currentMessages.some((message) =>message.uuid_id === nextStreamingMessage.uuid_id,)) {return currentMessages.map((message) =>message.uuid_id === nextStreamingMessage.uuid_id? nextStreamingMessage: message,);}return [...currentMessages, nextStreamingMessage];});},[],);const stopStreamingTypingTimer = useCallback((): void => {if (streamingTypingTimerRef.current === undefined) {return;}window.clearInterval(streamingTypingTimerRef.current);streamingTypingTimerRef.current = undefined;}, []);const revealQueuedStreamingText = useCallback((): void => {if (streamingTextQueueRef.current === '') {stopStreamingTypingTimer();resolveStreamingTypingWaiters();return;}const visibleChunk = streamingTextQueueRef.current.slice(0,STREAM_TYPING_CHARS_PER_TICK,);streamingTextQueueRef.current = streamingTextQueueRef.current.slice(STREAM_TYPING_CHARS_PER_TICK,);const currentStreamingMessage =streamingAssistantMessageRef.current?.content ?? '';setStreamingAssistantContent(`${currentStreamingMessage}${visibleChunk}`);if (streamingTextQueueRef.current === '') {stopStreamingTypingTimer();resolveStreamingTypingWaiters();}}, [resolveStreamingTypingWaiters,setStreamingAssistantContent,stopStreamingTypingTimer,]);const startStreamingTypingTimer = useCallback((): void => {if (streamingTypingTimerRef.current !== undefined) {return;}revealQueuedStreamingText();streamingTypingTimerRef.current = window.setInterval(revealQueuedStreamingText,STREAM_TYPING_INTERVAL_MS,);}, [revealQueuedStreamingText]);const appendStreamingAssistantDelta = useCallback((delta: string): void => {if (delta === '') {return;}streamingTextQueueRef.current += delta;startStreamingTypingTimer();},[startStreamingTypingTimer],);const waitForStreamingTyping = useCallback((): Promise<void> => {if (streamingTextQueueRef.current === '' &&streamingTypingTimerRef.current === undefined) {return Promise.resolve();}return new Promise((resolve) => {streamingTypingWaitersRef.current.push(resolve);});}, []);const clearStreamingTyping = useCallback((): void => {streamingTextQueueRef.current = '';stopStreamingTypingTimer();resolveStreamingTypingWaiters();}, [resolveStreamingTypingWaiters, stopStreamingTypingTimer]);const replaceStreamingAssistantMessage = useCallback((assistantMessage: ChatMessageResponse): void => {const streamingMessageId =streamingAssistantMessageRef.current?.uuid_id;streamingAssistantMessageRef.current = undefined;setStreamingAssistantMessageId(undefined);setOptimisticMessages((currentMessages) => {if (streamingMessageId) {return currentMessages.map((message) =>message.uuid_id === streamingMessageId? assistantMessage: message,);}return appendUniqueMessages(currentMessages, [assistantMessage,]);});},[],);useEffect(() => clearStreamingTyping, [clearStreamingTyping]);const reloadChatHistory = useCallback((): void => {router.reload({onSuccess: () => {streamingAssistantMessageRef.current = undefined;setStreamingAssistantMessageId(undefined);setOptimisticMessages([]);},only: ['messages', 'chatSessions', 'currentSession'],});}, []);const sendMessage = useCallback((content: string,1 unmodified lineoptimisticUserMessage?: ChatMessageResponse,): void => {setLocalBackendMessage(undefined);isWaitingForDirectAssistantRef.current = isDirectChatMode;setIsProcessing(true);void (async () => {try {const response = isStreamChatMode? await streamChatMessage(sessionId,content,courseId,appendStreamingAssistantDelta,): await storeChatMessage(sessionId, content, courseId);pendingInitialChatRef.current = undefined;if (isStreamChatMode) {await waitForStreamingTyping();}if (response.assistantMessage) {const assistantMessage = response.assistantMessage;if (isStreamChatMode) {replaceStreamingAssistantMessage(assistantMessage);} else {setOptimisticMessages((currentMessages) =>appendUniqueMessages(currentMessages, [assistantMessage,]),);}}if (isStreamChatMode) {reloadChatHistory();}setQuestion('');} catch (error) {isWaitingForDirectAssistantRef.current = false;const streamingMessageId =streamingAssistantMessageRef.current?.uuid_id;clearStreamingTyping();streamingAssistantMessageRef.current = undefined;setStreamingAssistantMessageId(undefined);if (optimisticUserMessage) {setOptimisticMessages((currentMessages) =>currentMessages.filter((message) =>message.uuid_id !==optimisticUserMessage.uuid_id &&message.uuid_id !== streamingMessageId,),);} else if (streamingMessageId) {setOptimisticMessages((currentMessages) =>currentMessages.filter((message) =>message.uuid_id !== streamingMessageId,),);}pendingInitialChatRef.current = undefined;setQuestion(content);setLocalBackendMessage(error instanceof Error && error.message? error.message: undefined,);} finally {clearStreamingTyping();streamingAssistantMessageRef.current = undefined;setStreamingAssistantMessageId(undefined);setIsProcessing(false);}})();},[appendStreamingAssistantDelta,clearStreamingTyping,isDirectChatMode,isStreamChatMode,reloadChatHistory,replaceStreamingAssistantMessage,sessionId,waitForStreamingTyping,],);useEffect(() => {82 unmodified lines/>))}{isProcessing && !streamingAssistantMessageId && (<article className="student-message student-message--assistant"><span className="student-message-avatar student-message-avatar--assistant"><Bot className="size-4" />
2 unmodified lines3456782 unmodified lines<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">{{-- Inline script to detect system dark mode preference and apply it immediately --}}<script>2 unmodified lines34567892 unmodified lines<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="csrf-token" content="{{ csrf_token() }}">{{-- Inline script to detect system dark mode preference and apply it immediately --}}<script>
app/Http/Controllers/Controller.php+15
app/Http/Controllers/MahasiswaController.php+71-1
config/services.php+1-1
resources/js/lib/rag.ts+12
resources/js/pages/mahasiswa-chat.tsx+710-39
resources/views/app.blade.php+1