Skip to content

Agent Zero AI framework

toast errors

frdelf0be03ea77c3
diff --git a/agent.py b/agent.py
index fb5773564..c2033f349 100644
--- a/agent.py
+++ b/agent.py
@@ -87,7 +87,7 @@ class AgentContext:
self.process = DeferredTask(current_agent.monologue)
return self.process
-
+
def communicate(self, msg: "UserMessage", broadcast_level: int = 1):
self.paused = False # unpause if paused
@@ -394,7 +394,7 @@ class Agent:
# Handling for general exceptions
error_message = errors.format_error(exception)
PrintStyle(font_color="red", padding=True).print(error_message)
- self.context.log.log(type="error", content=error_message)
+ self.context.log.log(type="error", heading="Error", content=error_message)
raise HandledException(exception) # Re-raise the exception to kill the loop
async def get_system_prompt(self, loop_data: LoopData) -> list[str]:
diff --git a/webui/css/toast.css b/webui/css/toast.css
index f28fbe0bc..80a072ca2 100644
--- a/webui/css/toast.css
+++ b/webui/css/toast.css
@@ -37,7 +37,7 @@
.toast__message {
margin: 0;
- max-width: 320px;
+ /* max-width: 320px; */
text-overflow: ellipsis !important;
}
diff --git a/webui/index.js b/webui/index.js
index cf0975182..019cc3ff2 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -12,9 +12,13 @@ const statusSection = document.getElementById('status-section');
const chatsSection = document.getElementById('chats-section');
const progressBar = document.getElementById('progress-bar');
const autoScrollSwitch = document.getElementById('auto-scroll-switch');
+const timeDate = document.getElementById('time-date-container');
+
let autoScroll = true;
let context = "";
+let connectionStatus = false
+
// Initialize the toggle button
setupSidebarToggle();
@@ -157,9 +161,19 @@ export async function sendMessage() {
adjustTextareaHeight();
}
} catch (e) {
- toast(e.message, "error");
+ toastFetchError("Error sending message", e)
+ }
+}
+
+function toastFetchError(text, error) {
+ if (getConnectionStatus()) {
+ toast(`${text}: ${error.message}`, "error");
+ } else {
+ toast(`${text} (it seems the backend is not running): ${error.message}`, "error");
}
+ console.error(text, error);
}
+window.toastFetchError = toastFetchError
chatInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
@@ -302,6 +316,16 @@ function generateGUID() {
});
}
+function getConnectionStatus() {
+ return connectionStatus
+}
+
+function setConnectionStatus(connected) {
+ connectionStatus = connected
+ const statusIcon = Alpine.$data(timeDate.querySelector('.status-icon'));
+ statusIcon.connected = connected
+}
+
let lastLogVersion = 0;
let lastLogGuid = ""
let lastSpokenNo = 0
@@ -336,11 +360,7 @@ async function poll() {
inputAD.paused = response.paused;
// Update status icon state
- const timeDate = document.getElementById('time-date-container');
- if (timeDate) {
- const statusIcon = Alpine.$data(timeDate.querySelector('.status-icon'));
- statusIcon.connected = true;
- }
+ setConnectionStatus(true)
const chatsAD = Alpine.$data(chatsSection);
chatsAD.contexts = response.contexts;
@@ -350,11 +370,7 @@ async function poll() {
} catch (error) {
console.error('Error:', error);
- const timeDate = document.getElementById('time-date-container');
- if (timeDate) {
- const statusIcon = Alpine.$data(timeDate.querySelector('.status-icon'));
- statusIcon.connected = false;
- }
+ setConnectionStatus(false)
}
return updated
@@ -396,41 +412,56 @@ function updateProgress(progress) {
}
window.pauseAgent = async function (paused) {
- const resp = await sendJsonData("/pause", { paused: paused, context });
+ try {
+ const resp = await sendJsonData("/pause", { paused: paused, context });
+ } catch (e) {
+ window.toastFetchError("Error pausing agent", e)
+ }
}
window.resetChat = async function () {
- const resp = await sendJsonData("/chat_reset", { context });
- updateAfterScroll()
+ try {
+ const resp = await sendJsonData("/chat_reset", { context });
+ updateAfterScroll()
+ } catch (e) {
+ window.toastFetchError("Error resetting chat", e)
+ }
}
window.newChat = async function () {
- setContext(generateGUID());
- updateAfterScroll()
+ try {
+ setContext(generateGUID());
+ updateAfterScroll()
+ } catch (e) {
+ window.toastFetchError("Error creating new chat", e)
+ }
}
window.killChat = async function (id) {
+ try {
+ const chatsAD = Alpine.$data(chatsSection);
+ let found, other
+ for (let i = 0; i < chatsAD.contexts.length; i++) {
+ if (chatsAD.contexts[i].id == id) {
+ found = true
+ } else {
+ other = chatsAD.contexts[i]
+ }
+ if (found && other) break
+ }
-
- const chatsAD = Alpine.$data(chatsSection);
- let found, other
- for (let i = 0; i < chatsAD.contexts.length; i++) {
- if (chatsAD.contexts[i].id == id) {
- found = true
- } else {
- other = chatsAD.contexts[i]
+ if (context == id && found) {
+ if (other) setContext(other.id)
+ else setContext(generateGUID())
}
- if (found && other) break
- }
- if (context == id && found) {
- if (other) setContext(other.id)
- else setContext(generateGUID())
- }
+ if (found) sendJsonData("/chat_remove", { context: id });
- if (found) sendJsonData("/chat_remove", { context: id });
+ updateAfterScroll()
- updateAfterScroll()
+ } catch (e) {
+ window.toastFetchError("Error creating new chat", e)
+ }
}
window.selectChat = async function (id) {
@@ -493,21 +524,25 @@ window.nudge = async function () {
try {
const resp = await sendJsonData("/nudge", { ctxid: getContext() });
} catch (e) {
- toast(e.message, "error")
+ toastFetchError("Error nudging agent", e)
}
}
window.restart = async function () {
try {
+ if (!getConnectionStatus()) {
+ toast("Backend disconnected, cannot restart.", "error");
+ return
+ }
// First try to initiate restart
const resp = await sendJsonData("/restart", {});
} catch (e) {
// Show restarting message
toast("Restarting...", "info", 0);
-
+
let retries = 0;
const maxRetries = 60; // Maximum number of retries (15 seconds with 250ms interval)
-
+
while (retries < maxRetries) {
try {
const resp = await sendJsonData("/health", {});
@@ -523,7 +558,7 @@ window.restart = async function () {
await new Promise(resolve => setTimeout(resolve, 250));
}
}
-
+
// If we get here, restart failed or took too long
hideToast();
await new Promise(resolve => setTimeout(resolve, 400));
@@ -592,7 +627,7 @@ window.loadChats = async function () {
}
} catch (e) {
- toast(e.message, "error")
+ toastFetchError("Error loading chats", e)
}
}
@@ -616,7 +651,7 @@ window.saveChat = async function () {
}
} catch (e) {
- toast(e.message, "error")
+ toastFetchError("Error saving chat", e)
}
}
@@ -751,7 +786,7 @@ function toast(text, type = 'info', timeout = 5000) {
// If a toast is visible, hide it first then show the new one
toast.classList.remove('show');
toast.classList.add('hide');
-
+
// Wait for hide animation to complete before showing new toast
setTimeout(() => {
toast.classList.remove('hide');
@@ -765,13 +800,13 @@ function toast(text, type = 'info', timeout = 5000) {
function hideToast() {
const toast = document.getElementById('toast');
-
+
// Clear any existing timeout
if (toast.timeoutId) {
clearTimeout(toast.timeoutId);
toast.timeoutId = null;
}
-
+
toast.classList.remove('show');
toast.classList.add('hide');
diff --git a/webui/js/file_browser.js b/webui/js/file_browser.js
index fd9eca788..21a842537 100644
--- a/webui/js/file_browser.js
+++ b/webui/js/file_browser.js
@@ -51,7 +51,7 @@ const fileBrowserModalProxy = {
this.browser.entries = [];
}
} catch (error) {
- console.error('Error fetching files:', error);
+ window.toastFetchError("Error fetching files", error)
this.browser.entries = [];
} finally {
this.isLoading = false;
@@ -129,7 +129,7 @@ const fileBrowserModalProxy = {
alert(`Error deleting file: ${await response.text()}`);
}
} catch (error) {
- console.error('Error deleting file:', error);
+ window.toastFetchError("Error deleting file", error)
alert('Error deleting file');
}
},
@@ -180,7 +180,7 @@ const fileBrowserModalProxy = {
}
} catch (error) {
- console.error('Error uploading files:', error);
+ window.toastFetchError("Error uploading files", error)
alert('Error uploading files');
}
},
@@ -209,8 +209,7 @@ const fileBrowserModalProxy = {
window.URL.revokeObjectURL(link.href);
} catch (error) {
-
- console.error('Error downloading file:', error);
+ window.toastFetchError("Error downloading file", error)
alert('Error downloading file');
}
},
diff --git a/webui/js/history.js b/webui/js/history.js
index 2817e177f..1afb48f20 100644
--- a/webui/js/history.js
+++ b/webui/js/history.js
@@ -1,20 +1,31 @@
import { getContext } from "../index.js";
export async function openHistoryModal() {
- const hist = await window.sendJsonData("/history_get", { context: getContext() });
+ try {
+ const hist = await window.sendJsonData("/history_get", { context: getContext() });
+ } catch (e) {
+ window.toastFetchError("Error fetching history", e)
+ return
+ }
const data = JSON.stringify(hist.history, null, 4);
const size = hist.tokens
- await showEditorModal(data, "json", `History ~${size} tokens`,"Conversation history visible to the LLM. History is compressed to fit into the context window over time.");
+ await showEditorModal(data, "json", `History ~${size} tokens`, "Conversation history visible to the LLM. History is compressed to fit into the context window over time.");
+
}
export async function openCtxWindowModal() {
- const win = await window.sendJsonData("/ctx_window_get", { context: getContext() });
+ try {
+ const win = await window.sendJsonData("/ctx_window_get", { context: getContext() });
+ } catch (e) {
+ window.toastFetchError("Error fetching context", e)
+ return
+ }
const data = win.content
const size = win.tokens
- await showEditorModal(data, "markdown", `Context window ~${size} tokens`,"Data passed to the LLM during last interaction. Contains system message, conversation history and RAG.");
+ await showEditorModal(data, "markdown", `Context window ~${size} tokens`, "Data passed to the LLM during last interaction. Contains system message, conversation history and RAG.");
}
-async function showEditorModal(data, type = "json", title, description="") {
+async function showEditorModal(data, type = "json", title, description = "") {
// Generate the HTML with JSON Viewer container
const html = `<div id="json-viewer-container"></div>`;
@@ -29,7 +40,7 @@ async function showEditorModal(data, type = "json", title, description="") {
const dark = localStorage.getItem('darkMode')
if (dark != "false") {
editor.setTheme("ace/theme/github_dark");
- }else{
+ } else {
editor.setTheme("ace/theme/tomorrow");
}
diff --git a/webui/js/settings.js b/webui/js/settings.js
index e5eb65149..bae08417f 100644
--- a/webui/js/settings.js
+++ b/webui/js/settings.js
@@ -10,32 +10,38 @@ const settingsModalProxy = {
const modalAD = Alpine.$data(modalEl);
//get settings from backend
- const set = await sendJsonData("/settings_get", null);
-
- const settings = {
- "title": "Settings page",
- "buttons": [
- {
- "id": "save",
- "title": "Save",
- "classes": "btn btn-ok"
- },
- {
- "id": "cancel",
- "title": "Cancel",
- "type": "secondary",
- "classes": "btn btn-cancel"
- }
- ],
- "sections": set.settings.sections
- }
-
- modalAD.isOpen = true; // Update directly
- modalAD.settings = settings; // Update directly
+ try {
+ const set = await sendJsonData("/settings_get", null);
+
+
+ const settings = {
+ "title": "Settings page",
+ "buttons": [
+ {
+ "id": "save",
+ "title": "Save",
+ "classes": "btn btn-ok"
+ },
+ {
+ "id": "cancel",
+ "title": "Cancel",
+ "type": "secondary",
+ "classes": "btn btn-cancel"
+ }
+ ],
+ "sections": set.settings.sections
+ }
+
+ modalAD.isOpen = true; // Update directly
+ modalAD.settings = settings; // Update directly
+
+ return new Promise(resolve => {
+ this.resolvePromise = resolve;
+ });
- return new Promise(resolve => {
- this.resolvePromise = resolve;
- });
+ } catch (e) {
+ window.toastFetchError("Error getting settings", e)
+ }
},
async handleButton(buttonId) {
@@ -43,7 +49,12 @@ const settingsModalProxy = {
const modalEl = document.getElementById('settingsModal');
const modalAD = Alpine.$data(modalEl);
- resp = await window.sendJsonData("/settings_set", modalAD.settings);
+ try {
+ resp = await window.sendJsonData("/settings_set", modalAD.settings);
+ } catch (e) {
+ window.toastFetchError("Error saving settings", e)
+ return
+ }
document.dispatchEvent(new CustomEvent('settings-updated', { detail: resp.settings }));
this.resolvePromise({
status: 'saved',
@@ -86,16 +97,16 @@ const settingsModalProxy = {
// });
function getIconName(title) {
- const iconMap = {
- 'Agent Config': 'agentconfig',
- 'Chat Model': 'chat-model',
- 'Utility model': 'utility-model',
- 'Embedding Model': 'embed-model',
- 'Speech to Text': 'voice',
- 'API Keys': 'api-keys',
- 'Authentication': 'auth',
- 'Development': 'dev'
- };
- return iconMap[title] || 'default';
+ const iconMap = {
+ 'Agent Config': 'agentconfig',
+ 'Chat Model': 'chat-model',
+ 'Utility model': 'utility-model',
+ 'Embedding Model': 'embed-model',
+ 'Speech to Text': 'voice',
+ 'API Keys': 'api-keys',
+ 'Authentication': 'auth',
+ 'Development': 'dev'
+ };
+ return iconMap[title] || 'default';
}
diff --git a/webui/js/speech.js b/webui/js/speech.js
index 602838e3a..2a088b06d 100644
--- a/webui/js/speech.js
+++ b/webui/js/speech.js
@@ -33,7 +33,7 @@ async function loadMicSettings() {
const response = await fetch('/settings_get');
const data = await response.json();
const sttSettings = data.settings.sections.find(s => s.title === 'Speech to Text');
-
+
if (sttSettings) {
// Update options from server settings
sttSettings.fields.forEach(field => {
@@ -42,6 +42,7 @@ async function loadMicSettings() {
});
}
} catch (error) {
+ window.toastFetchError("Failed to load speech settings", error)
console.error('Failed to load speech settings:', error);
}
}
@@ -282,8 +283,8 @@ class MicrophoneInput {
await this.updateCallback(result.text, true);
}
} catch (error) {
+ window.toastFetchError("Transcription error", error)
console.error('Transcription error:', error);
- toast('Transcription failed.', 'error');
} finally {
this.audioChunks = [];
this.status = Status.LISTENING;
@@ -407,7 +408,7 @@ class Speech {
}
replaceURLs(text) {
- const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])|(\b(www\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])|(\b[-A-Z0-9+&@#\/%?=~_|!:,.;]*\.(?:[A-Z]{2,})[-A-Z0-9+&@#\/%?=~_|])/ig; return text.replace(urlRegex, (url) => {
+ const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])|(\b(www\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])|(\b[-A-Z0-9+&@#\/%?=~_|!:,.;]*\.(?:[A-Z]{2,})[-A-Z0-9+&@#\/%?=~_|])/ig; return text.replace(urlRegex, (url) => {
let text = url
// if contains ://, split by it
if (text.includes('://')) text = text.split('://')[1];