Rework UI by returning error/statuses, some refactorings

This commit is contained in:
Ettore Di Giacinto
2025-03-03 22:34:46 +01:00
parent 365f89cd5e
commit 173eda4fb3
9 changed files with 614 additions and 161 deletions

View File

@@ -168,37 +168,6 @@ func (a *Agent) askLLM(ctx context.Context, conversation []openai.ChatCompletion
return resp.Choices[0].Message, nil
}
func (a *Agent) saveCurrentConversationInMemory() {
if !a.options.enableLongTermMemory && !a.options.enableSummaryMemory {
xlog.Debug("Long term memory is disabled", "agent", a.Character.Name)
return
}
xlog.Info("Saving conversation", "agent", a.Character.Name, "conversation size", len(a.currentConversation))
if a.options.enableSummaryMemory && len(a.currentConversation) > 0 {
msg, err := a.askLLM(a.context.Context, []openai.ChatCompletionMessage{{
Role: "user",
Content: "Summarize the conversation below, keep the highlights as a bullet list:\n" + Messages(a.currentConversation).String(),
}})
if err != nil {
xlog.Error("Error summarizing conversation", "error", err)
}
if err := a.options.ragdb.Store(msg.Content); err != nil {
xlog.Error("Error storing into memory", "error", err)
}
} else {
for _, message := range a.currentConversation {
if message.Role == "user" {
if err := a.options.ragdb.Store(message.Content); err != nil {
xlog.Error("Error storing into memory", "error", err)
}
}
}
}
}
func (a *Agent) ResetConversation() {
a.Lock()
defer a.Unlock()
@@ -280,59 +249,6 @@ func (a *Agent) runAction(chosenAction Action, params action.ActionParams) (resu
return result, nil
}
func (a *Agent) knowledgeBaseLookup() {
if (!a.options.enableKB && !a.options.enableLongTermMemory && !a.options.enableSummaryMemory) ||
len(a.currentConversation) <= 0 {
xlog.Debug("[Knowledge Base Lookup] Disabled, skipping", "agent", a.Character.Name)
return
}
// Walk conversation from bottom to top, and find the first message of the user
// to use it as a query to the KB
var userMessage string
for i := len(a.currentConversation) - 1; i >= 0; i-- {
xlog.Info("[Knowledge Base Lookup] Conversation", "role", a.currentConversation[i].Role, "Content", a.currentConversation[i].Content)
if a.currentConversation[i].Role == "user" {
userMessage = a.currentConversation[i].Content
break
}
}
xlog.Info("[Knowledge Base Lookup] Last user message", "agent", a.Character.Name, "message", userMessage)
if userMessage == "" {
xlog.Info("[Knowledge Base Lookup] No user message found in conversation", "agent", a.Character.Name)
return
}
results, err := a.options.ragdb.Search(userMessage, a.options.kbResults)
if err != nil {
xlog.Info("Error finding similar strings inside KB:", "error", err)
}
if len(results) == 0 {
xlog.Info("[Knowledge Base Lookup] No similar strings found in KB", "agent", a.Character.Name)
return
}
formatResults := ""
for _, r := range results {
formatResults += fmt.Sprintf("- %s \n", r)
}
xlog.Info("[Knowledge Base Lookup] Found similar strings in KB", "agent", a.Character.Name, "results", formatResults)
// a.currentConversation = append(a.currentConversation,
// openai.ChatCompletionMessage{
// Role: "system",
// Content: fmt.Sprintf("Given the user input you have the following in memory:\n%s", formatResults),
// },
// )
a.currentConversation = append([]openai.ChatCompletionMessage{
{
Role: "system",
Content: fmt.Sprintf("Given the user input you have the following in memory:\n%s", formatResults),
}}, a.currentConversation...)
}
func (a *Agent) consumeJob(job *Job, role string) {
a.Lock()
paused := a.pause

View File

@@ -0,0 +1,92 @@
package agent
import (
"fmt"
"github.com/mudler/LocalAgent/pkg/xlog"
"github.com/sashabaranov/go-openai"
)
func (a *Agent) knowledgeBaseLookup() {
if (!a.options.enableKB && !a.options.enableLongTermMemory && !a.options.enableSummaryMemory) ||
len(a.currentConversation) <= 0 {
xlog.Debug("[Knowledge Base Lookup] Disabled, skipping", "agent", a.Character.Name)
return
}
// Walk conversation from bottom to top, and find the first message of the user
// to use it as a query to the KB
var userMessage string
for i := len(a.currentConversation) - 1; i >= 0; i-- {
xlog.Info("[Knowledge Base Lookup] Conversation", "role", a.currentConversation[i].Role, "Content", a.currentConversation[i].Content)
if a.currentConversation[i].Role == "user" {
userMessage = a.currentConversation[i].Content
break
}
}
xlog.Info("[Knowledge Base Lookup] Last user message", "agent", a.Character.Name, "message", userMessage)
if userMessage == "" {
xlog.Info("[Knowledge Base Lookup] No user message found in conversation", "agent", a.Character.Name)
return
}
results, err := a.options.ragdb.Search(userMessage, a.options.kbResults)
if err != nil {
xlog.Info("Error finding similar strings inside KB:", "error", err)
}
if len(results) == 0 {
xlog.Info("[Knowledge Base Lookup] No similar strings found in KB", "agent", a.Character.Name)
return
}
formatResults := ""
for _, r := range results {
formatResults += fmt.Sprintf("- %s \n", r)
}
xlog.Info("[Knowledge Base Lookup] Found similar strings in KB", "agent", a.Character.Name, "results", formatResults)
// a.currentConversation = append(a.currentConversation,
// openai.ChatCompletionMessage{
// Role: "system",
// Content: fmt.Sprintf("Given the user input you have the following in memory:\n%s", formatResults),
// },
// )
a.currentConversation = append([]openai.ChatCompletionMessage{
{
Role: "system",
Content: fmt.Sprintf("Given the user input you have the following in memory:\n%s", formatResults),
}}, a.currentConversation...)
}
func (a *Agent) saveCurrentConversationInMemory() {
if !a.options.enableLongTermMemory && !a.options.enableSummaryMemory {
xlog.Debug("Long term memory is disabled", "agent", a.Character.Name)
return
}
xlog.Info("Saving conversation", "agent", a.Character.Name, "conversation size", len(a.currentConversation))
if a.options.enableSummaryMemory && len(a.currentConversation) > 0 {
msg, err := a.askLLM(a.context.Context, []openai.ChatCompletionMessage{{
Role: "user",
Content: "Summarize the conversation below, keep the highlights as a bullet list:\n" + Messages(a.currentConversation).String(),
}})
if err != nil {
xlog.Error("Error summarizing conversation", "error", err)
}
if err := a.options.ragdb.Store(msg.Content); err != nil {
xlog.Error("Error storing into memory", "error", err)
}
} else {
for _, message := range a.currentConversation {
if message.Role == "user" {
if err := a.options.ragdb.Store(message.Content); err != nil {
xlog.Error("Error storing into memory", "error", err)
}
}
}
}
}

View File

@@ -64,8 +64,6 @@ func (c *WrappedClient) Search(s string, similarity int) ([]string, error) {
func (c *WrappedClient) Store(s string) error {
// the Client API of LocalRAG takes only files at the moment.
// So we take the string that we want to store, write it to a file, and then store the file.
// get current date and time for file name
t := time.Now()
dateTime := t.Format("2006-01-02-15-04-05")
hash := md5.Sum([]byte(s))

View File

@@ -1,7 +1,6 @@
package webui
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
@@ -15,7 +14,6 @@ import (
"github.com/mudler/LocalAgent/core/state"
"github.com/donseba/go-htmx"
"github.com/dslipak/pdf"
fiber "github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html/v2"
)
@@ -79,12 +77,24 @@ func (a *App) Delete(pool *state.AgentPool) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
if err := pool.Remove(c.Params("name")); err != nil {
xlog.Info("Error removing agent", err)
return c.Status(http.StatusInternalServerError).SendString(err.Error())
return errorJSONMessage(c, err.Error())
}
return c.Redirect("/agents")
return statusJSONMessage(c, "ok")
}
}
func errorJSONMessage(c *fiber.Ctx, message string) error {
return c.Status(http.StatusInternalServerError).JSON(struct {
Error string `json:"error"`
}{Error: message})
}
func statusJSONMessage(c *fiber.Ctx, message string) error {
return c.JSON(struct {
Status string `json:"status"`
}{Status: message})
}
func (a *App) Pause(pool *state.AgentPool) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
xlog.Info("Pausing agent", c.Params("name"))
@@ -92,7 +102,7 @@ func (a *App) Pause(pool *state.AgentPool) func(c *fiber.Ctx) error {
if agent != nil {
agent.Pause()
}
return c.Redirect("/agents")
return statusJSONMessage(c, "ok")
}
}
@@ -102,7 +112,7 @@ func (a *App) Start(pool *state.AgentPool) func(c *fiber.Ctx) error {
if agent != nil {
agent.Resume()
}
return c.Redirect("/agents")
return statusJSONMessage(c, "ok")
}
}
@@ -110,20 +120,18 @@ func (a *App) Create(pool *state.AgentPool) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
config := state.AgentConfig{}
if err := c.BodyParser(&config); err != nil {
return err
return errorJSONMessage(c, err.Error())
}
fmt.Printf("Agent configuration: %+v\n", config)
if config.Name == "" {
c.Status(http.StatusBadRequest).SendString("Name is required")
return nil
return errorJSONMessage(c, "Name is required")
}
if err := pool.CreateAgent(config.Name, &config); err != nil {
c.Status(http.StatusInternalServerError).SendString(err.Error())
return nil
return errorJSONMessage(c, err.Error())
}
return c.Redirect("/agents")
return statusJSONMessage(c, "ok")
}
}
@@ -131,7 +139,7 @@ func (a *App) ExportAgent(pool *state.AgentPool) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
agent := pool.GetConfig(c.Params("name"))
if agent == nil {
return c.Status(http.StatusNotFound).SendString("Agent not found")
return errorJSONMessage(c, "Agent not found")
}
c.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.json", agent.Name))
@@ -168,15 +176,13 @@ func (a *App) ImportAgent(pool *state.AgentPool) func(c *fiber.Ctx) error {
xlog.Info("Importing agent", config.Name)
if config.Name == "" {
c.Status(http.StatusBadRequest).SendString("Name is required")
return nil
return errorJSONMessage(c, "Name is required")
}
if err := pool.CreateAgent(config.Name, &config); err != nil {
c.Status(http.StatusInternalServerError).SendString(err.Error())
return nil
return errorJSONMessage(c, err.Error())
}
return c.Redirect("/agents")
return statusJSONMessage(c, "ok")
}
}
@@ -237,17 +243,3 @@ func (a *App) Chat(pool *state.AgentPool) func(c *fiber.Ctx) error {
return nil
}
}
func readPdf(path string) (string, error) {
r, err := pdf.Open(path)
if err != nil {
return "", err
}
var buf bytes.Buffer
b, err := r.GetPlainText()
if err != nil {
return "", err
}
buf.ReadFrom(b)
return buf.String(), nil
}

