refactor(web): consolidate routing and expose auth handler

- Add `*.log` to `.gitignore` to exclude log files from version control.
- Change `auth_handler` to `pub` in `src/auth/mod.rs` to make the endpoint publicly accessible.
- Remove unused `bot_index` import and route; replace direct service registration with `web_server::configure_app` in `src/main.rs`.
- Refactor `src/web_server/mod.rs`:
  - Remove the `bot_index` handler.
  - Introduce `serve_html` helper for loading HTML pages.
  - Simplify static file serving by configuring separate routes for JS and CSS assets.
  - Centralize all route and static file configuration in `configure_app`.
- Clean up related imports and improve error handling for missing pages.
This commit is contained in:
Rodrigo Rodriguez (Pragmatismo) 2025-11-17 10:00:12 -03:00
parent 737f934d68
commit f9a1e3a8c0
7 changed files with 772 additions and 774 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
*.log
target*
.env
*.env

View file

@ -11,7 +11,7 @@ impl AuthService {
}
}
#[actix_web::get("/api/auth")]
async fn auth_handler(
pub async fn auth_handler(
_req: HttpRequest,
data: web::Data<AppState>,
web::Query(params): web::Query<HashMap<String, String>>,

View file

@ -46,7 +46,6 @@ use crate::session::{create_session, get_session_history, get_sessions, start_se
use crate::shared::state::AppState;
use crate::shared::utils::create_conn;
use crate::shared::utils::create_s3_operator;
use crate::web_server::{bot_index};
#[derive(Debug, Clone)]
pub enum BootstrapProgress {
StartingBootstrap,
@ -306,7 +305,6 @@ async fn main() -> std::io::Result<()> {
.wrap(Logger::default())
.wrap(Logger::new("HTTP REQUEST: %a %{User-Agent}i"))
.app_data(web::Data::from(app_state_clone))
.configure(web_server::configure_app)
.service(auth_handler)
.service(create_session)
.service(get_session_history)
@ -332,7 +330,8 @@ async fn main() -> std::io::Result<()> {
.service(save_draft)
.service(save_click);
}
app = app.service(bot_index);
app = app.configure(web_server::configure_app);
app
})
.workers(worker_count)

View file

@ -14,15 +14,12 @@ async fn index() -> Result<HttpResponse> {
}
}
#[actix_web::get("/{botname}")]
async fn bot_index(req: HttpRequest) -> Result<HttpResponse> {
let botname = req.match_info().query("botname");
debug!("Serving bot interface for: {}", botname);
match fs::read_to_string("web/desktop/index.html") {
async fn serve_html(path: &str) -> Result<HttpResponse> {
match fs::read_to_string(format!("web/desktop/{}", path)) {
Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)),
Err(e) => {
error!("Failed to load index page for bot {}: {}", botname, e);
Ok(HttpResponse::InternalServerError().body("Failed to load index page"))
error!("Failed to load page {}: {}", path, e);
Ok(HttpResponse::InternalServerError().body("Failed to load page"))
}
}
}
@ -30,16 +27,6 @@ async fn bot_index(req: HttpRequest) -> Result<HttpResponse> {
pub fn configure_app(cfg: &mut actix_web::web::ServiceConfig) {
let static_path = Path::new("./web/desktop");
// Serve all static files from desktop directory
cfg.service(
Files::new("/", static_path)
.index_file("index.html")
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true)
.show_files_listing()
);
// Serve all JS files
cfg.service(
Files::new("/js", static_path.join("js"))
@ -48,17 +35,42 @@ pub fn configure_app(cfg: &mut actix_web::web::ServiceConfig) {
.use_etag(true)
);
// Serve all component directories
["drive", "tasks", "mail"].iter().for_each(|dir| {
// Serve CSS files
cfg.service(
Files::new(&format!("/{}", dir), static_path.join(dir))
Files::new("/css", static_path.join("css"))
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true)
);
});
// Serve index routes
cfg.service(
Files::new("/drive", static_path.join("drive"))
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true)
);
cfg.service(
Files::new("/chat", static_path.join("chat"))
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true)
);
cfg.service(
Files::new("/mail", static_path.join("mail"))
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true)
);
cfg.service(
Files::new("/tasks", static_path.join("tasks"))
.prefer_utf8(true)
.use_last_modified(true)
.use_etag(true)
);
cfg.service(index);
cfg.service(bot_index);
}

View file

