import type { SessionEntry } from "./types"; export async function sendChat(threadId: string | null, message: string): Promise<{ threadId: string; response: string }> { const r = await fetch("/code/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ threadId, message }), signal: AbortSignal.timeout(300000), }); if (!r.ok) { const err = await r.json().catch(() => ({ error: "HTTP " + r.status })); throw new Error(err.error); } return r.json(); } export async function sendChatStream( threadId: string | null, message: string, onText: (chunk: string) => void, opts?: { title?: string }, ): Promise<{ threadId: string }> { const r = await fetch("/code/api/chat-stream", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ threadId, message, title: opts?.title }), }); if (!r.ok) { const err = await r.json().catch(() => ({ error: "HTTP " + r.status })); throw new Error(err.error); } const reader = r.body!.getReader(); const decoder = new TextDecoder(); let buffer = ""; let returnedTid = threadId || ""; let eventType = ""; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split("\n"); buffer = lines.pop()!; for (const line of lines) { if (line.startsWith("event: ")) { eventType = line.slice(7); } else if (line.startsWith("data: ")) { const data = JSON.parse(line.slice(6)); if (eventType === "thread") returnedTid = data.threadId; else if (eventType === "text") onText(data.text); else if (eventType === "error") throw new Error(data.error); eventType = ""; } } } return { threadId: returnedTid }; } export async function fetchSessionLog(sessionFile: string, n = 30): Promise { const r = await fetch(`/code/api/session-tails?file=${encodeURIComponent(sessionFile)}&n=${n}&t=${Date.now()}`); if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); } export async function attachThread(threadId: string, linearIssue: string): Promise { await fetch("/code/api/attach-thread", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ threadId, linearIssue }), }); } export async function deleteThread(channel: string, threadId: string): Promise { await fetch("/code/api/delete-thread", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ channel, threadId }), }); } export async function updateThreadStatus(channel: string, threadId: string, status: string): Promise { await fetch("/code/api/update-thread", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ channel, threadId, status }), }); }