Spaces:
Sleeping
Sleeping
AKKHIRNYA BISA STREAM
Browse filesFiles changed (6)
29 unmodified lines3031323329 unmodified linesAGENTS.md.agents.codex29 unmodified lines303132333435363729 unmodified linesAGENTS.md.agents.codexCLAUDE.md.claude.mcp.jsonboost.json
16 unmodified lines171819202122232412 unmodified lines37383940414243442 unmodified lines4748495051525354555632 unmodified lines8990919293949510 unmodified lines106107108109110111112113224 unmodified lines33833934034134234334434596 unmodified lines44244344444544644744844916 unmodified linesprivate 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'],]);try {$session = $this->createChatSession($payload, $this->authToken($request));} 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'],]);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()) {try {return $this->streamChatMessage($sessionId,$payload['content'],224 unmodified lines$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();96 unmodified linesreturn self::DIRECT_MESSAGES_SESSION_PREFIX.'.'.$sessionId;}private function pendingInitialChatKey(string $sessionId): string{return self::PENDING_INITIAL_CHAT_SESSION_PREFIX.'.'.$sessionId;}}16 unmodified lines17181920212212 unmodified lines353637383940414243442 unmodified lines474849505152535455565758596061626364656667686932 unmodified lines10210310410510610710 unmodified lines118119120121122123124125126127224 unmodified lines35235335435535635735835936036136236336436536636736836996 unmodified lines46646746846916 unmodified linesprivate const DIRECT_MESSAGES_SESSION_PREFIX = 'sevima_raghub_direct_messages';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, $token);} catch (RagApiException $exception) {return back()->withErrors(['chat' => $exception->getMessage()])2 unmodified lines$sessionId = (string) ($session['uuid_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,'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() && $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()) {$chunk = $stream->read(1);if ($chunk === '') {usleep(10_000);continue;}echo $chunk;if (ob_get_level() > 0) {ob_flush();96 unmodified linesreturn self::DIRECT_MESSAGES_SESSION_PREFIX.'.'.$sessionId;}}
123456{"agents": ["codex"],"cloud": false,"guidelines": true,123456{"agents": ["claude_code"],"cloud": false,"guidelines": true,
12344 unmodified lines9101112131415import { Moon, Sun } from 'lucide-react';import { Button } from '@/components/ui/button';import { useAppearance } from '@/hooks/use-appearance';import { cn } from '@/lib/utils';4 unmodified linesexport default function AppearanceToggle({ className }: AppearanceToggleProps) {const { resolvedAppearance, updateAppearance } = useAppearance();const isDarkMode = resolvedAppearance === 'dark';const handleToggle = (): void => {updateAppearance(isDarkMode ? 'light' : 'dark');123454 unmodified lines101112131415161718192021import { 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 linesexport default function AppearanceToggle({ className }: AppearanceToggleProps) {const { resolvedAppearance, updateAppearance } = useAppearance();const [isMounted, setIsMounted] = useState(false);const isDarkMode = isMounted && resolvedAppearance === 'dark';useEffect(() => {setIsMounted(true);}, []);const handleToggle = (): void => {updateAppearance(isDarkMode ? 'light' : 'dark');
19 unmodified lines202122232425262728293018 unmodified lines4950515253545576 unmodified lines13213313413513613773 unmodified lines21121221321421521621721899 unmodified lines3183193203213223233243253261 unmodified line3283293303313323333343353363373383393403413422 unmodified lines3453463473483493503513523533543556 unmodified lines3623633643653663673683693703713723733743753767 unmodified lines3843853863873883899 unmodified lines3994004014024034044054064074084094104114124136 unmodified lines4204214224234244254 unmodified lines4304314324334344351 unmodified line4374384394404414421 unmodified line4444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864873 unmodified lines49149249349449549666 unmodified lines56356456556656756856954 unmodified lines6246256266276286296306316326336346356363 unmodified lines640641642643644645646647648649650651652653654655656657658659660661662663664665666667668199 unmodified lines8688698708718728738748758768778788798808818828838846 unmodified lines8918928938948958968972 unmodified lines9009019029039049059069079089099109119129139149159169172 unmodified lines92092192292392492592692792892993093119 unmodified lines9519529539549559569571 unmodified line9599609619629639649659669679682 unmodified lines971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100319 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 linesisDirectChatMode?: boolean;isStreamChatMode?: boolean;messages: ChatMessageResponse[];pendingInitialChat?: PendingInitialChat | null;selectedCourseId?: string | null;sessionId: string;};76 unmodified lines);}async function storeChatMessage(sessionId: string,content: string,73 unmodified lines'completed','done','end','finish','finished','success',].includes(value ?? '');}99 unmodified linesfunction 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;1 unmodified lineif (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,2 unmodified linesconst payload = parseStreamPayload(data);const finalMessage = finalMessageFromPayload(payload);if (isStreamDone(data, eventName, payload)) {return { done: true, finalMessage };}if (eventName === 'error') {throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);6 unmodified lines}if (finalMessage) {return {done: false,finalMessage,};}const delta = streamTextFromPayload(payload);if (delta) {onDelta(delta);}7 unmodified linesonDelta: (delta: string) => void,): Promise<StoreMessageJsonResponse> {const token = csrfToken();const response = await fetch(storeMahasiswaMessage.url(sessionId), {body: JSON.stringify({content,9 unmodified linesmethod: 'POST',});if (!response.ok) {const payload: unknown = await response.json().catch(() => undefined);throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);}if (!response.body) {return {};}6 unmodified linesconst processFrame = (frame: string): void => {const { data, eventName } = parseSseFrame(frame);if (!data) {return;}4 unmodified lines};const processRawData = (data: string): void => {const result = handleStreamPayload(data, undefined, onDelta);finalMessage = result.finalMessage ?? finalMessage;shouldStop = shouldStop || result.done;1 unmodified linewhile (true) {if (shouldStop) {await reader.cancel();break;}1 unmodified lineconst { 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:')) {3 unmodified lines}}return {assistantMessage: finalMessage,};66 unmodified lines<div className="student-message-bubble"><p className="student-message-content">{!isUser && shouldAnimateTyping ? (<TypingTextkey={message.uuid_id}text={message.content}54 unmodified linesisDirectChatMode = 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 linesconst 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 [optimisticMessages, setOptimisticMessages] = useState<ChatMessageResponse[]>(() => (pendingUserMessage ? [pendingUserMessage] : []));const [question, setQuestion] = useState('');const [selectedCourseId, setSelectedCourseId] = useState(pendingInitialChat?.courseId ??initialSelectedCourseId ??currentSession?.course_id ??'',);const studentName = useStoredStudentName();const messagesEndRef = useRef<HTMLDivElement>(null);199 unmodified linesuseEffect(() => 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 linesvoid (async () => {try {const response = isStreamChatMode? await streamChatMessage(sessionId,content,2 unmodified lines): 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,2 unmodified lines}}if (isStreamChatMode) {reloadChatHistory();}setQuestion('');} catch (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 {clearStreamingTyping();streamingAssistantMessageRef.current = undefined;setStreamingAssistantMessageId(undefined);setIsProcessing(false);}})();},2 unmodified linesclearStreamingTyping,isDirectChatMode,isStreamChatMode,reloadChatHistory,replaceStreamingAssistantMessage,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> => {19 unmodified lines20212223242518 unmodified lines44454647484976 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416573 unmodified lines23924024124224324424524624724824925099 unmodified lines3503513523533543553563573583593603613623631 unmodified line3653663673683693703713723733743753763773783793803813823833843853863873883893903912 unmodified lines3943953963973983994004014024034044054064074084094104114124136 unmodified lines4204214224234244254264274284294304314324334344354364374384397 unmodified lines4474484494504514524534544554564574584594609 unmodified lines4704714724734744754764774784794804814824834844854864874884894904914924934944956 unmodified lines5025035045055065075085094 unmodified lines5145155165175185195205211 unmodified line5235245255265275285291 unmodified line5315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695703 unmodified lines57457557657757857958058166 unmodified lines64864965065165265365465565665765865954 unmodified lines7147157167177187197207217227233 unmodified lines727728729730731732733734735736737738739740741742743744199 unmodified lines9449459469479489496 unmodified lines9569579589599609619629639649659669679682 unmodified lines9719729739749759769779789799809819829839849859869879889892 unmodified lines992993994995996997998999100019 unmodified lines1020102110221023102410251 unmodified line10271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310542 unmodified lines105710581059106010611062106310641065106610671068106919 unmodified linesimport { destroy as destroyMahasiswaSession } from '@/routes/mahasiswa';import { store as storeMahasiswaMessage } from '@/routes/mahasiswa/messages';type StoreMessageJsonResponse = {assistantMessage?: ChatMessageResponse;};18 unmodified linesisDirectChatMode?: boolean;isStreamChatMode?: boolean;messages: ChatMessageResponse[];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 linesfunction 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 lineif (line.startsWith('data:')) {dataLines.push(line.slice('data:'.length).trimStart());continue;}fallbackLines.push(line);}return {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 linesconst payload = parseStreamPayload(data);const finalMessage = finalMessageFromPayload(payload);debugStream('payload', { data, eventName, payload });if (isStreamDone(data, eventName, payload)) {debugStream('done-status', { data, eventName, payload });return {done: true,finalMessage: isAssistantMessage(finalMessage)? finalMessage: undefined,};}if (eventName?.toLowerCase() === 'error') {throw new BackendResponseError(backendMessageFromPayload(payload) ?? '',);6 unmodified lines}if (finalMessage) {debugStream('final-message', finalMessage);return {done: isAssistantMessage(finalMessage),finalMessage: isAssistantMessage(finalMessage)? finalMessage: undefined,};}const delta = streamTextFromPayload(payload);if (delta) {debugStream('delta', delta);onDelta(delta);}7 unmodified linesonDelta: (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 linesmethod: '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 linesconst 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 linewhile (true) {if (shouldStop) {debugStream('reader:cancel-before-read');await reader.cancel();break;}1 unmodified lineconst { done, value } = await reader.read();if (done) {debugStream('reader:done');break;}const chunk = decoder.decode(value, { stream: true });debugStream('chunk', chunk);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) {debugStream('reader:cancel-after-frame');await reader.cancel();break;}boundaryIndex = buffer.indexOf('\n\n');}if (shouldStop) {break;}}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 === '' ? (<LoadingIndicatorlabel="Thinking"showSpinner={false}/>) : !isUser && shouldAnimateTyping ? (<TypingTextkey={message.uuid_id}text={message.content}54 unmodified linesisDirectChatMode = false,isStreamChatMode = false,messages: initialMessages,selectedCourseId: initialSelectedCourseId,sessionId,}: MahasiswaChatProps) {const isWaitingForDirectAssistantRef = useRef(false);const streamingAssistantMessageRef = useRef<ChatMessageResponse | undefined>(undefined);3 unmodified linesconst knownMessageIdsRef = useRef(new Set(initialMessages.map((message) => message.uuid_id)),);const [localBackendMessage, setLocalBackendMessage] = useState<string>();const [animatedAssistantMessageId, setAnimatedAssistantMessageId] =useState<string>();const [streamingAssistantMessageId, setStreamingAssistantMessageId] =useState<string>();const [isProcessing, setIsProcessing] = useState(false);const [optimisticMessages, setOptimisticMessages] = useState<ChatMessageResponse[]>([]);const [question, setQuestion] = useState('');const [selectedCourseId, setSelectedCourseId] = useState(initialSelectedCourseId ?? currentSession?.course_id ?? '',);const studentName = useStoredStudentName();const messagesEndRef = useRef<HTMLDivElement>(null);199 unmodified linesuseEffect(() => clearStreamingTyping, [clearStreamingTyping]);const sendMessage = useCallback((content: string,6 unmodified linesvoid (async () => {try {const shouldUseStream = isStreamChatMode;if (shouldUseStream) {setStreamingAssistantContent('');}const response = shouldUseStream? await streamChatMessage(sessionId,content,2 unmodified lines): await storeChatMessage(sessionId, content, courseId);if (shouldUseStream) {await waitForStreamingTyping();}if (response.assistantMessage) {const assistantMessage = response.assistantMessage;if (shouldUseStream) {replaceStreamingAssistantMessage(assistantMessage);} else {setAnimatedAssistantMessageId(assistantMessage.uuid_id,);setOptimisticMessages((currentMessages) =>appendUniqueMessages(currentMessages, [assistantMessage,2 unmodified lines}}setQuestion('');} catch (error) {debugStream('request:error', error);isWaitingForDirectAssistantRef.current = false;const streamingMessageId =streamingAssistantMessageRef.current?.uuid_id;19 unmodified lines);}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 linesclearStreamingTyping,isDirectChatMode,isStreamChatMode,replaceStreamingAssistantMessage,setStreamingAssistantContent,sessionId,waitForStreamingTyping,],);const handleDeleteSession = (targetSessionId: string,): Promise<DeleteSessionResult> => {
100 unmodified lines1011021031041051061073 unmodified lines111112113114115116131 unmodified lines248249250251252253100 unmodified lines'title' => 'Apa itu stack?',])->assertRedirect(route('mahasiswa.show', ['sessionId' => 'session-1']))->assertSessionHas('sevima_raghub_pending_initial_chat.session-1')->assertSessionHasNoErrors();Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'POST'3 unmodified lines&& $request['title'] === 'Apa itu stack?');});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 chat message uses backend error message', function () {config(['services.rag.base_url' => 'https://rag.test/api/v1',100 unmodified lines1011021031041051061071081093 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', 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