forge
Explore
Log in

Don't you dare go Hollow

🤖 wire Çelebi panel to chatbot API

Browse files at this commit

70c243c6fae03fe9fe097e7aaf65b2069810a125Burak BoduroğluParent: 08a26e0
  • feat
    • 🤖 wire Çelebi panel to chatbot API
Show full message
feat: 🤖 wire Çelebi panel to chatbot API

Adds the chatbot API layer (create thread, send message, poll message
by id) and connects the panel to it: async send, pending/failed/
truncated message states, per-message polling with cleanup. Also
carries the pre-existing inert-on-open SidePanel fix, empty/unavailable
copy updates, and the favicon link.

Pre-existing work already in the tree before this session started;
committed as its own baseline so the subsequent layout fix is a clean,
reviewable diff on top.
index.htmlmodified+1 -0
@@ -4,6 +4,7 @@
4 <meta charset="UTF-8" />4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <meta name="color-scheme" content="light dark" />6 <meta name="color-scheme" content="light dark" />
7+ <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
7 <title>Hezarfen</title>8 <title>Hezarfen</title>
8 <script>9 <script>
9 (() => {10 (() => {
public/favicon.svgadded+5 -0
@@ -0,0 +1,5 @@
1+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2+ <rect width="64" height="64" rx="16" fill="#0f766e"/>
3+ <path fill="#fef3c7" d="M14 18h36v8H14zm4 12h28v18H18z"/>
4+ <path fill="#0f766e" d="M24 34h16v4H24zm0 8h12v3H24z"/>
5+</svg>
src/api/__tests__/chatbot/chatbot.test.tsadded+33 -0
@@ -0,0 +1,33 @@
1+import { afterEach, describe, expect, it, vi } from "vitest";
2+import { getChatbotMessageById, postChatbotMessage, postChatbotThread } from "../../chatbot";
3+import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch";
4+
5+describe("chatbot API", () => {
6+ afterEach(() => vi.restoreAllMocks());
7+
8+ it("creates an untitled chatbot thread", async () => {
9+ mockFetchSuccess({ id: "thread-1" });
10+ await postChatbotThread();
11+ const [url, init] = lastFetchCall();
12+ expect(url).toBe("/api/chatbot/threads");
13+ expect(init?.method).toBe("POST");
14+ expect(init?.body).toBe("{}");
15+ });
16+
17+ it("sends a message to its thread", async () => {
18+ mockFetchSuccess({ message_id: "answer-1", status: "pending" });
19+ await postChatbotMessage("thread 1", "Merhaba");
20+ const [url, init] = lastFetchCall();
21+ expect(url).toBe("/api/chatbot/threads/thread%201/messages");
22+ expect(init?.method).toBe("POST");
23+ expect(init?.body).toBe(JSON.stringify({ content: "Merhaba" }));
24+ });
25+
26+ it("reads a pending or completed assistant message", async () => {
27+ mockFetchSuccess({ id: "answer-1", status: "complete" });
28+ await getChatbotMessageById("thread-1", "answer-1");
29+ const [url, init] = lastFetchCall();
30+ expect(url).toBe("/api/chatbot/threads/thread-1/messages/answer-1");
31+ expect(init?.method).toBe("GET");
32+ });
33+});
src/api/chatbot/getChatbotMessageById.tsadded+8 -0
@@ -0,0 +1,8 @@
1+import { client } from "../client";
2+import type { ChatbotMessage } from "./types";
3+
4+export function getChatbotMessageById(threadId: string, messageId: string): Promise<ChatbotMessage> {
5+ return client<ChatbotMessage>(
6+ `/chatbot/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}`,
7+ );
8+}
src/api/chatbot/index.tsadded+4 -0
@@ -0,0 +1,4 @@
1+export * from "./getChatbotMessageById";
2+export * from "./postChatbotMessage";
3+export * from "./postChatbotThread";
4+export * from "./types";
src/api/chatbot/postChatbotMessage.tsadded+9 -0
@@ -0,0 +1,9 @@
1+import { client } from "../client";
2+import type { AcceptedChatbotMessage } from "./types";
3+
4+export function postChatbotMessage(threadId: string, content: string): Promise<AcceptedChatbotMessage> {
5+ return client<AcceptedChatbotMessage>(`/chatbot/threads/${encodeURIComponent(threadId)}/messages`, {
6+ method: "POST",
7+ body: { content },
8+ });
9+}
src/api/chatbot/postChatbotThread.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { ChatbotThread } from "./types";
3+
4+export function postChatbotThread(): Promise<ChatbotThread> {
5+ return client<ChatbotThread>("/chatbot/threads", { method: "POST", body: {} });
6+}
src/api/chatbot/types.tsadded+25 -0
@@ -0,0 +1,25 @@
1+export type ChatbotMessageStatus = "pending" | "complete" | "failed";
2+
3+export type ChatbotThread = {
4+ id: string;
5+ title: string | null;
6+ created_at: number;
7+ updated_at: number;
8+};
9+
10+export type ChatbotMessage = {
11+ id: string;
12+ thread_id: string;
13+ role: "user" | "assistant";
14+ status: ChatbotMessageStatus;
15+ content: string;
16+ truncated: boolean;
17+ error_code: string | null;
18+ created_at: number;
19+ completed_at: number | null;
20+};
21+
22+export type AcceptedChatbotMessage = {
23+ message_id: string;
24+ status: "pending";
25+};
src/components/layout/celebi-panel.tsxmodified+106 -28
@@ -1,24 +1,98 @@
1-import { For, Show, createSignal } from "solid-js";1+import { For, Show, createSignal, onCleanup } from "solid-js";
2+import { getChatbotMessageById, postChatbotMessage, postChatbotThread, type ChatbotMessage } from "@/api/chatbot";
3+import { formatApiError } from "@/api/client";
2 import { Button } from "@/components/ui/button";4 import { Button } from "@/components/ui/button";
3-import { IconSparkles } from "@/components/ui/icons";5+import { IconAlert, IconBotSquare, IconSend, IconSparkles } from "@/components/ui/icons";
4 import { SidePanel } from "@/components/ui/side-panel";6 import { SidePanel } from "@/components/ui/side-panel";
5 import { Textarea } from "@/components/ui/textarea";7 import { Textarea } from "@/components/ui/textarea";
6-import { useT } from "@/stores/preferences-context";8+import { usePreferences, useT } from "@/stores/preferences-context";
7 9
8-type Message = {10+type PanelMessage = Pick<ChatbotMessage, "id" | "role" | "status" | "content" | "truncated" | "error_code">;
9- role: "user" | "assistant";11+
10- text: string;12+const POLL_INTERVAL_MS = 1_000;
11-};
12 13
13 export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean) => void }) {14 export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean) => void }) {
14 const t = useT();15 const t = useT();
16+ const { locale } = usePreferences();
15 const [draft, setDraft] = createSignal("");17 const [draft, setDraft] = createSignal("");
16- const [messages, setMessages] = createSignal<Message[]>([]);18+ const [messages, setMessages] = createSignal<PanelMessage[]>([]);
17- const send = () => {19+ const [threadId, setThreadId] = createSignal<string>();
18- const text = draft().trim();20+ const [sending, setSending] = createSignal(false);
19- if (!text) return;21+ let pollTimer: number | undefined;
20- setMessages((items) => [...items, { role: "user", text }, { role: "assistant", text: t("ai.unavailable") }]);22+
23+ const stopPolling = () => {
24+ if (pollTimer !== undefined) window.clearInterval(pollTimer);
25+ pollTimer = undefined;
26+ };
27+
28+ const failureMessage = (code: string | null) => {
29+ if (locale() === "tr") return code ? `Yanıt alınamadı (${code}).` : "Yanıt alınamadı. Lütfen tekrar dene.";
30+ return code ? `No response was received (${code}).` : "No response was received. Please try again.";
31+ };
32+
33+ const updateAssistant = (message: ChatbotMessage) => {
34+ setMessages((items) => items.map((item) => (item.id === message.id ? message : item)));
35+ if (message.status !== "pending") stopPolling();
36+ };
37+
38+ const poll = (activeThreadId: string, messageId: string) => {
39+ stopPolling();
40+ const read = async () => {
41+ try {
42+ updateAssistant(await getChatbotMessageById(activeThreadId, messageId));
43+ } catch {
44+ // A transient poll failure should not turn a received request into an error.
45+ }
46+ };
47+ void read();
48+ pollTimer = window.setInterval(() => void read(), POLL_INTERVAL_MS);
49+ };
50+
51+ onCleanup(stopPolling);
52+
53+ const send = async () => {
54+ const content = draft().trim();
55+ if (!content || sending()) return;
56+
57+ setSending(true);
21 setDraft("");58 setDraft("");
59+ const localUserId = `local-${Date.now()}`;
60+ setMessages((items) => [...items, { id: localUserId, role: "user", status: "complete", content, truncated: false, error_code: null }]);
61+
62+ try {
63+ const activeThreadId = threadId() ?? (await postChatbotThread()).id;
64+ setThreadId(activeThreadId);
65+ const accepted = await postChatbotMessage(activeThreadId, content);
66+ setMessages((items) => [
67+ ...items,
68+ {
69+ id: accepted.message_id,
70+ thread_id: activeThreadId,
71+ role: "assistant",
72+ status: "pending",
73+ content: "",
74+ truncated: false,
75+ error_code: null,
76+ created_at: Date.now(),
77+ completed_at: null,
78+ },
79+ ]);
80+ poll(activeThreadId, accepted.message_id);
81+ } catch (error) {
82+ setMessages((items) => [
83+ ...items,
84+ {
85+ id: `error-${Date.now()}`,
86+ role: "assistant",
87+ status: "failed",
88+ content: formatApiError(error, locale()),
89+ truncated: false,
90+ error_code: null,
91+ },
92+ ]);
93+ } finally {
94+ setSending(false);
95+ }
22 };96 };
23 97
24 return (98 return (
@@ -27,35 +101,39 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean
27 <Show101 <Show
28 when={messages().length > 0}102 when={messages().length > 0}
29 fallback={103 fallback={
30- <div class="rounded-xl border border-dashed border-border bg-card px-4 py-8 text-center text-sm text-muted-foreground">104+ <div class="relative overflow-hidden rounded-2xl border border-border bg-card px-5 py-9 text-center text-sm text-muted-foreground">
31- <span class="mx-auto mb-3 flex h-10 w-10 items-center justify-center rounded-xl border border-border bg-background text-primary">105+ <div class="absolute inset-x-8 top-0 h-px bg-gradient-to-r from-transparent via-primary/60 to-transparent" />
106+ <span class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary ring-1 ring-primary/20">
32 <IconSparkles class="h-5 w-5" />107 <IconSparkles class="h-5 w-5" />
33 </span>108 </span>
34 {t("ai.empty")}109 {t("ai.empty")}
35 </div>110 </div>
36 }111 }
37 >112 >
38- <div class="flex flex-1 flex-col gap-3">113+ <div class="flex flex-1 flex-col gap-3 overflow-y-auto pr-1">
39 <For each={messages()}>114 <For each={messages()}>
40 {(message) => (115 {(message) => (
41- <div class={message.role === "user" ? "ml-8 rounded-xl bg-primary px-3 py-2 text-sm text-primary-foreground" : "mr-8 rounded-xl border border-border bg-card px-3 py-2 text-sm text-foreground"}>116+ <div class={message.role === "user" ? "ml-8 rounded-2xl rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground" : "mr-6 rounded-2xl rounded-bl-sm border border-border bg-card px-3.5 py-2.5 text-sm text-foreground shadow-sm"}>
42- {message.text}117+ <Show when={message.role === "assistant" && message.status === "pending"} fallback={<p class="whitespace-pre-wrap leading-6">{message.status === "failed" && !message.content ? failureMessage(message.error_code) : message.content}</p>}>
118+ <span class="flex items-center gap-2 text-muted-foreground"><IconBotSquare class="h-4 w-4 text-primary" /><span class="animate-pulse">•••</span></span>
119+ </Show>
120+ <Show when={message.role === "assistant" && message.status === "failed"}>
121+ <span class="mt-2 flex items-center gap-1.5 text-xs text-destructive"><IconAlert class="h-3.5 w-3.5" />{failureMessage(message.error_code)}</span>
122+ </Show>
123+ <Show when={message.role === "assistant" && message.truncated}>
124+ <p class="mt-2 text-xs text-muted-foreground">{locale() === "tr" ? "Yanıt uzunluk sınırında kısaltıldı." : "Response was shortened at the configured limit."}</p>
125+ </Show>
43 </div>126 </div>
44 )}127 )}
45 </For>128 </For>
46 </div>129 </div>
47 </Show>130 </Show>
48- <form131+ <form class="mt-auto rounded-2xl border border-border bg-card p-2 shadow-sm" onSubmit={(event) => { event.preventDefault(); void send(); }}>
49- class="mt-auto space-y-2"132+ <Textarea rows={3} class="resize-none border-0 bg-transparent shadow-none focus-visible:ring-0" value={draft()} placeholder={t("ai.placeholder")} onInput={(event) => setDraft(event.currentTarget.value)} />
50- onSubmit={(event) => {133+ <div class="flex items-center justify-between px-1 pt-2">
51- event.preventDefault();134+ <span class="text-xs text-muted-foreground">{locale() === "tr" ? "Çelebi yanıtları yapay zekâ tarafından üretilir." : "Çelebi responses are AI-generated."}</span>
52- send();135+ <Button type="submit" size="sm" class="rounded-xl" disabled={!draft().trim() || sending()}>
53- }}136+ <IconSend class="mr-1.5 h-4 w-4" />{t("ai.send")}
54- >
55- <Textarea rows={3} value={draft()} placeholder={t("ai.placeholder")} onInput={(event) => setDraft(event.currentTarget.value)} />
56- <div class="flex justify-end">
57- <Button type="submit" size="sm" class="rounded-lg" disabled={!draft().trim()}>
58- {t("ai.send")}
59 </Button>137 </Button>
60 </div>138 </div>
61 </form>139 </form>
src/components/ui/side-panel.tsxmodified+20 -2
@@ -1,8 +1,10 @@
1 import { Dialog as DialogPrimitive } from "@kobalte/core/dialog";1 import { Dialog as DialogPrimitive } from "@kobalte/core/dialog";
2-import type { ParentProps } from "solid-js";2+import { createEffect, onCleanup, type ParentProps } from "solid-js";
3 import { IconX } from "@/components/ui/icons";3 import { IconX } from "@/components/ui/icons";
4 import { cn } from "@/lib/cn";4 import { cn } from "@/lib/cn";
5 5
6+let openPanelCount = 0;
7+
6 export function SidePanel(8 export function SidePanel(
7 props: ParentProps<{9 props: ParentProps<{
8 open: boolean;10 open: boolean;
@@ -14,6 +16,22 @@ export function SidePanel(
14 size?: "default" | "wide" | "xl";16 size?: "default" | "wide" | "xl";
15 }>,17 }>,
16 ) {18 ) {
19+ // Kobalte's modal Dialog hides the app with aria-hidden before its focus
20+ // scope can move focus into this portalled panel. Chromium correctly blocks
21+ // that transition when the opener still owns focus. `inert` makes the app
22+ // unfocusable as well as hidden to assistive tech, while the portal remains
23+ // interactive outside #root.
24+ createEffect(() => {
25+ if (!props.open || typeof document === "undefined") return;
26+ const root = document.getElementById("root");
27+ openPanelCount += 1;
28+ root?.setAttribute("inert", "");
29+ onCleanup(() => {
30+ openPanelCount -= 1;
31+ if (openPanelCount === 0) root?.removeAttribute("inert");
32+ });
33+ });
34+
17 const width = () => {35 const width = () => {
18 if (props.size === "xl") return "max-w-[min(48rem,100vw)]";36 if (props.size === "xl") return "max-w-[min(48rem,100vw)]";
19 if (props.size === "wide") return "max-w-[min(42rem,100vw)]";37 if (props.size === "wide") return "max-w-[min(42rem,100vw)]";
@@ -21,7 +39,7 @@ export function SidePanel(
21 };39 };
22 40
23 return (41 return (
24- <DialogPrimitive open={props.open} onOpenChange={props.onOpenChange}>42+ <DialogPrimitive open={props.open} onOpenChange={props.onOpenChange} modal={false} preventScroll>
25 <DialogPrimitive.Portal>43 <DialogPrimitive.Portal>
26 <DialogPrimitive.Overlay class="fixed inset-0 z-50 bg-black/40 backdrop-blur-md transition-opacity duration-200 data-closed:opacity-0 data-expanded:opacity-100" />44 <DialogPrimitive.Overlay class="fixed inset-0 z-50 bg-black/40 backdrop-blur-md transition-opacity duration-200 data-closed:opacity-0 data-expanded:opacity-100" />
27 <DialogPrimitive.Content45 <DialogPrimitive.Content
src/i18n/messages.tsmodified+4 -4
@@ -947,10 +947,10 @@ const en: Dict = {
947 "ai.askCelebi": "Ask Çelebi",947 "ai.askCelebi": "Ask Çelebi",
948 "ai.title": "Çelebi",948 "ai.title": "Çelebi",
949 "ai.description": "Campus assistant",949 "ai.description": "Campus assistant",
950- "ai.empty": "Ask Çelebi about this workspace. AI answers will be enabled when the backend is connected.",950+ "ai.empty": "Ask Çelebi about your school day, courses, exams, or attendance.",
951 "ai.placeholder": "Ask about courses, exams, attendance...",951 "ai.placeholder": "Ask about courses, exams, attendance...",
952 "ai.send": "Send",952 "ai.send": "Send",
953- "ai.unavailable": "Çelebi is not connected yet. Backend AI endpoint is needed for real answers.",953+ "ai.unavailable": "Çelebi is temporarily unavailable. Please try again shortly.",
954 "nav.home": "Home",954 "nav.home": "Home",
955 "nav.notes": "Notes",955 "nav.notes": "Notes",
956 "nav.events": "Events",956 "nav.events": "Events",
@@ -1900,10 +1900,10 @@ const tr: Dict = {
1900 "ai.askCelebi": "Çelebi’ye sor",1900 "ai.askCelebi": "Çelebi’ye sor",
1901 "ai.title": "Çelebi",1901 "ai.title": "Çelebi",
1902 "ai.description": "Kampüs asistanı",1902 "ai.description": "Kampüs asistanı",
1903- "ai.empty": "Bu çalışma alanı hakkında Çelebi’ye sor. Backend bağlanınca gerçek yanıtlar aktif olacak.",1903+ "ai.empty": "Okul günün, derslerin, sınavların veya yoklamaların hakkında Çelebi’ye sor.",
1904 "ai.placeholder": "Dersler, sınavlar, yoklamalar hakkında sor...",1904 "ai.placeholder": "Dersler, sınavlar, yoklamalar hakkında sor...",
1905 "ai.send": "Gönder",1905 "ai.send": "Gönder",
1906- "ai.unavailable": "Çelebi henüz bağlı değil. Gerçek yanıtlar için backend AI endpoint’i gerekli.",1906+ "ai.unavailable": "Çelebi şu anda kullanılamıyor. Lütfen biraz sonra tekrar dene.",
1907 "nav.home": "Ana sayfa",1907 "nav.home": "Ana sayfa",
1908 "nav.notes": "Defter",1908 "nav.notes": "Defter",
1909 "nav.events": "Etkinlikler",1909 "nav.events": "Etkinlikler",