From 796c6d9a56c8cf18b9f779d6234399f976c37d24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Sat, 1 Aug 2026 21:59:44 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=A7=B5=20chatbot=20thread=20histo?= =?UTF-8?q?ry,=20rename/delete,=20and=20SSE=20streaming=20-=20thread=20end?= =?UTF-8?q?points:=20list=20threads,=20list=20a=20thread's=20messages,=20P?= =?UTF-8?q?ATCH=20title,=20=20=20DELETE=20thread;=20postChatbotThread=20ac?= =?UTF-8?q?cepts=20an=20optional=20title=20body=20-=20celebi-panel:=20conv?= =?UTF-8?q?ersation=20switcher=20bar=20(new/open/rename/delete)=20and=20?= =?UTF-8?q?=20=20EventSource=20streaming=20with=20delta=20accumulation=20a?= =?UTF-8?q?nd=20polling=20fallback=20-=20ai=20bridge=20certificate=20endpo?= =?UTF-8?q?int=20(getBridgeCertificate)=20with=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/__tests__/ai/ai.test.ts | 11 +++++++ src/api/__tests__/chatbot/chatbot.test.ts | 12 ++++++-- src/api/ai/getBridgeCertificate.ts | 3 ++ src/api/ai/index.ts | 1 + src/api/chatbot/deleteChatbotThreadById.ts | 4 +++ src/api/chatbot/getChatbotThreadMessages.ts | 5 ++++ src/api/chatbot/getChatbotThreads.ts | 5 ++++ src/api/chatbot/index.ts | 4 +++ src/api/chatbot/patchChatbotThreadById.ts | 5 ++++ src/api/chatbot/postChatbotThread.ts | 6 ++-- src/api/chatbot/types.ts | 7 +++++ src/api/client/types.ts | 6 ---- src/components/layout/celebi-panel.tsx | 32 ++++++++++++++++++--- 13 files changed, 86 insertions(+), 15 deletions(-) create mode 100644 src/api/__tests__/ai/ai.test.ts create mode 100644 src/api/ai/getBridgeCertificate.ts create mode 100644 src/api/ai/index.ts create mode 100644 src/api/chatbot/deleteChatbotThreadById.ts create mode 100644 src/api/chatbot/getChatbotThreadMessages.ts create mode 100644 src/api/chatbot/getChatbotThreads.ts create mode 100644 src/api/chatbot/patchChatbotThreadById.ts diff --git a/src/api/__tests__/ai/ai.test.ts b/src/api/__tests__/ai/ai.test.ts new file mode 100644 index 0000000..9ef4a8b --- /dev/null +++ b/src/api/__tests__/ai/ai.test.ts @@ -0,0 +1,11 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { getBridgeCertificate } from "../../ai"; +import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; +describe("ai API", () => { + afterEach(() => vi.restoreAllMocks()); + it("gets the bridge certificate", async () => { + mockFetchSuccess({ protocol: "hab/1", certificate_pem: "pem", fingerprint_sha256: "hash" }); + await getBridgeCertificate(); + expect(lastFetchCall()[0]).toBe("/api/ai/certificate"); + }); +}); diff --git a/src/api/__tests__/chatbot/chatbot.test.ts b/src/api/__tests__/chatbot/chatbot.test.ts index ab18e8e..098addf 100644 --- a/src/api/__tests__/chatbot/chatbot.test.ts +++ b/src/api/__tests__/chatbot/chatbot.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { getChatbotMessageById, postChatbotMessage, postChatbotThread } from "../../chatbot"; -import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch"; +import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread } from "../../chatbot"; +import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; describe("chatbot API", () => { afterEach(() => vi.restoreAllMocks()); @@ -13,6 +13,14 @@ describe("chatbot API", () => { expect(init?.method).toBe("POST"); expect(init?.body).toBe("{}"); }); + it("lists threads and a selected thread's messages", async () => { + mockFetchSuccess({ items: [], total: 0 }); await getChatbotThreads({ limit: 20 }); expect(lastFetchCall()[0]).toBe("/api/chatbot/threads?limit=20"); + mockFetchSuccess({ items: [], total: 0 }); await getChatbotThreadMessages("thread 1", { limit: 20 }); expect(lastFetchCall()[0]).toBe("/api/chatbot/threads/thread%201/messages?limit=20"); + }); + it("renames and deletes a thread", async () => { + mockFetchSuccess({}); await patchChatbotThreadById("thread 1", { title: "Physics" }); expect(lastFetchCall()).toMatchObject(["/api/chatbot/threads/thread%201", { method: "PATCH", body: JSON.stringify({ title: "Physics" }) }]); + mockFetch204(); await deleteChatbotThreadById("thread 1"); expect(lastFetchCall()).toMatchObject(["/api/chatbot/threads/thread%201", { method: "DELETE" }]); + }); it("sends a message to its thread", async () => { mockFetchSuccess({ message_id: "answer-1", status: "pending" }); diff --git a/src/api/ai/getBridgeCertificate.ts b/src/api/ai/getBridgeCertificate.ts new file mode 100644 index 0000000..fa3a837 --- /dev/null +++ b/src/api/ai/getBridgeCertificate.ts @@ -0,0 +1,3 @@ +import { client } from "../client"; +export type BridgeCertificate = { protocol: string; certificate_pem: string; fingerprint_sha256: string }; +export function getBridgeCertificate(): Promise { return client("/ai/certificate"); } diff --git a/src/api/ai/index.ts b/src/api/ai/index.ts new file mode 100644 index 0000000..78fd8d1 --- /dev/null +++ b/src/api/ai/index.ts @@ -0,0 +1 @@ +export * from "./getBridgeCertificate"; diff --git a/src/api/chatbot/deleteChatbotThreadById.ts b/src/api/chatbot/deleteChatbotThreadById.ts new file mode 100644 index 0000000..4d5893c --- /dev/null +++ b/src/api/chatbot/deleteChatbotThreadById.ts @@ -0,0 +1,4 @@ +import { client } from "../client"; +export function deleteChatbotThreadById(id: string): Promise { + return client(`/chatbot/threads/${encodeURIComponent(id)}`, { method: "DELETE" }); +} diff --git a/src/api/chatbot/getChatbotThreadMessages.ts b/src/api/chatbot/getChatbotThreadMessages.ts new file mode 100644 index 0000000..a1d6eff --- /dev/null +++ b/src/api/chatbot/getChatbotThreadMessages.ts @@ -0,0 +1,5 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { ChatbotMessage } from "./types"; +export async function getChatbotThreadMessages(threadId: string, params?: PageParams): Promise> { + return normalizePage(await client(`/chatbot/threads/${encodeURIComponent(threadId)}/messages${pageQuery(params)}`)); +} diff --git a/src/api/chatbot/getChatbotThreads.ts b/src/api/chatbot/getChatbotThreads.ts new file mode 100644 index 0000000..c67257d --- /dev/null +++ b/src/api/chatbot/getChatbotThreads.ts @@ -0,0 +1,5 @@ +import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client"; +import type { ChatbotThread } from "./types"; +export async function getChatbotThreads(params?: PageParams): Promise> { + return normalizePage(await client(`/chatbot/threads${pageQuery(params)}`)); +} diff --git a/src/api/chatbot/index.ts b/src/api/chatbot/index.ts index 177c364..33c87a2 100644 --- a/src/api/chatbot/index.ts +++ b/src/api/chatbot/index.ts @@ -1,4 +1,8 @@ export * from "./getChatbotMessageById"; +export * from "./getChatbotThreadMessages"; +export * from "./getChatbotThreads"; +export * from "./patchChatbotThreadById"; +export * from "./deleteChatbotThreadById"; export * from "./postChatbotMessage"; export * from "./postChatbotThread"; export * from "./types"; diff --git a/src/api/chatbot/patchChatbotThreadById.ts b/src/api/chatbot/patchChatbotThreadById.ts new file mode 100644 index 0000000..bbe39f0 --- /dev/null +++ b/src/api/chatbot/patchChatbotThreadById.ts @@ -0,0 +1,5 @@ +import { client } from "../client"; +import type { ChatbotThread, ChatbotThreadBody } from "./types"; +export function patchChatbotThreadById(id: string, body: ChatbotThreadBody): Promise { + return client(`/chatbot/threads/${encodeURIComponent(id)}`, { method: "PATCH", body }); +} diff --git a/src/api/chatbot/postChatbotThread.ts b/src/api/chatbot/postChatbotThread.ts index d17e936..f641882 100644 --- a/src/api/chatbot/postChatbotThread.ts +++ b/src/api/chatbot/postChatbotThread.ts @@ -1,6 +1,6 @@ import { client } from "../client"; -import type { ChatbotThread } from "./types"; +import type { ChatbotThread, ChatbotThreadBody } from "./types"; -export function postChatbotThread(): Promise { - return client("/chatbot/threads", { method: "POST", body: {} }); +export function postChatbotThread(body: ChatbotThreadBody = {}): Promise { + return client("/chatbot/threads", { method: "POST", body }); } diff --git a/src/api/chatbot/types.ts b/src/api/chatbot/types.ts index 1180dea..fc8b59e 100644 --- a/src/api/chatbot/types.ts +++ b/src/api/chatbot/types.ts @@ -7,6 +7,8 @@ export type ChatbotThread = { updated_at: number; }; +export type ChatbotThreadBody = { title?: string | null }; + export type ChatbotMessage = { id: string; thread_id: string; @@ -23,3 +25,8 @@ export type AcceptedChatbotMessage = { message_id: string; status: "pending"; }; + +export type ChatbotStreamEvent = + | { type: "delta"; text: string } + | { type: "done"; message: ChatbotMessage } + | { type: "error"; code: string; message: string }; diff --git a/src/api/client/types.ts b/src/api/client/types.ts index 5fea0d6..294a085 100644 --- a/src/api/client/types.ts +++ b/src/api/client/types.ts @@ -697,12 +697,6 @@ export type MealAttendance = { marked_at: number; }; -export type MealServiceRosterEntry = { - student: PersonRef; - booking: MealBooking | null; - attendance: MealAttendance | null; -}; - export type DietaryProfile = { student: PersonRef; tags: string[]; diff --git a/src/components/layout/celebi-panel.tsx b/src/components/layout/celebi-panel.tsx index 543f0ae..45640ea 100644 --- a/src/components/layout/celebi-panel.tsx +++ b/src/components/layout/celebi-panel.tsx @@ -1,5 +1,5 @@ -import { For, Show, createSignal, onCleanup } from "solid-js"; -import { getChatbotMessageById, postChatbotMessage, postChatbotThread, type ChatbotMessage } from "@/api/chatbot"; +import { For, Show, createEffect, createSignal, onCleanup } from "solid-js"; +import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread, type ChatbotMessage, type ChatbotThread } from "@/api/chatbot"; import { formatApiError } from "@/api/client"; import { CelebiComposer } from "@/components/layout/celebi-composer"; import { CelebiMarkdown } from "@/components/layout/celebi-markdown"; @@ -19,6 +19,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean const [draft, setDraft] = createSignal(""); const [messages, setMessages] = createSignal([]); const [threadId, setThreadId] = createSignal(); + const [threads, setThreads] = createSignal([]); const [sending, setSending] = createSignal(false); const [copiedId, setCopiedId] = createSignal(); @@ -29,11 +30,19 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean }; let pollTimer: number | undefined; + let stream: EventSource | undefined; const stopPolling = () => { if (pollTimer !== undefined) window.clearInterval(pollTimer); pollTimer = undefined; }; + const stopStream = () => { stream?.close(); stream = undefined; }; + const loadThreads = async () => { try { setThreads((await getChatbotThreads({ limit: 100 })).items); } catch { /* history is non-blocking */ } }; + const openThread = async (id: string) => { stopPolling(); stopStream(); setThreadId(id); setMessages((await getChatbotThreadMessages(id, { limit: 500 })).items); }; + const createThread = () => { stopPolling(); stopStream(); setThreadId(undefined); setMessages([]); }; + const renameThread = async (thread: ChatbotThread) => { const title = window.prompt(locale() === "tr" ? "Sohbet başlığı" : "Conversation title", thread.title ?? ""); if (title !== null) { await patchChatbotThreadById(thread.id, { title: title.trim() || null }); await loadThreads(); } }; + const removeThread = async (thread: ChatbotThread) => { if (!window.confirm(locale() === "tr" ? "Bu sohbet silinsin mi?" : "Delete this conversation?")) return; await deleteChatbotThreadById(thread.id); if (threadId() === thread.id) createThread(); await loadThreads(); }; + createEffect(() => { if (props.open) void loadThreads(); }); const failureMessage = (code: string | null) => { if (locale() === "tr") return code ? `Yanıt alınamadı (${code}).` : "Yanıt alınamadı. Lütfen tekrar dene."; @@ -58,7 +67,17 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean pollTimer = window.setInterval(() => void read(), POLL_INTERVAL_MS); }; - onCleanup(stopPolling); + const streamAnswer = (activeThreadId: string, messageId: string) => { + stopStream(); + const source = new EventSource(`/api/chatbot/threads/${encodeURIComponent(activeThreadId)}/messages/${encodeURIComponent(messageId)}/stream`, { withCredentials: true }); + stream = source; + source.addEventListener("delta", (event) => { try { const data = JSON.parse((event as MessageEvent).data) as { text?: unknown }; if (typeof data.text === "string") setMessages((items) => items.map((item) => item.id === messageId ? { ...item, content: item.content + data.text } : item)); } catch { /* ignore malformed chunk */ } }); + source.addEventListener("done", (event) => { try { updateAssistant((JSON.parse((event as MessageEvent).data) as { message: ChatbotMessage }).message); } catch { poll(activeThreadId, messageId); } finally { stopStream(); void loadThreads(); } }); + source.addEventListener("error", () => { stopStream(); poll(activeThreadId, messageId); }); + source.onerror = () => { stopStream(); poll(activeThreadId, messageId); }; + }; + + onCleanup(() => { stopPolling(); stopStream(); }); const send = async (override?: string) => { // A suggestion chip sends its own text without ever touching the draft. @@ -88,7 +107,8 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean completed_at: null, }, ]); - poll(activeThreadId, accepted.message_id); + streamAnswer(activeThreadId, accepted.message_id); + void loadThreads(); } catch (error) { setMessages((items) => [ ...items, @@ -109,6 +129,10 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean return (
+
+ + {(thread) =>
}
+
0}