Spaces:
Running
Running
File size: 16,932 Bytes
9d3e9f6 c9222f5 796777c 4cf9868 c0f8586 796777c 8625087 796777c 4cf9868 796777c 3ad88a4 c9c783c 1c022be c9c783c 1c022be c9c783c 4cf9868 c9c783c 1c022be c9c783c 1c022be c9c783c 4cf9868 c9c783c 43d2f79 c9c783c 39a37e3 3e6d92c 796777c 4cf9868 796777c 3ad88a4 ea8edd8 796777c 3ad88a4 796777c 3ad88a4 4cf9868 3ad88a4 796777c 3ad88a4 ea8edd8 3ad88a4 796777c 3ad88a4 1c022be 3ad88a4 796777c 3ad88a4 796777c 6888bb5 3ad88a4 6888bb5 c0f8586 3ad88a4 6888bb5 3ad88a4 4cf9868 c0f8586 3ad88a4 6888bb5 3ad88a4 6888bb5 3ad88a4 6888bb5 3ad88a4 6888bb5 3ad88a4 402be81 3ad88a4 1c022be 3ad88a4 6888bb5 3ad88a4 6888bb5 3ad88a4 6888bb5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 | // In development: http://localhost:8000
// In production: set VITE_API_URL in Vercel environment variables
export const BASE = import.meta.env.VITE_API_URL || "http://localhost:8000";
/**
* Returns the PostHog distinct ID header if posthog-js is loaded.
*
* Sending this with API requests lets the backend attach server-side events
* (ingest, query, etc.) to the same person as client-side events, so both
* show up under one identity in PostHog funnels and session recordings.
*/
function phHeaders() {
try {
// posthog is loaded globally by the PostHogProvider in main.jsx
const id = window.posthog?.get_distinct_id?.();
if (id) return { "X-POSTHOG-DISTINCT-ID": id };
} catch (_) { /* posthog not yet loaded β degrade silently */ }
return {};
}
export async function fetchAgentModels() {
const res = await fetch(`${BASE}/agent/models`);
if (!res.ok) return [];
const data = await res.json();
return data.models || [];
}
export async function fetchRepos() {
const res = await fetch(`${BASE}/repos`);
if (!res.ok) throw new Error("Failed to fetch repos");
return res.json();
}
// ββ Sessions (Tier 2 β shareable chat URLs) ββββββββββββββββββββββββββββββββββ
// Sessions used to live in localStorage; they're now backed by Qdrant so
// they survive across machines and are linkable via /r/owner/repo/c/:id.
// Each helper is fire-and-await β callers handle errors at the call site
// (typically by falling back to a fresh chat or showing a toast).
export async function fetchSessions(repo) {
const res = await fetch(`${BASE}/sessions?repo=${encodeURIComponent(repo)}`);
if (!res.ok) return [];
const data = await res.json();
return data.sessions || [];
}
export async function fetchSession(sessionId) {
const res = await fetch(`${BASE}/sessions/${encodeURIComponent(sessionId)}`);
if (!res.ok) return null;
return res.json();
}
export async function saveSession(session) {
// Fire-and-forget from the caller's POV β we still await so transient
// network errors surface, but the UI doesn't gate on the response (the
// local state was already updated optimistically before this call).
await fetch(`${BASE}/sessions`, {
method: "POST",
headers: { "Content-Type": "application/json", ...phHeaders() },
body: JSON.stringify(session),
});
}
export async function deleteSession(sessionId) {
await fetch(`${BASE}/sessions/${encodeURIComponent(sessionId)}`, {
method: "DELETE",
});
}
export async function ingestRepo(repoUrl, force = false) {
const res = await fetch(`${BASE}/ingest`, {
method: "POST",
headers: { "Content-Type": "application/json", ...phHeaders() },
body: JSON.stringify({ repo_url: repoUrl, force }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || "Ingestion failed");
return data;
}
export async function fetchTour(slug) {
const [owner, name] = slug.split("/");
const res = await fetch(`${BASE}/repos/${owner}/${name}/tour`);
if (!res.ok) throw new Error("Failed to generate tour");
return res.json(); // { summary, entry_point, concepts: [...] }
}
export async function fetchDiagram(slug, type = "architecture") {
const [owner, name] = slug.split("/");
const res = await fetch(`${BASE}/repos/${owner}/${name}/diagram?type=${type}`);
if (!res.ok) throw new Error("Failed to generate diagram");
return res.json(); // { diagram: "<mermaid syntax>", type } or { error: "..." }
}
/**
* Stream codebase tour generation with live progress events.
*
* Replaces the blank spinner with real progress stages:
* loading β analysing β generating β parsing β done
*
* onProgress({ stage, progress, message }) β called for each intermediate event
* onDone(tourData) β called with the full tour on completion
* onError(msg) β called on failure
*
* Returns a cancel() function.
*/
export function streamTour(slug, { onProgress, onDone, onError, force = false }) {
const [owner, name] = slug.split("/");
const controller = new AbortController();
const url = force
? `${BASE}/repos/${owner}/${name}/tour/stream?force=true`
: `${BASE}/repos/${owner}/${name}/tour/stream`;
fetch(url, { signal: controller.signal, headers: phHeaders() })
.then(async (res) => {
if (!res.ok) { onError?.(`Server error ${res.status}`); return; }
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop();
for (const part of parts) {
if (!part.trim()) continue;
const line = part.split("\n").find(l => l.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6));
if (event.stage === "done") {
const { stage, progress, ...tourData } = event;
onDone?.(tourData);
} else if (event.stage === "error") {
onError?.(event.error || "Failed to generate tour");
} else {
onProgress?.(event);
}
}
}
})
.catch((err) => {
if (err.name !== "AbortError") onError?.(err.message || "Connection lost");
});
return () => controller.abort();
}
/**
* Stream diagram generation with live progress events.
*
* Progress stages: loading β building β enriching β done
*
* onProgress({ stage, progress, message })
* onDone({ diagram, type })
* onError(msg)
*
* Returns a cancel() function.
*/
export function streamDiagram(slug, type = "architecture", { onProgress, onDone, onError, force = false }) {
const [owner, name] = slug.split("/");
const controller = new AbortController();
const url = `${BASE}/repos/${owner}/${name}/diagram/stream?type=${type}${force ? "&force=true" : ""}`;
fetch(url, { signal: controller.signal, headers: phHeaders() })
.then(async (res) => {
if (!res.ok) { onError?.(`Server error ${res.status}`); return; }
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop();
for (const part of parts) {
if (!part.trim()) continue;
const line = part.split("\n").find(l => l.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6));
if (event.stage === "done") {
onDone?.({ diagram: event.diagram, type: event.type });
} else if (event.stage === "error") {
onError?.(event.error || "Failed to generate diagram");
} else {
onProgress?.(event);
}
}
}
})
.catch((err) => {
if (err.name !== "AbortError") onError?.(err.message || "Connection lost");
});
return () => controller.abort();
}
/**
* Stream README generation with live progress events.
*
* onProgress({ stage, progress, message })
* onDone({ content, from_cache })
* onError(msg)
*
* Returns a cancel() function.
*/
export function streamReadme(slug, { onProgress, onDone, onError, force = false }) {
const [owner, name] = slug.split("/");
const controller = new AbortController();
const url = `${BASE}/repos/${owner}/${name}/readme/stream${force ? "?force=true" : ""}`;
fetch(url, { signal: controller.signal, headers: phHeaders() })
.then(async (res) => {
if (!res.ok) { onError?.(`Server error ${res.status}`); return; }
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop();
for (const part of parts) {
if (!part.trim()) continue;
const line = part.split("\n").find(l => l.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6));
if (event.stage === "done") {
onDone?.({ content: event.content, from_cache: event.from_cache });
} else if (event.stage === "error") {
onError?.(event.error || "Failed to generate README");
} else {
onProgress?.(event);
}
}
}
})
.catch((err) => {
if (err.name !== "AbortError") onError?.(err.message || "Connection lost");
});
return () => controller.abort();
}
export async function fetchMcpPrompt(name, args = {}) {
const res = await fetch(
`${BASE}/mcp-prompt?name=${encodeURIComponent(name)}&arguments=${encodeURIComponent(JSON.stringify(args))}`
);
if (!res.ok) throw new Error("Failed to fetch prompt");
return res.json(); // { name, text }
}
export async function fetchMcpStatus() {
const res = await fetch(`${BASE}/mcp-status`);
if (!res.ok) throw new Error("Failed to fetch MCP status");
return res.json();
}
export async function deleteRepo(slug) {
const [owner, name] = slug.split("/");
const res = await fetch(`${BASE}/repos/${owner}/${name}`, { method: "DELETE", headers: phHeaders() });
if (!res.ok) throw new Error("Failed to delete repo");
return res.json();
}
/**
* Low-level POST SSE helper.
*
* EventSource only supports GET, so we can't send a request body (e.g. history).
* Instead we use fetch() with a ReadableStream response and parse the SSE format
* manually. The returned cancel() function aborts the in-flight request.
*
* SSE wire format (per spec):
* event: <type>\ndata: <json>\n\n β named event
* data: <text>\n\n β default event
*/
async function postSSE(path, body, handlers) {
const controller = new AbortController();
try {
const res = await fetch(`${BASE}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: controller.signal,
});
if (!res.ok) {
handlers.onError?.(`Server error ${res.status}`);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// SSE events are separated by blank lines (\n\n)
const parts = buffer.split("\n\n");
buffer = parts.pop(); // keep any incomplete trailing chunk
for (const part of parts) {
if (!part.trim()) continue;
let eventType = "message";
let data = "";
for (const line of part.split("\n")) {
if (line.startsWith("event: ")) eventType = line.slice(7).trim();
else if (line.startsWith("data: ")) data = line.slice(6);
}
if (data) handlers[eventType]?.(data);
}
}
} catch (err) {
if (err.name !== "AbortError") handlers.onError?.(err.message || "Connection lost");
}
return () => controller.abort();
}
/**
* Stream a query response via SSE (POST so we can send conversation history).
*
* The server sends two event types:
* event: meta β JSON with { sources, query_type } (arrives before tokens)
* (default) β token text, or "[DONE]" to signal completion
*/
export function streamQuery({ question, repo, mode, history, onToken, onSources, onGrade, onDone, onError }) {
const controller = new AbortController();
fetch(`${BASE}/query/stream`, {
method: "POST",
headers: { "Content-Type": "application/json", ...phHeaders() },
body: JSON.stringify({
question,
mode: mode || "hybrid",
top_k: 6,
repo: repo || null,
history: history || [],
}),
signal: controller.signal,
}).then(async (res) => {
if (!res.ok) { onError(`Server error ${res.status}`); return; }
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop();
for (const part of parts) {
if (!part.trim()) continue;
let eventType = "message";
let data = "";
for (const line of part.split("\n")) {
if (line.startsWith("event: ")) eventType = line.slice(7).trim();
else if (line.startsWith("data: ")) data = line.slice(6);
}
if (!data) continue;
if (eventType === "meta") {
const { sources, query_type, pipeline, model } = JSON.parse(data);
onSources(sources || [], query_type || "technical", pipeline || {}, model || "");
} else if (eventType === "grade") {
onGrade?.(JSON.parse(data));
} else {
// default event: token or [DONE]
if (data === "[DONE]") { onDone(); return; }
onToken(data.replace(/\\n/g, "\n"));
}
}
}
}).catch((err) => {
if (err.name !== "AbortError") onError(err.message || "Connection lost");
});
return () => controller.abort();
}
/**
* Stream the agentic RAG loop via SSE (POST so we can send conversation history).
*
* Unlike streamQuery (one retrieval β tokens), this endpoint shows the
* agent's full ReAct reasoning loop in real time:
*
* 1. agent decides to search β event: tool_call
* 2. result comes back β event: tool_result
* 3. agent decides to search again (or answer)
* 4. when done, answer streams token-by-token (default events)
* 5. event: done signals completion with iteration count
*
* Callbacks:
* onToolCall(tool, input) β agent is calling a tool
* onToolResult(tool, output) β tool returned a result
* onToken(text) β token of the final answer
* onDone(iterations) β agent finished
* onError(msg) β connection or server error
*/
export function streamAgentQuery({ question, repo, model_id, history, onThought, onToolCall, onToolResult, onToken, onSources, onDone, onError }) {
const controller = new AbortController();
fetch(`${BASE}/agent/stream`, {
method: "POST",
headers: { "Content-Type": "application/json", ...phHeaders() },
body: JSON.stringify({ question, repo: repo || null, model_id: model_id || null, history: history || [] }),
signal: controller.signal,
}).then(async (res) => {
if (!res.ok) { onError?.(`Server error ${res.status}`); return; }
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop();
for (const part of parts) {
if (!part.trim()) continue;
let eventType = "message";
let data = "";
for (const line of part.split("\n")) {
if (line.startsWith("event: ")) eventType = line.slice(7).trim();
else if (line.startsWith("data: ")) data = line.slice(6);
}
if (!data) continue;
if (eventType === "thought") {
const { text } = JSON.parse(data);
onThought?.(text);
} else if (eventType === "tool_call") {
const { tool, input } = JSON.parse(data);
onToolCall?.(tool, input);
} else if (eventType === "tool_result") {
const { tool, output } = JSON.parse(data);
onToolResult?.(tool, output);
} else if (eventType === "sources") {
const { sources } = JSON.parse(data);
onSources?.(sources || []);
} else if (eventType === "done") {
const { iterations, model } = JSON.parse(data);
onDone?.(iterations, model);
} else if (eventType === "agent_error") {
const { message } = JSON.parse(data);
onError?.(message);
return;
} else {
// default: token or [DONE]
if (data === "[DONE]") return;
onToken?.(data.replace(/\\n/g, "\n"));
}
}
}
}).catch((err) => {
if (err.name !== "AbortError") onError?.("Could not connect to the agent. Is the backend running?");
});
return () => controller.abort();
}
|