@ -1,101 +1,7 @@
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8"/>
<title>General Bots Chat</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="chat.css">
</head>
<body>
<div class="connection-status connecting" id="connectionStatus"></div>
<div class="flash-overlay" id="flashOverlay"></div>
<div class="float-menu">
<div class="float-logo" id="floatLogo" title="Menu"></div>
<div class="menu-button" id="themeBtn" title="Theme"></div>
</div>
<div class="sidebar" id="sidebar">
<div class="sidebar-header">
<div class="sidebar-logo"></div>
<div class="sidebar-title" id="sidebarTitle">General Bots Chat</div>
</div>
<button class="sidebar-button" id="voiceToggle" onclick="toggleVoiceMode()">🎤 Voice Mode</button>
<div class="history-section">
<div class="history-title">History</div>
<div id="history"></div>
</div>
</div>
<!-- Chat layout analogous to Drive layout -->
<div class="chat-layout" x-data="chatApp()" x-cloak>
<div class="panel chat-sidebar">
<div style="padding: 1rem; border-bottom: 1px solid #334155;">
<h3>General Bots Chat</h3>
</div>
<template x-for="item in navItems" :key="item.name">
<div class="nav-item"
:class="{ active: current === item.name }"
@click="current = item.name">
<span x-text="item.icon"></span>
<span x-text="item.name"></span>
</div>
</template>
</div>
<div class="panel chat-main">
<div style="padding: 1rem; border-bottom: 1px solid #334155;">
<h2 x-text="current"></h2>
<input type="text" x-model="search" placeholder="Search chats..."
style="width: 100%; margin-top: 0.5rem; padding: 0.5rem; background: #0f172a; border: 1px solid #334155; border-radius: 0.375rem; color: #e2e8f0;">
</div>
<div class="chat-list">
<template x-for="chat in filteredChats" :key="chat.id">
<div class="chat-item"
:class="{ selected: selectedChat?.id === chat.id }"
@click="selectedChat = chat">
<span class="chat-icon" x-text="chat.icon"></span>
<div style="flex: 1;">
<div style="font-weight: 600;" x-text="chat.name"></div>
<div class="text-xs text-gray" x-text="chat.lastMessage"></div>
</div>
<div class="text-sm text-gray" x-text="chat.time"></div>
</div>
</template>
</div>
</div>
<div class="panel chat-details">
<template x-if="selectedChat">
<div style="padding: 2rem;">
<div style="text-align: center; margin-bottom: 2rem;">
<div style="font-size: 4rem; margin-bottom: 1rem;" x-text="selectedChat.icon"></div>
<h3 x-text="selectedChat.name"></h3>
<p class="text-sm text-gray" x-text="selectedChat.status"></p>
</div>
<div style="margin-bottom: 1rem;">
<div class="text-sm" style="margin-bottom: 0.5rem;">Last Message</div>
<div class="text-gray" x-text="selectedChat.lastMessage"></div>
</div>
<div style="margin-bottom: 1rem;">
<div class="text-sm" style="margin-bottom: 0.5rem;">Time</div>
<div class="text-gray" x-text="selectedChat.time"></div>
</div>
<div style="display: flex; gap: 0.5rem; margin-top: 2rem;">
<button style="flex: 1; padding: 0.75rem; background: #3b82f6; color: white; border: none; border-radius: 0.375rem; cursor: pointer;">Reply</button>
<button style="flex: 1; padding: 0.75rem; background: #10b981; color: white; border: none; border-radius: 0.375rem; cursor: pointer;">Close</button>
</div>
</div>
</template>
<template x-if="!selectedChat">
<div style="padding: 2rem; text-align: center; color: #64748b;">
<div style="font-size: 4rem; margin-bottom: 1rem;">💬</div>
<p>Select a chat to view details</p>
</div>
</template>
</div>
</div>
<div id="connectionStatus" class="connection-status disconnected"></div>
<main id="messages"></main>
<footer>
<div class="suggestions-container" id="suggestions"></div>
@ -105,7 +11,13 @@
<button id="sendBtn" title="Send"></button>
</div>
</footer>
<button class="scroll-to-bottom" id="scrollToBottom"></button>
<div class="context-indicator" id="contextIndicator">
<div>Context</div>
<div id="contextPercentage">0%</div>
<div class="context-progress">
<div class="context-progress-bar" id="contextProgressBar" style="width:0%"></div>
</div>
</div>
<script src="chat.js"></script>
</body>
</html>
</div>

View file

