forge
Explore
Log in

Don't you dare go Hollow

🧵 chatbot thread history, rename/delete, and SSE streaming

Browse files at this commit

796c6d9a56c8cf18b9f779d6234399f976c37d24Burak BoduroğluParent: 38703d4
  • feat
    • 🧵 chatbot thread history, rename/delete, and SSE streaming
Show full message
feat: 🧵 chatbot thread history, rename/delete, and SSE streaming
- thread endpoints: list threads, list a thread's messages, PATCH title,
  DELETE thread; postChatbotThread accepts an optional title body
- celebi-panel: conversation switcher bar (new/open/rename/delete) and
  EventSource streaming with delta accumulation and polling fallback
- ai bridge certificate endpoint (getBridgeCertificate) with tests
src/api/__tests__/ai/ai.test.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { afterEach, describe, expect, it, vi } from "vitest";
2+import { getBridgeCertificate } from "../../ai";
3+import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch";
4+describe("ai API", () => {
5+ afterEach(() => vi.restoreAllMocks());
6+ it("gets the bridge certificate", async () => {
7+ mockFetchSuccess({ protocol: "hab/1", certificate_pem: "pem", fingerprint_sha256: "hash" });
8+ await getBridgeCertificate();
9+ expect(lastFetchCall()[0]).toBe("/api/ai/certificate");
10+ });
11+});
src/api/__tests__/chatbot/chatbot.test.tsmodified+10 -2
@@ -1,6 +1,6 @@
1 import { afterEach, describe, expect, it, vi } from "vitest";1 import { afterEach, describe, expect, it, vi } from "vitest";
2-import { getChatbotMessageById, postChatbotMessage, postChatbotThread } from "../../chatbot";2+import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread } from "../../chatbot";
3-import { lastFetchCall, mockFetchSuccess } from "../helpers/mock-fetch";3+import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
4 4
5 describe("chatbot API", () => {5 describe("chatbot API", () => {
6 afterEach(() => vi.restoreAllMocks());6 afterEach(() => vi.restoreAllMocks());
@@ -13,6 +13,14 @@ describe("chatbot API", () => {
13 expect(init?.method).toBe("POST");13 expect(init?.method).toBe("POST");
14 expect(init?.body).toBe("{}");14 expect(init?.body).toBe("{}");
15 });15 });
16+ it("lists threads and a selected thread's messages", async () => {
17+ mockFetchSuccess({ items: [], total: 0 }); await getChatbotThreads({ limit: 20 }); expect(lastFetchCall()[0]).toBe("/api/chatbot/threads?limit=20");
18+ mockFetchSuccess({ items: [], total: 0 }); await getChatbotThreadMessages("thread 1", { limit: 20 }); expect(lastFetchCall()[0]).toBe("/api/chatbot/threads/thread%201/messages?limit=20");
19+ });
20+ it("renames and deletes a thread", async () => {
21+ mockFetchSuccess({}); await patchChatbotThreadById("thread 1", { title: "Physics" }); expect(lastFetchCall()).toMatchObject(["/api/chatbot/threads/thread%201", { method: "PATCH", body: JSON.stringify({ title: "Physics" }) }]);
22+ mockFetch204(); await deleteChatbotThreadById("thread 1"); expect(lastFetchCall()).toMatchObject(["/api/chatbot/threads/thread%201", { method: "DELETE" }]);
23+ });
16 24
17 it("sends a message to its thread", async () => {25 it("sends a message to its thread", async () => {
18 mockFetchSuccess({ message_id: "answer-1", status: "pending" });26 mockFetchSuccess({ message_id: "answer-1", status: "pending" });
src/api/ai/getBridgeCertificate.tsadded+3 -0
@@ -0,0 +1,3 @@
1+import { client } from "../client";
2+export type BridgeCertificate = { protocol: string; certificate_pem: string; fingerprint_sha256: string };
3+export function getBridgeCertificate(): Promise<BridgeCertificate> { return client<BridgeCertificate>("/ai/certificate"); }
src/api/ai/index.tsadded+1 -0
@@ -0,0 +1 @@
1+export * from "./getBridgeCertificate";
src/api/chatbot/deleteChatbotThreadById.tsadded+4 -0
@@ -0,0 +1,4 @@
1+import { client } from "../client";
2+export function deleteChatbotThreadById(id: string): Promise<void> {
3+ return client<void>(`/chatbot/threads/${encodeURIComponent(id)}`, { method: "DELETE" });
4+}
src/api/chatbot/getChatbotThreadMessages.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client";
2+import type { ChatbotMessage } from "./types";
3+export async function getChatbotThreadMessages(threadId: string, params?: PageParams): Promise<Page<ChatbotMessage>> {
4+ return normalizePage<ChatbotMessage>(await client<unknown>(`/chatbot/threads/${encodeURIComponent(threadId)}/messages${pageQuery(params)}`));
5+}
src/api/chatbot/getChatbotThreads.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client, normalizePage, pageQuery, type Page, type PageParams } from "../client";
2+import type { ChatbotThread } from "./types";
3+export async function getChatbotThreads(params?: PageParams): Promise<Page<ChatbotThread>> {
4+ return normalizePage<ChatbotThread>(await client<unknown>(`/chatbot/threads${pageQuery(params)}`));
5+}
src/api/chatbot/index.tsmodified+4 -0
@@ -1,4 +1,8 @@
1 export * from "./getChatbotMessageById";1 export * from "./getChatbotMessageById";
2+export * from "./getChatbotThreadMessages";
3+export * from "./getChatbotThreads";
4+export * from "./patchChatbotThreadById";
5+export * from "./deleteChatbotThreadById";
2 export * from "./postChatbotMessage";6 export * from "./postChatbotMessage";
3 export * from "./postChatbotThread";7 export * from "./postChatbotThread";
4 export * from "./types";8 export * from "./types";
src/api/chatbot/patchChatbotThreadById.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "../client";
2+import type { ChatbotThread, ChatbotThreadBody } from "./types";
3+export function patchChatbotThreadById(id: string, body: ChatbotThreadBody): Promise<ChatbotThread> {
4+ return client<ChatbotThread>(`/chatbot/threads/${encodeURIComponent(id)}`, { method: "PATCH", body });
5+}
src/api/chatbot/postChatbotThread.tsmodified+3 -3
@@ -1,6 +1,6 @@
1 import { client } from "../client";1 import { client } from "../client";
2-import type { ChatbotThread } from "./types";2+import type { ChatbotThread, ChatbotThreadBody } from "./types";
3 3
4-export function postChatbotThread(): Promise<ChatbotThread> {4+export function postChatbotThread(body: ChatbotThreadBody = {}): Promise<ChatbotThread> {
5- return client<ChatbotThread>("/chatbot/threads", { method: "POST", body: {} });5+ return client<ChatbotThread>("/chatbot/threads", { method: "POST", body });
6 }6 }
src/api/chatbot/types.tsmodified+7 -0
@@ -7,6 +7,8 @@ export type ChatbotThread = {
7 updated_at: number;7 updated_at: number;
8 };8 };
9 9
10+export type ChatbotThreadBody = { title?: string | null };
11+
10 export type ChatbotMessage = {12 export type ChatbotMessage = {
11 id: string;13 id: string;
12 thread_id: string;14 thread_id: string;
@@ -23,3 +25,8 @@ export type AcceptedChatbotMessage = {
23 message_id: string;25 message_id: string;
24 status: "pending";26 status: "pending";
25 };27 };
28+
29+export type ChatbotStreamEvent =
30+ | { type: "delta"; text: string }
31+ | { type: "done"; message: ChatbotMessage }
32+ | { type: "error"; code: string; message: string };
src/api/client/types.tsmodified+0 -6
@@ -697,12 +697,6 @@ export type MealAttendance = {
697 marked_at: number;697 marked_at: number;
698 };698 };
699 699
700-export type MealServiceRosterEntry = {
701- student: PersonRef;
702- booking: MealBooking | null;
703- attendance: MealAttendance | null;
704-};
705-
706 export type DietaryProfile = {700 export type DietaryProfile = {
707 student: PersonRef;701 student: PersonRef;
708 tags: string[];702 tags: string[];
src/components/layout/celebi-panel.tsxmodified+28 -4
@@ -1,5 +1,5 @@
1-import { For, Show, createSignal, onCleanup } from "solid-js";1+import { For, Show, createEffect, createSignal, onCleanup } from "solid-js";
2-import { getChatbotMessageById, postChatbotMessage, postChatbotThread, type ChatbotMessage } from "@/api/chatbot";2+import { deleteChatbotThreadById, getChatbotMessageById, getChatbotThreadMessages, getChatbotThreads, patchChatbotThreadById, postChatbotMessage, postChatbotThread, type ChatbotMessage, type ChatbotThread } from "@/api/chatbot";
3 import { formatApiError } from "@/api/client";3 import { formatApiError } from "@/api/client";
4 import { CelebiComposer } from "@/components/layout/celebi-composer";4 import { CelebiComposer } from "@/components/layout/celebi-composer";
5 import { CelebiMarkdown } from "@/components/layout/celebi-markdown";5 import { CelebiMarkdown } from "@/components/layout/celebi-markdown";
@@ -19,6 +19,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean
19 const [draft, setDraft] = createSignal("");19 const [draft, setDraft] = createSignal("");
20 const [messages, setMessages] = createSignal<PanelMessage[]>([]);20 const [messages, setMessages] = createSignal<PanelMessage[]>([]);
21 const [threadId, setThreadId] = createSignal<string>();21 const [threadId, setThreadId] = createSignal<string>();
22+ const [threads, setThreads] = createSignal<ChatbotThread[]>([]);
22 const [sending, setSending] = createSignal(false);23 const [sending, setSending] = createSignal(false);
23 const [copiedId, setCopiedId] = createSignal<string>();24 const [copiedId, setCopiedId] = createSignal<string>();
24 25
@@ -29,11 +30,19 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean
29 };30 };
30 31
31 let pollTimer: number | undefined;32 let pollTimer: number | undefined;
33+ let stream: EventSource | undefined;
32 34
33 const stopPolling = () => {35 const stopPolling = () => {
34 if (pollTimer !== undefined) window.clearInterval(pollTimer);36 if (pollTimer !== undefined) window.clearInterval(pollTimer);
35 pollTimer = undefined;37 pollTimer = undefined;
36 };38 };
39+ const stopStream = () => { stream?.close(); stream = undefined; };
40+ const loadThreads = async () => { try { setThreads((await getChatbotThreads({ limit: 100 })).items); } catch { /* history is non-blocking */ } };
41+ const openThread = async (id: string) => { stopPolling(); stopStream(); setThreadId(id); setMessages((await getChatbotThreadMessages(id, { limit: 500 })).items); };
42+ const createThread = () => { stopPolling(); stopStream(); setThreadId(undefined); setMessages([]); };
43+ 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(); } };
44+ 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(); };
45+ createEffect(() => { if (props.open) void loadThreads(); });
37 46
38 const failureMessage = (code: string | null) => {47 const failureMessage = (code: string | null) => {
39 if (locale() === "tr") return code ? `Yanıt alınamadı (${code}).` : "Yanıt alınamadı. Lütfen tekrar dene.";48 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
58 pollTimer = window.setInterval(() => void read(), POLL_INTERVAL_MS);67 pollTimer = window.setInterval(() => void read(), POLL_INTERVAL_MS);
59 };68 };
60 69
61- onCleanup(stopPolling);70+ const streamAnswer = (activeThreadId: string, messageId: string) => {
71+ stopStream();
72+ const source = new EventSource(`/api/chatbot/threads/${encodeURIComponent(activeThreadId)}/messages/${encodeURIComponent(messageId)}/stream`, { withCredentials: true });
73+ stream = source;
74+ 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 */ } });
75+ source.addEventListener("done", (event) => { try { updateAssistant((JSON.parse((event as MessageEvent).data) as { message: ChatbotMessage }).message); } catch { poll(activeThreadId, messageId); } finally { stopStream(); void loadThreads(); } });
76+ source.addEventListener("error", () => { stopStream(); poll(activeThreadId, messageId); });
77+ source.onerror = () => { stopStream(); poll(activeThreadId, messageId); };
78+ };
79+
80+ onCleanup(() => { stopPolling(); stopStream(); });
62 81
63 const send = async (override?: string) => {82 const send = async (override?: string) => {
64 // A suggestion chip sends its own text without ever touching the draft.83 // 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
88 completed_at: null,107 completed_at: null,
89 },108 },
90 ]);109 ]);
91- poll(activeThreadId, accepted.message_id);110+ streamAnswer(activeThreadId, accepted.message_id);
111+ void loadThreads();
92 } catch (error) {112 } catch (error) {
93 setMessages((items) => [113 setMessages((items) => [
94 ...items,114 ...items,
@@ -109,6 +129,10 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean
109 return (129 return (
110 <SidePanel open={props.open} onOpenChange={props.onOpenChange} title={t("ai.title")} description={t("ai.description")}>130 <SidePanel open={props.open} onOpenChange={props.onOpenChange} title={t("ai.title")} description={t("ai.description")}>
111 <div class="flex h-full min-h-0 flex-col">131 <div class="flex h-full min-h-0 flex-col">
132+ <div class="mb-3 flex shrink-0 gap-2 overflow-x-auto border-b border-border pb-3">
133+ <button type="button" class="rounded-lg border px-2.5 py-1.5 text-xs font-medium" onClick={createThread}>{locale() === "tr" ? "Yeni sohbet" : "New chat"}</button>
134+ <For each={threads()}>{(thread) => <div class="flex shrink-0 overflow-hidden rounded-lg border"><button type="button" class={thread.id === threadId() ? "bg-muted px-2.5 py-1.5 text-xs font-medium" : "px-2.5 py-1.5 text-xs"} onClick={() => void openThread(thread.id)}>{thread.title || (locale() === "tr" ? "Adsız sohbet" : "Untitled chat")}</button><button type="button" class="border-l px-2 text-xs" aria-label={locale() === "tr" ? "Sohbeti yeniden adlandır" : "Rename chat"} onClick={() => void renameThread(thread)}>✎</button><button type="button" class="border-l px-2 text-xs text-destructive" aria-label={locale() === "tr" ? "Sohbeti sil" : "Delete chat"} onClick={() => void removeThread(thread)}>×</button></div>}</For>
135+ </div>
112 <div class="min-h-0 flex-1 overflow-y-auto pr-1">136 <div class="min-h-0 flex-1 overflow-y-auto pr-1">
113 <Show137 <Show
114 when={messages().length > 0}138 when={messages().length > 0}