feat(chat): implement WebSocket chat client with useChatSocket hook

Replace the stubbed chat API with a real WebSocket hook that
connects to /ws/chat and supports DM creation, messaging,
session join/leave, and history retrieval. Keep REST stub
functions for backward compatibility with existing pages
that require listChatSessions/getChatSessionById imports.
This commit is contained in:
zetaloop
2026-05-01 04:25:56 +08:00
parent 1f20198f23
commit a3f0b49112
8 changed files with 426 additions and 215 deletions
+26
View File
@@ -12,6 +12,29 @@ function getCookieValue(name: string): string | null {
return null
}
let csrfReady: Promise<void> | null = null
async function prepareCsrf() {
if (getCookieValue("__Host-XSRF-TOKEN") && getCookieValue("__Host-XSRF-GUARD")) return
csrfReady ??= fetch("/healthz", {
cache: "no-store",
credentials: "include",
})
.then(() => {})
.finally(() => {
csrfReady = null
})
await csrfReady
if (!getCookieValue("__Host-XSRF-TOKEN")) {
await fetch("/api/v1/games?offset=0&limit=1", {
cache: "no-store",
credentials: "include",
})
}
}
async function readJsonBody(res: Response): Promise<{ json: unknown | null; text: string }> {
const text = await res.text()
if (!text) return { json: null, text: "" }
@@ -70,6 +93,8 @@ export async function uploadFile(file: File, type: UploadFileType): Promise<stri
formData.set("type", type)
formData.set("file", file)
await prepareCsrf()
const headers = new Headers()
const xsrfToken = getCookieValue("__Host-XSRF-TOKEN")
if (xsrfToken) headers.set("XSRF-TOKEN", xsrfToken)
@@ -78,6 +103,7 @@ export async function uploadFile(file: File, type: UploadFileType): Promise<stri
method: "POST",
headers,
body: formData,
credentials: "include",
})
const { json, text } = await readJsonBody(res)