Spaces:
Sleeping
Sleeping
AKKHIRNYA BISA STREAM
Browse filesFiles changed (6)
29 unmodified lines30313233333435363729 unmodified lines
AGENTS.md.agents.codex.codexCLAUDE.md.claude.mcp.jsonboost.json16 unmodified lines171819202120212212 unmodified lines35363738394041414243442 unmodified lines47484950515253505152535455565758596061626364656667686932 unmodified lines1021031049210510610710 unmodified lines118119120109121122123124125126127224 unmodified lines35235335435535635734235835936036136236336436536636736836996 unmodified lines46646746844544644744846916 unmodified lines
private const DIRECT_MESSAGES_SESSION_PREFIX = 'sevima_raghub_direct_messages';
private const PENDING_INITIAL_CHAT_SESSION_PREFIX = 'sevima_raghub_pending_initial_chat';
public function index(Request $request): Response { $payload = $this->studentDashboardPayload($request);12 unmodified lines 'title' => ['required', 'string'], ]);
$token = $this->authToken($request);
try { $session = $this->createChatSession($payload, $this->authToken($request)); $session = $this->createChatSession($payload, $token); } catch (RagApiException $exception) { return back() ->withErrors(['chat' => $exception->getMessage()])2 unmodified lines
$sessionId = (string) ($session['uuid_id'] ?? '');
$request->session()->flash($this->pendingInitialChatKey($sessionId), [ 'content' => $payload['title'], 'courseId' => $payload['course_id'], ]); try { $assistantMessage = $this->sendConfiguredChatMessage( $sessionId, $payload['course_id'], $payload['title'], $token, );
if ($this->isDirectChatMode()) { $this->appendDirectChatMessages($request, $sessionId, [ $this->localUserMessage($payload['title']), $assistantMessage, ]); } } catch (RagApiException) { // Session created; initial message failed — user can retry from the session page. }
return to_route('mahasiswa.show', ['sessionId' => $sessionId]); }32 unmodified lines 'isDirectChatMode' => $this->isDirectChatMode(), 'isStreamChatMode' => $this->isStreamChatMode(), 'messages' => $messages, 'pendingInitialChat' => $request->session()->pull($this->pendingInitialChatKey($sessionId)), 'selectedCourseId' => is_string($currentSession['course_id'] ?? null) ? $currentSession['course_id'] : $this->firstCourseId($payload['courses']),10 unmodified lines ]); $userMessage = $this->localUserMessage($payload['content']);
if ($this->isStreamChatMode()) { if ($this->isStreamChatMode() && $request->accepts('text/event-stream')) { try { $request->session()->save();
return $this->streamChatMessage( $sessionId, $payload['content'],224 unmodified lines $stream = $response->toPsrResponse()->getBody();
return response()->stream(function () use ($stream): void { @ini_set('zlib.output_compression', '0');
while (! $stream->eof()) { echo $stream->read(1024); $chunk = $stream->read(1);
if ($chunk === '') { usleep(10_000);
continue; }
echo $chunk;
if (ob_get_level() > 0) { ob_flush();96 unmodified lines return self::DIRECT_MESSAGES_SESSION_PREFIX.'.'.$sessionId; }
private function pendingInitialChatKey(string $sessionId): string { return self::PENDING_INITIAL_CHAT_SESSION_PREFIX.'.'.$sessionId; }}1233456{ "agents": [ "codex" "claude_code" ], "cloud": false, "guidelines": true,123454 unmodified lines10111213121415161718192021import { Moon, Sun } from 'lucide-react';import { useEffect, useState } from 'react';import { Button } from '@/components/ui/button';import { useAppearance } from '@/hooks/use-appearance';import { cn } from '@/lib/utils';4 unmodified lines
export default function AppearanceToggle({ className }: AppearanceToggleProps) { const { resolvedAppearance, updateAppearance } = useAppearance(); const [isMounted, setIsMounted] = useState(false); const isDarkMode = resolvedAppearance === 'dark'; const isDarkMode = isMounted && resolvedAppearance === 'dark';
useEffect(() => { setIsMounted(true); }, []);
const handleToggle = (): void => { updateAppearance(isDarkMode ? 'light' : 'dark');19 unmodified lines202122232425262723242518 unmodified lines4445465247484976 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416573 unmodified lines23924024124224324424524624724824925099 unmodified lines3503513523533543553563573583593603613623631 unmodified line3653663673683693703713723733743353753763773783793803813823833843853863873883893903912 unmodified lines3943953963973983993494004014024034044054064074084093524104114124136 unmodified lines4204214224234244253663674264274284294304314324334344354364374384397 unmodified lines4474484494504514524534544554564574584594609 unmodified lines4704714724734744754764774784794804814824834844854864874884894904914924934944956 unmodified lines5025035045055065075085094 unmodified lines5145155165175185195205211 unmodified line5235245255265275285291 unmodified line5315325335345355365375385394524534544554564574584595405414614624634645425434664674684695445454714725465475485495505515525535545555564785575585594815605615625635644845655665675685695703 unmodified lines57457557657757857958058166 unmodified lines64864965065165265365465556665665765865954 unmodified lines7147157166277177187196317206337217227233 unmodified lines727728729643644645646647648730731732733734654655656735736737659738739740662663664665741742743744199 unmodified lines9449459468718728738748758768778788798808819479489496 unmodified lines9569579588949599609619629639649659669679682 unmodified lines9719729739039049059749759769779789799809129819829839849859869879889892 unmodified lines992993994923924925926995996997998999100019 unmodified lines1020102110229541023102410251 unmodified line10271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310542 unmodified lines1057105810599741060106110621063106410651066981982983984985986987988989990991992993994995996997998999100010671068106919 unmodified linesimport { destroy as destroyMahasiswaSession } from '@/routes/mahasiswa';import { store as storeMahasiswaMessage } from '@/routes/mahasiswa/messages';
type PendingInitialChat = { content: string; courseId: string;};
type StoreMessageJsonResponse = { assistantMessage?: ChatMessageResponse;};18 unmodified lines isDirectChatMode?: boolean; isStreamChatMode?: boolean; messages: ChatMessageResponse[]; pendingInitialChat?: PendingInitialChat | null; selectedCourseId?: string | null; sessionId: string;};76 unmodified lines );}
function isStreamDebugEnabled(): boolean { if (import.meta.env.DEV) { return true; }
if (typeof window === 'undefined') { return false; }
if (new URLSearchParams(window.location.search).has('debug_stream')) { return true; }
try { return window.localStorage.getItem('rag_stream_debug') === '1'; } catch { return false; }}
function debugStream(label: string, value?: unknown): void { if (!isStreamDebugEnabled()) { return; }
if (value === undefined) { console.log(`[rag-stream] ${label}`);
return; }
console.log(`[rag-stream] ${label}`, value);}
async function storeChatMessage( sessionId: string, content: string,73 unmodified lines 'completed', 'done', 'end', 'final', 'finalized', 'finish', 'finished', 'message_done', 'stop', 'success', ].includes(value ?? '');}99 unmodified lines
function parseSseFrame(frame: string): { data: string; eventName?: string } { const dataLines: string[] = []; const fallbackLines: string[] = []; let eventName: string | undefined;
for (const line of frame.split('\n')) { if (line.startsWith(':')) { continue; }
if (line.startsWith('event:')) { eventName = line.slice('event:'.length).trim(); continue;1 unmodified line
if (line.startsWith('data:')) { dataLines.push(line.slice('data:'.length).trimStart()); continue; }
fallbackLines.push(line); }
return { data: dataLines.length > 0 ? dataLines.join('\n') : frame.trim(), data: dataLines.length > 0 ? dataLines.join('\n') : fallbackLines.join('\n').trim(), eventName, };}
function isAssistantMessage( message: ChatMessageResponse | undefined,): message is ChatMessageResponse { return Boolean(message && !isUserMessage(message.role));}
function handleStreamPayload( data: string, eventName: string | undefined,2 unmodified lines const payload = parseStreamPayload(data); const finalMessage = finalMessageFromPayload(payload);
debugStream('payload', { data, eventName, payload });
if (isStreamDone(data, eventName, payload)) { return { done: true, finalMessage }; debugStream('done-status', { data, eventName, payload });
return { done: true, finalMessage: isAssistantMessage(finalMessage) ? finalMessage : undefined, }; }
if (eventName === 'error') { if (eventName?.toLowerCase() === 'error') { throw new BackendResponseError( backendMessageFromPayload(payload) ?? '', );6 unmodified lines }
if (finalMessage) { debugStream('final-message', finalMessage);
return { done: false, finalMessage, done: isAssistantMessage(finalMessage), finalMessage: isAssistantMessage(finalMessage) ? finalMessage : undefined, }; }
const delta = streamTextFromPayload(payload);
if (delta) { debugStream('delta', delta); onDelta(delta); }
7 unmodified lines onDelta: (delta: string) => void,): Promise<StoreMessageJsonResponse> { const token = csrfToken();
debugStream('request:start', { content, courseId, sessionId, url: storeMahasiswaMessage.url(sessionId), });
const response = await fetch(storeMahasiswaMessage.url(sessionId), { body: JSON.stringify({ content,9 unmodified lines method: 'POST', });
debugStream('response', { contentType: response.headers.get('content-type'), ok: response.ok, status: response.status, statusText: response.statusText, });
if (!response.ok) { const payload: unknown = await response.json().catch(() => undefined);
debugStream('response:error-payload', payload);
throw new BackendResponseError( backendMessageFromPayload(payload) ?? '', ); }
if (!response.body) { debugStream('response:no-body');
return {}; }
6 unmodified lines const processFrame = (frame: string): void => { const { data, eventName } = parseSseFrame(frame);
debugStream('frame', { data, eventName, frame });
if (!data) { return; }4 unmodified lines };
const processRawData = (data: string): void => { debugStream('raw-data', data);
const result = handleStreamPayload(data, undefined, onDelta); finalMessage = result.finalMessage ?? finalMessage; shouldStop = shouldStop || result.done;1 unmodified line
while (true) { if (shouldStop) { debugStream('reader:cancel-before-read'); await reader.cancel(); break; }1 unmodified line const { done, value } = await reader.read();
if (done) { debugStream('reader: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'); debugStream('chunk', chunk);
while (boundaryIndex !== -1) { const frame = buffer.slice(0, boundaryIndex); buffer = buffer.slice(boundaryIndex + 2); processFrame(frame); buffer += chunk.replace(/\r\n/g, '\n');
if (shouldStop) { await reader.cancel(); break; } let boundaryIndex = buffer.indexOf('\n\n');
boundaryIndex = buffer.indexOf('\n\n'); } while (boundaryIndex !== -1) { const frame = buffer.slice(0, boundaryIndex); buffer = buffer.slice(boundaryIndex + 2); processFrame(frame);
if (shouldStop) { debugStream('reader:cancel-after-frame'); await reader.cancel(); break; }
continue; boundaryIndex = buffer.indexOf('\n\n'); }
processRawData(chunk); if (shouldStop) { break; } }
const remaining = `${buffer}${decoder.decode()}`.trim(); const remaining = shouldStop ? '' : `${buffer}${decoder.decode()}`.trim();
debugStream('remaining', remaining);
if (remaining) { if (remaining.includes('data:') || remaining.includes('event:')) {3 unmodified lines } }
debugStream('request:finish', { finalMessage });
return { assistantMessage: finalMessage, };66 unmodified lines
<div className="student-message-bubble"> <p className="student-message-content"> {!isUser && message.content === '' ? ( <LoadingIndicator label="Thinking" showSpinner={false} /> {!isUser && shouldAnimateTyping ? ( ) : !isUser && shouldAnimateTyping ? ( <TypingText key={message.uuid_id} text={message.content}54 unmodified lines isDirectChatMode = false, isStreamChatMode = false, messages: initialMessages, pendingInitialChat, selectedCourseId: initialSelectedCourseId, sessionId,}: MahasiswaChatProps) { const pendingInitialChatRef = useRef(pendingInitialChat ?? undefined); const isWaitingForDirectAssistantRef = useRef(false); const hasStartedPendingInitialChatRef = useRef(false); const streamingAssistantMessageRef = useRef< ChatMessageResponse | undefined >(undefined);3 unmodified lines const knownMessageIdsRef = useRef( new Set(initialMessages.map((message) => message.uuid_id)), ); const [pendingUserMessage] = useState<ChatMessageResponse | undefined>( pendingInitialChat ? createLocalUserMessage(pendingInitialChat.content) : undefined, ); const pendingUserMessageRef = useRef(pendingUserMessage); const [localBackendMessage, setLocalBackendMessage] = useState<string>(); const [animatedAssistantMessageId, setAnimatedAssistantMessageId] = useState<string>(); const [streamingAssistantMessageId, setStreamingAssistantMessageId] = useState<string>(); const [isProcessing, setIsProcessing] = useState( Boolean(pendingInitialChat), ); const [isProcessing, setIsProcessing] = useState(false); const [optimisticMessages, setOptimisticMessages] = useState< ChatMessageResponse[] >(() => (pendingUserMessage ? [pendingUserMessage] : [])); >([]); const [question, setQuestion] = useState(''); const [selectedCourseId, setSelectedCourseId] = useState( pendingInitialChat?.courseId ?? initialSelectedCourseId ?? currentSession?.course_id ?? '', initialSelectedCourseId ?? currentSession?.course_id ?? '', ); const studentName = useStoredStudentName(); const messagesEndRef = useRef<HTMLDivElement>(null);199 unmodified lines
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,6 unmodified lines
void (async () => { try { const response = isStreamChatMode const shouldUseStream = isStreamChatMode;
if (shouldUseStream) { setStreamingAssistantContent(''); }
const response = shouldUseStream ? await streamChatMessage( sessionId, content,2 unmodified lines ) : await storeChatMessage(sessionId, content, courseId);
pendingInitialChatRef.current = undefined;
if (isStreamChatMode) { if (shouldUseStream) { await waitForStreamingTyping(); }
if (response.assistantMessage) { const assistantMessage = response.assistantMessage;
if (isStreamChatMode) { if (shouldUseStream) { replaceStreamingAssistantMessage(assistantMessage); } else { setAnimatedAssistantMessageId( assistantMessage.uuid_id, ); setOptimisticMessages((currentMessages) => appendUniqueMessages(currentMessages, [ assistantMessage,2 unmodified lines } }
if (isStreamChatMode) { reloadChatHistory(); }
setQuestion(''); } catch (error) { debugStream('request:error', error); isWaitingForDirectAssistantRef.current = false; const streamingMessageId = streamingAssistantMessageRef.current?.uuid_id;19 unmodified lines ); }
pendingInitialChatRef.current = undefined; setQuestion(content); setLocalBackendMessage( error instanceof Error && error.message1 unmodified line : undefined, ); } finally { const emptyStreamingMessage = streamingAssistantMessageRef.current?.content === '' ? streamingAssistantMessageRef.current : undefined; clearStreamingTyping(); streamingAssistantMessageRef.current = undefined; setStreamingAssistantMessageId(undefined); setIsProcessing(false);
if (emptyStreamingMessage) { setOptimisticMessages((currentMessages) => currentMessages.filter( (message) => message.uuid_id !== emptyStreamingMessage.uuid_id, ), ); setLocalBackendMessage( 'Tidak ada respons dari AI. Silakan coba lagi.', ); setQuestion(content); } } })(); },2 unmodified lines clearStreamingTyping, isDirectChatMode, isStreamChatMode, reloadChatHistory, replaceStreamingAssistantMessage, setStreamingAssistantContent, sessionId, waitForStreamingTyping, ], );
useEffect(() => { const pendingInitialChat = pendingInitialChatRef.current;
if (!pendingInitialChat || hasStartedPendingInitialChatRef.current) { return; }
hasStartedPendingInitialChatRef.current = true; const pendingMessage = pendingUserMessageRef.current; const timeoutId = window.setTimeout(() => { sendMessage( pendingInitialChat.content, pendingInitialChat.courseId, pendingMessage, ); }, 0);
return () => window.clearTimeout(timeoutId); }, [sendMessage]);
const handleDeleteSession = ( targetSessionId: string, ): Promise<DeleteSessionResult> => {100 unmodified lines1011021031041041051061071081093 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179131 unmodified lines311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383100 unmodified lines 'title' => 'Apa itu stack?', ]) ->assertRedirect(route('mahasiswa.show', ['sessionId' => 'session-1'])) ->assertSessionHas('sevima_raghub_pending_initial_chat.session-1') ->assertSessionHas('sevima_raghub_pending_initial_chat.session-1', fn (array $pendingChat): bool => $pendingChat['content'] === 'Apa itu stack?' && $pendingChat['courseId'] === '101' && $pendingChat['session']['uuid_id'] === 'session-1') ->assertSessionHasNoErrors();
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'POST'3 unmodified lines && $request['title'] === 'Apa itu stack?');});
test('mahasiswa new chat detail page renders pending chat without fetching empty history', function () { config([ 'services.rag.base_url' => 'https://rag.test/api/v1', 'services.rag.chat_mode' => 'stream', ]);
Http::fake([ 'https://rag.test/api/v1/courses*' => Http::response([ 'data' => [ [ 'id' => '101', 'title' => 'Struktur Data', ], ], 'limit' => 100, 'page' => 1, 'total' => 1, ]), 'https://rag.test/api/v1/chats/sessions*' => Http::response([ 'data' => [], 'pagination' => [ 'limit' => 20, 'page' => 1, 'total' => 0, 'total_pages' => 0, ], ]), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', studentAuthUserCookie()) ->withSession([ 'sevima_raghub_pending_initial_chat.session-1' => [ 'content' => 'Apa itu stack?', 'courseId' => '101', 'session' => [ 'course_id' => '101', 'created_at' => '2026-05-01T10:00:00Z', 'message_count' => 0, 'title' => 'Apa itu stack?', 'updated_at' => '2026-05-01T10:00:00Z', 'user_id' => 'student-1', 'uuid_id' => 'session-1', ], ], ]) ->get(route('mahasiswa.show', ['sessionId' => 'session-1'])) ->assertOk() ->assertInertia(fn (Assert $page) => $page ->component('mahasiswa-chat') ->where('sessionId', 'session-1') ->where('currentSession.uuid_id', 'session-1') ->where('messages', []) ->where('pendingInitialChat.content', 'Apa itu stack?') ->where('pendingInitialChat.courseId', '101') ->where('selectedCourseId', '101'));
Http::assertNotSent(fn (HttpRequest $request): bool => $request->url() === 'https://rag.test/api/v1/chats/sessions/session-1' || $request->url() === 'https://rag.test/api/v1/chats/sessions/session-1/messages');});
test('mahasiswa chat detail page can be rendered with direct session messages', function () { config([ 'services.rag.base_url' => 'https://rag.test/api/v1',131 unmodified lines && $request['content'] === 'Apa itu stack?');});
test('mahasiswa stream mode json chat message uses rest endpoint', function () { config([ 'services.rag.base_url' => 'https://rag.test/api/v1', 'services.rag.chat_mode' => 'stream', ]);
Http::fake([ 'https://rag.test/api/v1/chats/sessions/session-1/messages' => Http::response([ 'content' => 'Stack adalah struktur data LIFO.', 'created_at' => '2026-05-01T10:01:00Z', 'role' => 'assistant', 'sources' => [], 'uuid_id' => 'message-1', ]), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', studentAuthUserCookie()) ->withHeaders(['Accept' => 'application/json']) ->postJson(route('mahasiswa.messages.store', ['sessionId' => 'session-1']), [ 'content' => 'Apa itu stack?', 'course_id' => '101', ]) ->assertSuccessful() ->assertJsonPath('assistantMessage.content', 'Stack adalah struktur data LIFO.');
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'POST' && $request->url() === 'https://rag.test/api/v1/chats/sessions/session-1/messages' && $request->hasHeader('Authorization', 'Bearer token') && $request['content'] === 'Apa itu stack?');});
test('mahasiswa stream chat message forwards backend server sent events', function () { config([ 'services.rag.base_url' => 'https://rag.test/api/v1', 'services.rag.chat_mode' => 'stream', ]);
$streamBody = "data: {\"content\":\"Stack adalah struktur data LIFO.\"}\n\n";
Http::fake([ 'https://rag.test/api/v1/chats/sessions/session-1/stream' => Http::response( $streamBody, 200, ['Content-Type' => 'text/event-stream'], ), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', studentAuthUserCookie()) ->withHeaders(['Accept' => 'text/event-stream']) ->post(route('mahasiswa.messages.store', ['sessionId' => 'session-1']), [ 'content' => 'Apa itu stack?', 'course_id' => '101', ]) ->assertSuccessful() ->assertStreamed() ->assertHeader('Content-Type', 'text/event-stream; charset=utf-8') ->assertStreamedContent($streamBody);
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'POST' && $request->url() === 'https://rag.test/api/v1/chats/sessions/session-1/stream' && $request->hasHeader('Authorization', 'Bearer token') && $request->hasHeader('Accept', 'text/event-stream') && $request['content'] === 'Apa itu stack?');});
test('mahasiswa chat message uses backend error message', function () { config([ 'services.rag.base_url' => 'https://rag.test/api/v1',.gitignore+5-1
app/Http/Controllers/MahasiswaController.php+34-14
boost.json+1-1
resources/js/components/appearance-toggle.tsx+7-1
resources/js/pages/mahasiswa-chat.tsx+158-92
tests/Feature/MahasiswaDashboardTest.php+131-1