added cors support and started chat client

This commit is contained in:
Storme-bit
2026-04-06 03:25:25 -07:00
parent 461438e81b
commit 1e2ce7a761
16 changed files with 2610 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
const BASE_URL = import.meta.env.VITE_ORCHESTRATION_URL ?? '';
// ── Sessions ────────────────────────────────────────────────
export async function fetchSessions(limit = 20, offset = 0) {
const res = await fetch(`${BASE_URL}/sessions?limit=${limit}&offset=${offset}`);
if (!res.ok) throw new Error(`Failed to fetch sessions: ${res.status}`);
return res.json();
}
export async function fetchSessionHistory(sessionId, limit = 50, offset = 0) {
const res = await fetch(`${BASE_URL}/sessions/${sessionId}/history?limit=${limit}&offset=${offset}`);
if (!res.ok) throw new Error(`Failed to fetch history: ${res.status}`);
return res.json();
}
// ── Chat ────────────────────────────────────────────────────
export async function sendMessage(sessionId, message, model) {
const res = await fetch(`${BASE_URL}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, message, model }),
});
if (!res.ok) throw new Error(`Chat request failed: ${res.status}`);
return res.json();
}
// onChunk(text) called for each token
// onDone({ model, tokenCount }) called when stream closes
// returns an abort function — call it to cancel mid-stream
export function streamMessage(sessionId, message, model, { onChunk, onDone, onError }) {
const controller = new AbortController();
(async () => {
try {
const res = await fetch(`${BASE_URL}/chat/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, message, model }),
signal: controller.signal,
});
if (!res.ok) throw new Error(`Stream request failed: ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
// Append to buffer and split on double newline (SSE event delimiter)
buffer += decoder.decode(value, { stream: true });
const events = buffer.split('\n\n');
buffer = events.pop(); // last item may be incomplete — keep in buffer
for (const event of events) {
const line = event.trim();
if (!line.startsWith('data: ')) continue;
const raw = line.slice(6);
try {
const data = JSON.parse(raw);
if (data.text) onChunk(data.text);
if (data.done) onDone({ model, tokenCount: data.tokenCount ?? 0 });
if (data.error) onError(new Error(data.error));
} catch {
// malformed JSON — skip
}
}
}
} catch (err) {
if (err.name !== 'AbortError') onError(err);
}
})();
return () => controller.abort();
}