@ -1,19 +1,51 @@
function chatApp() {
// Core state variables (shared via closure)
let ws = null,
currentSessionId = null,
currentUserId = null,
currentBotId = "default_bot",
isStreaming = false,
voiceRoom = null,
isVoiceMode = false,
mediaRecorder = null,
audioChunks = [],
streamingMessageId = null,
isThinking = false,
currentStreamingContent = "",
hasReceivedInitialMessage = false,
reconnectAttempts = 0,
reconnectTimeout = null,
thinkingTimeout = null,
currentTheme = 'auto',
themeColor1 = null,
themeColor2 = null,
customLogoUrl = null,
contextUsage = 0,
isUserScrolling = false,
autoScrollEnabled = true,
isContextChange = false;
const maxReconnectAttempts = 5;
// DOM references (cached for performance)
let messagesDiv, input, sendBtn, voiceBtn, connectionStatus, flashOverlay, suggestionsContainer, floatLogo, sidebar, themeBtn, scrollToBottomBtn, contextIndicator, contextPercentage, contextProgressBar, sidebarTitle;
marked.setOptions({ breaks: true, gfm: true });
return {
// Current navigation section (e.g., All Chats, Direct, Group)
// ----------------------------------------------------------------------
// UI state (mirrors the structure used in driveApp)
// ----------------------------------------------------------------------
current: 'All Chats',
// Search term for filtering chats
search: '',
// Currently selected chat object
selectedChat: null,
// Navigation items similar to the Drive UI
navItems: [
{ name: 'All Chats', icon: '💬' },
{ name: 'Direct', icon: '👤' },
{ name: 'Groups', icon: '👥' },
{ name: 'Archived', icon: '🗄' }
],
// Sample chat list in a real app this would be fetched from a server
chats: [
{ id: 1, name: 'General Bot Support', icon: '🤖', lastMessage: 'How can I help you?', time: '10:15 AM', status: 'Online' },
{ id: 2, name: 'Project Alpha', icon: '🚀', lastMessage: 'Launch scheduled for tomorrow.', time: 'Yesterday', status: 'Active' },
@ -21,44 +53,31 @@ function chatApp() {
{ id: 4, name: 'Random Chat', icon: '🎲', lastMessage: 'Did you see the game last night?', time: '5 hrs ago', status: 'Idle' },
{ id: 5, name: 'Support Ticket #1234', icon: '🛠️', lastMessage: 'Issue resolved, closing ticket.', time: '3 days ago', status: 'Closed' }
],
// Computed property filters chats based on the search term
get filteredChats() {
return this.chats.filter(chat =>
chat.name.toLowerCase().includes(this.search.toLowerCase())
);
}
};
}
},
/* ----- Full application mechanics migrated from web/html/index.html ----- */
let ws=null,currentSessionId=null,currentUserId=null,currentBotId="default_bot",isStreaming=false,voiceRoom=null,isVoiceMode=false,mediaRecorder=null,audioChunks=[],streamingMessageId=null,isThinking=false,currentStreamingContent="",hasReceivedInitialMessage=false,reconnectAttempts=0,reconnectTimeout=null,thinkingTimeout=null,currentTheme='auto',themeColor1=null,themeColor2=null,customLogoUrl=null,contextUsage=0,isUserScrolling=false,autoScrollEnabled=true,isContextChange=false;
const maxReconnectAttempts=5,messagesDiv=document.getElementById("messages"),input=document.getElementById("messageInput"),sendBtn=document.getElementById("sendBtn"),voiceBtn=document.getElementById("voiceBtn"),connectionStatus=document.getElementById("connectionStatus"),flashOverlay=document.getElementById("flashOverlay"),suggestionsContainer=document.getElementById("suggestions"),floatLogo=document.getElementById("floatLogo"),sidebar=document.getElementById("sidebar"),themeBtn=document.getElementById("themeBtn"),scrollToBottomBtn=document.getElementById("scrollToBottom"),contextIndicator=document.getElementById("contextIndicator"),contextPercentage=document.getElementById("contextPercentage"),contextProgressBar=document.getElementById("contextProgressBar"),sidebarTitle=document.getElementById("sidebarTitle");
marked.setOptions({breaks:true,gfm:true});
floatLogo.addEventListener('click',toggleSidebar);
function toggleSidebar(){
// ----------------------------------------------------------------------
// UI helpers (formerly standalone functions)
// ----------------------------------------------------------------------
toggleSidebar() {
sidebar.classList.toggle('open');
}
},
function toggleTheme(){
toggleTheme() {
const themes = ['auto', 'dark', 'light'];
const savedTheme = localStorage.getItem('gb-theme') || 'auto';
const idx = themes.indexOf(savedTheme);
const newTheme = themes[(idx + 1) % themes.length];
localStorage.setItem('gb-theme', newTheme);
currentTheme = newTheme;
applyTheme();
updateThemeButton();
}
this.applyTheme();
this.updateThemeButton();
},
function updateThemeButton(){
const icons={'auto':'⚙','dark':'🌙','light':'☀️'};
themeBtn.textContent=icons[currentTheme]||'⚙';
}
function applyTheme(){
applyTheme() {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
let theme = currentTheme;
if (theme === 'auto') {
@ -73,30 +92,49 @@ function applyTheme(){
if (customLogoUrl) {
document.documentElement.style.setProperty('--logo-url', `url('${customLogoUrl}')`);
}
}
},
window.addEventListener("load",function(){
// ----------------------------------------------------------------------
// Lifecycle / event handlers
// ----------------------------------------------------------------------
init() {
document.addEventListener('ready', () => {
// Assign DOM elements after the document is ready
messagesDiv = document.getElementById("messages");
input = document.getElementById("messageInput");
sendBtn = document.getElementById("sendBtn");
voiceBtn = document.getElementById("voiceBtn");
connectionStatus = document.getElementById("connectionStatus");
flashOverlay = document.getElementById("flashOverlay");
suggestionsContainer = document.getElementById("suggestions");
floatLogo = document.getElementById("floatLogo");
sidebar = document.getElementById("sidebar");
themeBtn = document.getElementById("themeBtn");
scrollToBottomBtn = document.getElementById("scrollToBottom");
contextIndicator = document.getElementById("contextIndicator");
contextPercentage = document.getElementById("contextPercentage");
contextProgressBar = document.getElementById("contextProgressBar");
sidebarTitle = document.getElementById("sidebarTitle");
// Theme initialization and focus
const savedTheme = localStorage.getItem('gb-theme') || 'auto';
currentTheme = savedTheme;
applyTheme();
updateThemeButton();
this.applyTheme();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (currentTheme === 'auto') {
applyTheme();
this.applyTheme();
}
});
input.focus();
});
themeBtn.addEventListener('click',toggleTheme);
document.addEventListener('click',function(e){
// UI event listeners
document.addEventListener('click', (e) => {
if (sidebar.classList.contains('open') && !sidebar.contains(e.target) && !floatLogo.contains(e.target)) {
sidebar.classList.remove('open');
}
});
messagesDiv.addEventListener('scroll',function(){
messagesDiv.addEventListener('scroll', () => {
const isAtBottom = messagesDiv.scrollHeight - messagesDiv.scrollTop <= messagesDiv.clientHeight + 100;
if (!isAtBottom) {
isUserScrolling = true;
@ -107,74 +145,95 @@ messagesDiv.addEventListener('scroll',function(){
}
});
scrollToBottomBtn.addEventListener('click',function(){
scrollToBottom();
scrollToBottomBtn.addEventListener('click', () => {
this.scrollToBottom();
});
function updateContextUsage(u){
sendBtn.onclick = () => this.sendMessage();
input.addEventListener("keypress", e => { if (e.key === "Enter") this.sendMessage(); });
window.addEventListener("focus", () => {
if (!ws || ws.readyState !== WebSocket.OPEN) {
this.connectWebSocket();
}
});
// Start authentication flow
this.initializeAuth();
});
},
updateContextUsage(u) {
contextUsage = u;
const p = Math.min(100, Math.round(u * 100));
contextPercentage.textContent = `${p}%`;
contextProgressBar.style.width = `${p}%`;
contextIndicator.classList.remove('visible');
}
},
function flashScreen(){
gsap.to(flashOverlay,{opacity:0.15,duration:0.1,onComplete:()=>{gsap.to(flashOverlay,{opacity:0,duration:0.2});}});
}
flashScreen() {
gsap.to(flashOverlay, { opacity: 0.15, duration: 0.1, onComplete: () => {
gsap.to(flashOverlay, { opacity: 0, duration: 0.2 });
} });
},
function updateConnectionStatus(s){
updateConnectionStatus(s) {
connectionStatus.className = `connection-status ${s}`;
}
},
function getWebSocketUrl(){
getWebSocketUrl() {
const p = "ws:", s = currentSessionId || crypto.randomUUID(), u = currentUserId || crypto.randomUUID();
return `${p}//localhost:8080/ws?session_id=${s}&user_id=${u}`;
}
},
async function initializeAuth(){
async initializeAuth() {
try {
updateConnectionStatus("connecting");
const p=window.location.pathname.split('/').filter(s=>s),b=p.length>0?p[0]:'default',r=await fetch(`http://localhost:8080/api/auth?bot_name=${encodeURIComponent(b)}`),a=await r.json();
this.updateConnectionStatus("connecting");
const p = window.location.pathname.split('/').filter(s => s);
const b = p.length > 0 ? p[0] : 'default';
const r = await fetch(`http://localhost:8080/api/auth?bot_name=${encodeURIComponent(b)}`);
const a = await r.json();
currentUserId = a.user_id;
currentSessionId = a.session_id;
connectWebSocket();
loadSessions();
this.connectWebSocket();
this.loadSessions();
} catch (e) {
console.error("Failed to initialize auth:", e);
updateConnectionStatus("disconnected");
setTimeout(initializeAuth,3000);
}
this.updateConnectionStatus("disconnected");
setTimeout(() => this.initializeAuth(), 3000);
}
},
async function loadSessions(){
async loadSessions() {
try {
const r=await fetch("http://localhost:8080/api/sessions"),s=await r.json(),h=document.getElementById("history");
const r = await fetch("http://localhost:8080/api/sessions");
const s = await r.json();
const h = document.getElementById("history");
h.innerHTML = "";
s.forEach(session => {
const item = document.createElement('div');
item.className = 'history-item';
item.textContent = session.title || `Session ${session.session_id.substring(0, 8)}`;
item.onclick=()=>switchSession(session.session_id);
item.onclick = () => this.switchSession(session.session_id);
h.appendChild(item);
});
} catch (e) {
console.error("Failed to load sessions:", e);
}
}
},
async function createNewSession(){
async createNewSession() {
try {
const r=await fetch("http://localhost:8080/api/sessions",{method:"POST"}),s=await r.json();
const r = await fetch("http://localhost:8080/api/sessions", { method: "POST" });
const s = await r.json();
currentSessionId = s.session_id;
hasReceivedInitialMessage = false;
connectWebSocket();
loadSessions();
this.connectWebSocket();
this.loadSessions();
messagesDiv.innerHTML = "";
clearSuggestions();
updateContextUsage(0);
this.clearSuggestions();
this.updateContextUsage(0);
if (isVoiceMode) {
await stopVoiceSession();
await this.stopVoiceSession();
isVoiceMode = false;
const v = document.getElementById("voiceToggle");
v.textContent = "🎤 Voice Mode";
@ -183,135 +242,137 @@ async function createNewSession(){
} catch (e) {
console.error("Failed to create session:", e);
}
}
},
function switchSession(s){
switchSession(s) {
currentSessionId = s;
hasReceivedInitialMessage = false;
loadSessionHistory(s);
connectWebSocket();
this.loadSessionHistory(s);
this.connectWebSocket();
if (isVoiceMode) {
startVoiceSession();
this.startVoiceSession();
}
sidebar.classList.remove('open');
}
},
async function loadSessionHistory(s){
async loadSessionHistory(s) {
try {
const r=await fetch("http://localhost:8080/api/sessions/"+s),h=await r.json(),m=document.getElementById("messages");
const r = await fetch(`http://localhost:8080/api/sessions/${s}`);
const h = await r.json();
const m = document.getElementById("messages");
m.innerHTML = "";
if (h.length === 0) {
updateContextUsage(0);
this.updateContextUsage(0);
} else {
h.forEach(([role, content]) => {
addMessage(role,content,false);
this.addMessage(role, content, false);
});
updateContextUsage(h.length/20);
this.updateContextUsage(h.length / 20);
}
} catch (e) {
console.error("Failed to load session history:", e);
}
}
},
function connectWebSocket(){
connectWebSocket() {
if (ws) {
ws.close();
}
clearTimeout(reconnectTimeout);
const u=getWebSocketUrl();
const u = this.getWebSocketUrl();
ws = new WebSocket(u);
ws.onmessage=function(e){
ws.onmessage = (e) => {
const r = JSON.parse(e.data);
if (r.bot_id) {
currentBotId = r.bot_id;
}
if (r.message_type === 2) {
const d = JSON.parse(r.content);
handleEvent(d.event,d.data);
this.handleEvent(d.event, d.data);
return;
}
if (r.message_type === 5) {
isContextChange = true;
return;
}
processMessageContent(r);
this.processMessageContent(r);
};
ws.onopen=function(){
ws.onopen = () => {
console.log("Connected to WebSocket");
updateConnectionStatus("connected");
this.updateConnectionStatus("connected");
reconnectAttempts = 0;
hasReceivedInitialMessage = false;
};
ws.onclose=function(e){
ws.onclose = (e) => {
console.log("WebSocket disconnected:", e.code, e.reason);
updateConnectionStatus("disconnected");
this.updateConnectionStatus("disconnected");
if (isStreaming) {
showContinueButton();
this.showContinueButton();
}
if (reconnectAttempts < maxReconnectAttempts) {
reconnectAttempts++;
const d = Math.min(1000 * reconnectAttempts, 10000);
reconnectTimeout = setTimeout(() => {
updateConnectionStatus("connecting");
connectWebSocket();
this.updateConnectionStatus("connecting");
this.connectWebSocket();
}, d);
} else {
updateConnectionStatus("disconnected");
this.updateConnectionStatus("disconnected");
}
};
ws.onerror=function(e){
ws.onerror = (e) => {
console.error("WebSocket error:", e);
updateConnectionStatus("disconnected");
this.updateConnectionStatus("disconnected");
};
}
},
function processMessageContent(r){
processMessageContent(r) {
if (isContextChange) {
isContextChange = false;
return;
}
if (r.context_usage !== undefined) {
updateContextUsage(r.context_usage);
this.updateContextUsage(r.context_usage);
}
if (r.suggestions && r.suggestions.length > 0) {
handleSuggestions(r.suggestions);
this.handleSuggestions(r.suggestions);
}
if (r.is_complete) {
if (isStreaming) {
finalizeStreamingMessage();
this.finalizeStreamingMessage();
isStreaming = false;
streamingMessageId = null;
currentStreamingContent = "";
} else {
addMessage("assistant",r.content,false);
this.addMessage("assistant", r.content, false);
}
} else {
if (!isStreaming) {
isStreaming = true;
streamingMessageId = "streaming-" + Date.now();
currentStreamingContent = r.content || "";
addMessage("assistant",currentStreamingContent,true,streamingMessageId);
this.addMessage("assistant", currentStreamingContent, true, streamingMessageId);
} else {
currentStreamingContent += r.content || "";
updateStreamingMessage(currentStreamingContent);
}
this.updateStreamingMessage(currentStreamingContent);
}
}
},
function handleEvent(t,d){
handleEvent(t, d) {
console.log("Event received:", t, d);
switch (t) {
case "thinking_start":
showThinkingIndicator();
this.showThinkingIndicator();
break;
case "thinking_end":
hideThinkingIndicator();
this.hideThinkingIndicator();
break;
case "warn":
showWarning(d.message);
this.showWarning(d.message);
break;
case "context_usage":
updateContextUsage(d.usage);
this.updateContextUsage(d.usage);
break;
case "change_theme":
if (d.color1) themeColor1 = d.color1;
@ -321,12 +382,12 @@ function handleEvent(t,d){
if (d.logo_text) {
sidebarTitle.textContent = d.logo_text;
}
applyTheme();
this.applyTheme();
break;
}
}
},
function showThinkingIndicator(){
showThinkingIndicator() {
if (isThinking) return;
const t = document.createElement("div");
t.id = "thinking-indicator";
@ -335,18 +396,18 @@ function showThinkingIndicator(){
messagesDiv.appendChild(t);
gsap.to(t, { opacity: 1, y: 0, duration: .3, ease: "power2.out" });
if (!isUserScrolling) {
scrollToBottom();
this.scrollToBottom();
}
thinkingTimeout = setTimeout(() => {
if (isThinking) {
hideThinkingIndicator();
showWarning("O servidor pode estar ocupado. A resposta está demorando demais.");
this.hideThinkingIndicator();
this.showWarning("O servidor pode estar ocupado. A resposta está demorando demais.");
}
}, 60000);
isThinking = true;
}
},
function hideThinkingIndicator(){
hideThinkingIndicator() {
if (!isThinking) return;
const t = document.getElementById("thinking-indicator");
if (t) {
@ -357,55 +418,64 @@ function hideThinkingIndicator(){
thinkingTimeout = null;
}
isThinking = false;
}
},
function showWarning(m){
showWarning(m) {
const w = document.createElement("div");
w.className = "warning-message";
w.innerHTML = `⚠️ ${m}`;
messagesDiv.appendChild(w);
gsap.from(w, { opacity: 0, y: 20, duration: .4, ease: "power2.out" });
if (!isUserScrolling) {
scrollToBottom();
this.scrollToBottom();
}
setTimeout(() => {
if (w.parentNode) {
gsap.to(w, { opacity: 0, duration: .3, onComplete: () => w.remove() });
}
}, 5000);
}
},
function showContinueButton(){
showContinueButton() {
const c = document.createElement("div");
c.className = "message-container";
c.innerHTML=`<div class="assistant-message"><div class="assistant-avatar"></div><div class="assistant-message-content"><p>A conexão foi interrompida. Clique em "Continuar" para tentar recuperar a resposta.</p><button class="continue-button" onclick="continueInterruptedResponse()">Continuar</button></div></div>`;
c.innerHTML = `<div class="assistant-message"><div class="assistant-avatar"></div><div class="assistant-message-content"><p>A conexão foi interrompida. Clique em "Continuar" para tentar recuperar a resposta.</p><button class="continue-button" onclick="this.parentElement.parentElement.parentElement.remove();">Continuar</button></div></div>`;
messagesDiv.appendChild(c);
gsap.to(c, { opacity: 1, y: 0, duration: .5, ease: "power2.out" });
if (!isUserScrolling) {
scrollToBottom();
}
this.scrollToBottom();
}
},
function continueInterruptedResponse(){
continueInterruptedResponse() {
if (!ws || ws.readyState !== WebSocket.OPEN) {
connectWebSocket();
this.connectWebSocket();
}
if (ws && ws.readyState === WebSocket.OPEN) {
const d={bot_id:"default_bot",user_id:currentUserId,session_id:currentSessionId,channel:"web",content:"continue",message_type:3,media_url:null,timestamp:new Date().toISOString()};
const d = {
bot_id: "default_bot",
user_id: currentUserId,
session_id: currentSessionId,
channel: "web",
content: "continue",
message_type: 3,
media_url: null,
timestamp: new Date().toISOString()
};
ws.send(JSON.stringify(d));
}
document.querySelectorAll(".continue-button").forEach(b => { b.parentElement.parentElement.parentElement.remove(); });
}
},
function addMessage(role,content,streaming=false,msgId=null){
addMessage(role, content, streaming = false, msgId = null) {
const m = document.createElement("div");
m.className = "message-container";
if (role === "user") {
m.innerHTML=`<div class="user-message"><div class="user-message-content">${escapeHtml(content)}</div></div>`;
updateContextUsage(contextUsage+.05);
m.innerHTML = `<div class="user-message"><div class="user-message-content">${this.escapeHtml(content)}</div></div>`;
this.updateContextUsage(contextUsage + .05);
} else if (role === "assistant") {
m.innerHTML = `<div class="assistant-message"><div class="assistant-avatar"></div><div class="assistant-message-content markdown-content" id="${msgId || ""}">${streaming ? "" : marked.parse(content)}</div></div>`;
updateContextUsage(contextUsage+.03);
this.updateContextUsage(contextUsage + .03);
} else if (role === "voice") {
m.innerHTML = `<div class="assistant-message"><div class="assistant-avatar">🎤</div><div class="assistant-message-content">${content}</div></div>`;
} else {
@ -414,61 +484,58 @@ function addMessage(role,content,streaming=false,msgId=null){
messagesDiv.appendChild(m);
gsap.to(m, { opacity: 1, y: 0, duration: .5, ease: "power2.out" });
if (!isUserScrolling) {
scrollToBottom();
}
this.scrollToBottom();
}
},
function updateStreamingMessage(c){
updateStreamingMessage(c) {
const m = document.getElementById(streamingMessageId);
if (m) {
m.innerHTML = marked.parse(c);
if (!isUserScrolling) {
scrollToBottom();
}
this.scrollToBottom();
}
}
},
function finalizeStreamingMessage(){
finalizeStreamingMessage() {
const m = document.getElementById(streamingMessageId);
if (m) {
m.innerHTML = marked.parse(currentStreamingContent);
m.removeAttribute("id");
if (!isUserScrolling) {
scrollToBottom();
}
this.scrollToBottom();
}
}
},
function escapeHtml(t){
escapeHtml(t) {
const d = document.createElement("div");
d.textContent = t;
return d.innerHTML;
}
},
function clearSuggestions(){
clearSuggestions() {
suggestionsContainer.innerHTML = '';
}
},
function handleSuggestions(s){
handleSuggestions(s) {
const uniqueSuggestions = s.filter((v, i, a) => i === a.findIndex(t => t.text === v.text && t.context === v.context));
suggestionsContainer.innerHTML = '';
uniqueSuggestions.forEach(v => {
const b = document.createElement('button');
b.textContent = v.text;
b.className = 'suggestion-button';
b.onclick=()=>{setContext(v.context);input.value='';};
b.onclick = () => { this.setContext(v.context); input.value = ''; };
suggestionsContainer.appendChild(b);
});
}
},
let pendingContextChange=null;
async function setContext(c){
async setContext(c) {
try {
const t = event?.target?.textContent || c;
addMessage("user",t);
const i=document.getElementById('messageInput');
if(i){i.value='';}
this.addMessage("user", t);
input.value = '';
if (ws && ws.readyState === WebSocket.OPEN) {
pendingContextChange = new Promise(r => {
const h = e => {
@ -487,14 +554,14 @@ async function setContext(c){
if (x) { document.getElementById('contextPercentage').textContent = c; }
} else {
console.warn("WebSocket não está conectado. Tentando reconectar...");
connectWebSocket();
this.connectWebSocket();
}
} catch (err) {
console.error('Failed to set context:', err);
}
}
},
async function sendMessage(){
async sendMessage() {
if (pendingContextChange) {
await pendingContextChange;
pendingContextChange = null;
@ -502,56 +569,62 @@ async function sendMessage(){
const m = input.value.trim();
if (!m || !ws || ws.readyState !== WebSocket.OPEN) {
if (!ws || ws.readyState !== WebSocket.OPEN) {
showWarning("Conexão não disponível. Tentando reconectar...");
connectWebSocket();
this.showWarning("Conexão não disponível. Tentando reconectar...");
this.connectWebSocket();
}
return;
}
if (isThinking) {
hideThinkingIndicator();
this.hideThinkingIndicator();
}
addMessage("user",m);
this.addMessage("user", m);
const d = { bot_id: currentBotId, user_id: currentUserId, session_id: currentSessionId, channel: "web", content: m, message_type: 1, media_url: null, timestamp: new Date().toISOString() };
ws.send(JSON.stringify(d));
input.value = "";
input.focus();
}
},
sendBtn.onclick=sendMessage;
input.addEventListener("keypress",e=>{if(e.key==="Enter")sendMessage();});
async function toggleVoiceMode(){
async toggleVoiceMode() {
isVoiceMode = !isVoiceMode;
const v = document.getElementById("voiceToggle");
if (isVoiceMode) {
v.textContent = "🔴 Stop Voice";
v.classList.add("recording");
await startVoiceSession();
await this.startVoiceSession();
} else {
v.textContent = "🎤 Voice Mode";
v.classList.remove("recording");
await stopVoiceSession();
}
await this.stopVoiceSession();
}
},
async function startVoiceSession(){
async startVoiceSession() {
if (!currentSessionId) return;
try {
const r=await fetch("http://localhost:8080/api/voice/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:currentSessionId,user_id:currentUserId})}),d=await r.json();
const r = await fetch("http://localhost:8080/api/voice/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ session_id: currentSessionId, user_id: currentUserId })
});
const d = await r.json();
if (d.token) {
await connectToVoiceRoom(d.token);
startVoiceRecording();
await this.connectToVoiceRoom(d.token);
this.startVoiceRecording();
}
} catch (e) {
console.error("Failed to start voice session:", e);
showWarning("Falha ao iniciar modo de voz");
}
this.showWarning("Falha ao iniciar modo de voz");
}
},
async function stopVoiceSession(){
async stopVoiceSession() {
if (!currentSessionId) return;
try {
await fetch("http://localhost:8080/api/voice/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:currentSessionId})});
await fetch("http://localhost:8080/api/voice/stop", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ session_id: currentSessionId })
});
if (voiceRoom) {
voiceRoom.disconnect();
voiceRoom = null;
@ -562,11 +635,12 @@ async function stopVoiceSession(){
} catch (e) {
console.error("Failed to stop voice session:", e);
}
}
},
async function connectToVoiceRoom(t){
async connectToVoiceRoom(t) {
try {
const r=new LiveKitClient.Room(),p="ws:",u=`${p}//localhost:8080/voice`;
const r = new LiveKitClient.Room();
const p = "ws:", u = `${p}//localhost:8080/voice`;
await r.connect(u, t);
voiceRoom = r;
r.on("dataReceived", d => {
@ -574,7 +648,7 @@ async function connectToVoiceRoom(t){
try {
const j = JSON.parse(m);
if (j.type === "voice_response") {
addMessage("assistant",j.text);
this.addMessage("assistant", j.text);
}
} catch (e) {
console.log("Voice data:", m);
@ -586,11 +660,11 @@ async function connectToVoiceRoom(t){
}
} catch (e) {
console.error("Failed to connect to voice room:", e);
showWarning("Falha na conexão de voz");
}
this.showWarning("Falha na conexão de voz");
}
},
function startVoiceRecording(){
startVoiceRecording() {
if (!navigator.mediaDevices) {
console.log("Media devices not supported");
return;
@ -599,42 +673,41 @@ function startVoiceRecording(){
mediaRecorder = new MediaRecorder(s);
audioChunks = [];
mediaRecorder.ondataavailable = e => { audioChunks.push(e.data); };
mediaRecorder.onstop=()=>{const a=new Blob(audioChunks,{type:"audio/wav"});simulateVoiceTranscription();};
mediaRecorder.onstop = () => { const a = new Blob(audioChunks, { type: "audio/wav" }); this.simulateVoiceTranscription(); };
mediaRecorder.start();
setTimeout(() => {
if (mediaRecorder && mediaRecorder.state === "recording") {
mediaRecorder.stop();
setTimeout(() => {
if (isVoiceMode) {
startVoiceRecording();
this.startVoiceRecording();
}
}, 1000);
}
}, 5000);
}).catch(e => {
console.error("Error accessing microphone:", e);
showWarning("Erro ao acessar microfone");
this.showWarning("Erro ao acessar microfone");
});
}
},
function simulateVoiceTranscription(){
const p=["Olá, como posso ajudá-lo hoje?","Entendo o que você está dizendo","Esse é um ponto interessante","Deixe-me pensar sobre isso","Posso ajudá-lo com isso","O que você gostaria de saber?","Isso parece ótimo","Estou ouvindo sua voz"],r=p[Math.floor(Math.random()*p.length)];
simulateVoiceTranscription() {
const p = ["Olá, como posso ajudá-lo hoje?", "Entendo o que você está dizendo", "Esse é um ponto interessante", "Deixe-me pensar sobre isso", "Posso ajudá-lo com isso", "O que você gostaria de saber?", "Isso parece ótimo", "Estou ouvindo sua voz"];
const r = p[Math.floor(Math.random() * p.length)];
if (voiceRoom) {
const m = { type: "voice_input", content: r, timestamp: new Date().toISOString() };
voiceRoom.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(m)), LiveKitClient.DataPacketKind.RELIABLE);
}
addMessage("voice",`🎤 ${r}`);
}
this.addMessage("voice", `🎤 ${r}`);
},
function scrollToBottom(){
scrollToBottom() {
messagesDiv.scrollTop = messagesDiv.scrollHeight;
isUserScrolling = false;
scrollToBottomBtn.classList.remove('visible');
}
window.addEventListener("load",initializeAuth);
window.addEventListener("focus",function(){
if(!ws||ws.readyState!==WebSocket.OPEN){
connectWebSocket();
};
}
});
// Initialize the app
chatApp().init();

View file

@ -1,12 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>General Bots Desktop</title>
<title>General Bots</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link rel="stylesheet" href="css/app.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script defer src="js/alpine.js"></script>
</head>
<body>
<nav x-data="{ current: 'drive' }">
<div class="logo">⚡ General Bots</div>
@ -27,16 +33,11 @@
<!-- Load Module Scripts -->
<script src="js/layout.js"></script>
<script src="chat/chat.js"></script>
<script src="drive/drive.js"></script>
<script src="tasks/tasks.js"></script>
<script src="mail/mail.js"></script>
<script src="dashboard/dashboard.js"></script>
<script src="editor/editor.js"></script>
<script src="player/player.js"></script>
<script src="paper/paper.js"></script>
<script src="settings/settings.js"></script>
<script src="tables/tables.js"></script>
<script src="news/news.js"></script>
</body>
</html>