View File

@@ -79,7 +79,7 @@ func (app *App) registerRoutes(pool *state.AgentPool, webapp *fiber.App) {
webapp.Get("/notify/:name", app.Notify(pool))
webapp.Post("/chat/:name", app.Chat(pool))
webapp.Post("/create", app.Create(pool))
webapp.Get("/delete/:name", app.Delete(pool))
webapp.Delete("/delete/:name", app.Delete(pool))
webapp.Put("/pause/:name", app.Pause(pool))
webapp.Put("/start/:name", app.Start(pool))

View File

@@ -9,12 +9,83 @@
.button-container {
display: flex;
justify-content: flex-end;
margin-bottom: 8px; /* Adjusts the spacing to your liking */
margin-bottom: 8px;
}
.section-box {
background-color: rgba(30, 41, 59, 0.8);
border-radius: 8px;
padding: 20px;
margin-top: 20px;
}
.alert {
padding: 10px 15px;
border-radius: 4px;
margin: 10px 0;
display: none;
}
.alert-success {
background-color: rgba(16, 185, 129, 0.2);
border: 1px solid #10b981;
color: #10b981;
}
.alert-error {
background-color: rgba(239, 68, 68, 0.2);
border: 1px solid #ef4444;
color: #ef4444;
}
.toast {
position: fixed;
top: 20px;
right: 20px;
max-width: 350px;
padding: 15px;
border-radius: 5px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
z-index: 1000;
opacity: 0;
transition: opacity 0.3s ease;
}
.toast-success {
background-color: #10b981;
color: white;
}
.toast-error {
background-color: #ef4444;
color: white;
}
.toast-visible {
opacity: 1;
}
.action-btn {
background-color: #374151;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
.start-btn {
background-color: #10b981;
}
.start-btn:hover {
background-color: #059669;
}
.pause-btn {
background-color: #f59e0b;
}
.pause-btn:hover {
background-color: #d97706;
}
</style>
</head>
<body class="bg-gray-900 p-4 text-white font-sans">
{{template "views/partials/menu"}}
<!-- Toast for notifications -->
<div id="toast" class="toast">
<span id="toast-message"></span>
</div>
<div class="max-w-6xl mx-auto">
<header class="text-center mb-8">
<h1 class="text-3xl md:text-5xl font-bold">Smart Agent List</h1>
@@ -55,7 +126,7 @@
<!-- Dynamic agent rows go here -->
{{ $status := .Status }}
{{ range .Agents }}
<tr hx-ext="sse">
<tr hx-ext="sse" data-agent-name="{{.}}">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-300">{{.}}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
Online: {{ index $status . }}
@@ -69,14 +140,24 @@
</a>
</td>
<td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
<button hx-put="/start/{{.}}">
<button class="action-btn start-btn"
hx-put="/start/{{.}}"
hx-swap="none"
hx-ext="json-enc"
data-action="start"
data-agent="{{.}}">
Start
</button>
</button>
</td>
<td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
<button hx-put="/pause/{{.}}">
<button class="action-btn pause-btn"
hx-put="/pause/{{.}}"
hx-swap="none"
hx-ext="json-enc"
data-action="pause"
data-agent="{{.}}">
Pause
</button>
</button>
</td>
<td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
<a href="/settings/{{.}}" class="text-indigo-500 hover:text-indigo-400">
@@ -93,19 +174,131 @@
</section>
<footer class="mt-8 text-center">
<!-- File Upload Form -->
<div class="section-box">
<form id='form' hx-encoding='multipart/form-data' hx-post='/settings/import'>
<h2>Import</h2>
<label for="file">File:</label>
<input type='file' name='file' id='file'>
<button type="submit">Upload File</button>
<progress id='progress' value='0' max='100'></progress>
</form>
</div>
<!-- File Upload Form -->
<div class="section-box">
<h2 class="text-2xl font-bold mb-4">Import Agent</h2>
<!-- Response Messages Container -->
<div id="response-container">
<!-- Success Alert -->
<div id="success-alert" class="alert alert-success">
Agent imported successfully! The page will refresh in a moment.
</div>
<!-- Error Alert -->
<div id="error-alert" class="alert alert-error">
<span id="error-message">Error importing agent.</span>
</div>
</div>
<form id='import-form' hx-encoding='multipart/form-data' hx-post='/settings/import' hx-target="#response-container" hx-swap="none">
<div class="mb-4">
<label for="file" class="block text-gray-300 mb-2">Select Agent File:</label>
<input type='file' name='file' id='file' class="bg-gray-700 text-white rounded p-2 w-full">
</div>
<div class="flex items-center">
<button id="import-button" type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded transition duration-300 ease-in-out">
Import Agent
</button>
<progress id='progress' value='0' max='100' class="ml-4"></progress>
</div>
</form>
</div>
</footer>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Handle import form submission
document.getElementById('import-form').addEventListener('htmx:afterRequest', function(event) {
const xhr = event.detail.xhr;
const successAlert = document.getElementById('success-alert');
const errorAlert = document.getElementById('error-alert');
const errorMessage = document.getElementById('error-message');
// Hide both alerts initially
successAlert.style.display = 'none';
errorAlert.style.display = 'none';
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
if (response.status === "ok") {
// Show success message
successAlert.style.display = 'block';
// Refresh the page after a short delay
setTimeout(() => {
window.location.reload();
}, 2000);
} else if (response.error) {
// Show error message
errorMessage.textContent = response.error;
errorAlert.style.display = 'block';
}
} catch (e) {
// Handle parsing error
errorMessage.textContent = "Invalid response format";
errorAlert.style.display = 'block';
}
} else {
// Handle HTTP error
errorMessage.textContent = "Server error: " + xhr.status;
errorAlert.style.display = 'block';
}
});
// Add event listeners for Start and Pause buttons
document.querySelectorAll('.action-btn').forEach(button => {
button.addEventListener('htmx:afterRequest', function(event) {
const xhr = event.detail.xhr;
const action = this.getAttribute('data-action');
const agent = this.getAttribute('data-agent');
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
if (response.status === "ok") {
// Show success toast
showToast(`Agent "${agent}" ${action === 'start' ? 'started' : 'paused'} successfully`, 'success');
// Update the status cell if needed
updateAgentStatus(agent, action === 'start' ? true : false);
} else if (response.error) {
// Show error toast
showToast(`Error: ${response.error}`, 'error');
}
} catch (e) {
// Handle parsing error
showToast("Invalid response format", 'error');
}
} else {
// Handle HTTP error
showToast(`Server error: ${xhr.status}`, 'error');
}
});
});
});
// Function to update agent status in the UI
function updateAgentStatus(agentName, isOnline) {
// Find the row for this agent
const rows = document.querySelectorAll('tr[data-agent-name]');
rows.forEach(row => {
if (row.getAttribute('data-agent-name') === agentName) {
// Find status cell (second cell in the row)
const statusCell = row.querySelector('td:nth-child(2)');
if (statusCell) {
// Update the "Online:" text
const statusText = statusCell.firstChild;
statusText.textContent = `Online: ${isOnline}`;
}
}
});
}
</script>
</body>
</html>
</html>

View File

@@ -6,13 +6,33 @@
<script src="https://unpkg.com/htmx.org"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/sse.js"></script>
<script src="https://unpkg.com/hyperscript.org@0.9.12"></script>
<style>
.alert {
padding: 12px 16px;
border-radius: 4px;
margin-bottom: 20px;
display: none;
}
.alert-success {
background-color: rgba(16, 185, 129, 0.2);
border: 1px solid #10b981;
color: #10b981;
}
.alert-error {
background-color: rgba(239, 68, 68, 0.2);
border: 1px solid #ef4444;
color: #ef4444;
}
</style>
</head>
<body class="bg-gray-900 p-4 text-white font-sans">
{{template "views/partials/menu"}}
<div class="max-w-2xl mx-auto my-12 bg-gray-800 p-8 rounded-lg shadow-lg">
<h1 class="text-3xl font-bold text-center mb-10 text-blue-400">Create New Agent</h1>
<h1 class="text-3xl font-bold text-center mb-6 text-blue-400">Create New Agent</h1>
<form action="/create" method="POST" class="space-y-6">
<form id="create-agent-form" action="/create" method="POST" class="space-y-6">
<div class="mb-6">
<label for="name" class="block text-lg font-medium text-gray-400">Name</label>
@@ -153,11 +173,89 @@
</div>
<div class="flex items-center justify-between">
<button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-500 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
<button type="submit" id="create-button" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-500 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
Create Agent
</button>
</div>
</form>
</div>
</div>
<!-- Response Messages Container -->
<div id="response-container">
<!-- Success Alert -->
<div id="success-alert" class="alert alert-success">
Agent created successfully! Redirecting to agent list...
</div>
<!-- Error Alert -->
<div id="error-alert" class="alert alert-error">
<span id="error-message">Error creating agent.</span>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Convert regular form to use HTMX
const form = document.getElementById('create-agent-form');
// Add HTMX attributes to the form
form.setAttribute('hx-post', '/create');
form.setAttribute('hx-swap', 'none');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Get form data
const formData = new FormData(form);
// Send the form data using fetch API
fetch('/create', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
const successAlert = document.getElementById('success-alert');
const errorAlert = document.getElementById('error-alert');
const errorMessage = document.getElementById('error-message');
// Hide both alerts initially
successAlert.style.display = 'none';
errorAlert.style.display = 'none';
if (data.status === "ok") {
// Show success message
successAlert.style.display = 'block';
// Redirect to agent list page after a delay
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else if (data.error) {
// Show error message
errorMessage.textContent = data.error;
errorAlert.style.display = 'block';
// Scroll to the error message
errorAlert.scrollIntoView({ behavior: 'smooth', block: 'center' });
} else {
// Handle unexpected response format
errorMessage.textContent = "Unexpected response format";
errorAlert.style.display = 'block';
}
})
.catch(error => {
// Handle network or other errors
const errorAlert = document.getElementById('error-alert');
const errorMessage = document.getElementById('error-message');
errorMessage.textContent = "Network error: " + error.message;
errorAlert.style.display = 'block';
errorAlert.scrollIntoView({ behavior: 'smooth', block: 'center' });
});
});
});
</script>
</div>
</body>
</html>

View File

@@ -220,4 +220,29 @@ select::-webkit-scrollbar-thumb {
}
</style>
</style>
<script>
// Function to show toast notifications
function showToast(message, type) {
const toast = document.getElementById('toast');
const toastMessage = document.getElementById('toast-message');
// Set message
toastMessage.textContent = message;
// Set toast type (success/error)
toast.className = 'toast';
toast.classList.add(type === 'success' ? 'toast-success' : 'toast-error');
// Show toast
setTimeout(() => {
toast.classList.add('toast-visible');
}, 100);
// Hide toast after 3 seconds
setTimeout(() => {
toast.classList.remove('toast-visible');
}, 3000);
}
</script>

View File

@@ -41,46 +41,185 @@
button:hover {
background-color: #5a86b8;
}
/* Toast notification styles */
.toast {
position: fixed;
top: 20px;
right: 20px;
max-width: 350px;
padding: 15px;
border-radius: 5px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
z-index: 1000;
opacity: 0;
transition: opacity 0.3s ease;
}
.toast-success {
background-color: #10b981;
color: white;
}
.toast-error {
background-color: #ef4444;
color: white;
}
.toast-visible {
opacity: 1;
}
/* Action button styles */
.action-button {
margin-bottom: 10px;
display: inline-block;
width: auto;
margin-right: 10px;
}
.start-button {
background-color: #10b981; /* Green */
}
.start-button:hover {
background-color: #059669;
}
.pause-button {
background-color: #f59e0b; /* Orange */
}
.pause-button:hover {
background-color: #d97706;
}
.delete-button {
background-color: #ef4444; /* Red */
color: white;
padding: 10px 15px;
border-radius: 5px;
text-decoration: none;
display: inline-block;
cursor: pointer;
}
.delete-button:hover {
background-color: #dc2626;
}
</style>
</head>
<body>
{{template "views/partials/menu"}}
<!-- Toast for notifications -->
<div id="toast" class="toast">
<span id="toast-message"></span>
</div>
<header class="text-center mb-8">
<h1 class="text-3xl md:text-5xl font-bold">Agent settings - {{.Name}}</h1>
</header>
<div class="max-w-4xl mx-auto">
<a href="/knowledgebase/{{.Name}}" class="card-link">
<div class="card">
<h2>Manage Knowledgebase</h2>
<p>Access and update your knowledgebase to improve agent responses and efficiency.</p>
</div>
</a>
<div class="section-box">
<button hx-put="/start/{{.Name}}" class="text-indigo-500 hover:text-indigo-400">
Start
<h2 class="mb-4">Agent Control</h2>
<button
class="action-button start-button"
hx-put="/start/{{.Name}}"
hx-swap="none"
data-action="start"
data-agent="{{.Name}}">
Start Agent
</button>
<button hx-put="/pause/{{.Name}}" class="text-indigo-500 hover:text-indigo-400">
Pause
<button
class="action-button pause-button"
hx-put="/pause/{{.Name}}"
hx-swap="none"
data-action="pause"
data-agent="{{.Name}}">
Pause Agent
</button>
</div>
<div class="section-box">
<h2>Export</h2>
<a href="/settings/export/{{.Name}}" >Export</a>
<h2>Export</h2>
<a href="/settings/export/{{.Name}}" class="action-button">Export</a>
</div>
<div class="section-box">
<h2>Danger section</h2>
<a href="/delete/{{.Name}}" class="text-red-500 hover:text-red-400">
<i class="fas fa-trash-alt"></i> Delete
</a>
<button
class="delete-button"
hx-delete="/delete/{{.Name}}"
hx-swap="none"
data-action="delete"
data-agent="{{.Name}}">
<i class="fas fa-trash-alt"></i> Delete Agent
</button>
</div>
</div>
<script>
htmx.on('#form', 'htmx:xhr:progress', function(evt) {
htmx.find('#progress').setAttribute('value', evt.detail.loaded / evt.detail.total * 100);
document.addEventListener('DOMContentLoaded', function() {
// Add event listeners for action buttons (Start, Pause)
document.querySelectorAll('.action-button').forEach(button => {
button.addEventListener('htmx:afterRequest', function(event) {
handleActionResponse(event, this);
});
});
// Add event listener for delete button
document.querySelector('.delete-button').addEventListener('htmx:afterRequest', function(event) {
handleActionResponse(event, this);
});
});
// Function to handle API responses for all actions
function handleActionResponse(event, button) {
const xhr = event.detail.xhr;
const action = button.getAttribute('data-action');
const agent = button.getAttribute('data-agent');
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
if (response.status === "ok") {
// Action successful
let message = "";
switch(action) {
case 'start':
message = `Agent "${agent}" started successfully`;
break;
case 'pause':
message = `Agent "${agent}" paused successfully`;
break;
case 'delete':
message = `Agent "${agent}" deleted successfully`;
break;
default:
message = "Operation completed successfully";
}
// Show success message
showToast(message, 'success');
// Redirect to agent list page after short delay
setTimeout(() => {
window.location.href = "/agents";
}, 2000);
} else if (response.error) {
// Show error message
showToast(`Error: ${response.error}`, 'error');
}
} catch (e) {
// Handle JSON parsing error
showToast("Invalid response format", 'error');
}
} else {
// Handle HTTP error
showToast(`Server error: ${xhr.status}`, 'error');
}
}
</script>
</body>
</html>
</html>