Skip to content

Agent Zero AI framework

feat: TaskScheduler - frontend tabbed display chats tasks

Rafael Uzarowski525c1c13f851
diff --git a/python/api/poll.py b/python/api/poll.py
index a7e61ddcf..d51ec2d53 100644
--- a/python/api/poll.py
+++ b/python/api/poll.py
@@ -3,6 +3,9 @@ from flask import Request, Response
from agent import AgentContext
+from python.helpers import persist_chat
+
+
class Poll(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
ctxid = input.get("context", None)
@@ -15,27 +18,47 @@ class Poll(ApiHandler):
# loop AgentContext._contexts
ctxs = []
+ tasks = []
+ processed_contexts = set() # Track processed context IDs
+
+ # First, identify all tasks
for ctx in AgentContext._contexts.values():
- ctxs.append(
- {
- "id": ctx.id,
- "name": ctx.name,
- "no": ctx.no,
- "log_guid": ctx.log.guid,
- "log_version": len(ctx.log.updates),
- "log_length": len(ctx.log.logs),
- "paused": ctx.paused,
- }
- )
+ # Skip if already processed
+ if ctx.id in processed_contexts:
+ continue
+
+ context_data = {
+ "id": ctx.id,
+ "name": ctx.name,
+ "no": ctx.no,
+ "log_guid": ctx.log.guid,
+ "log_version": len(ctx.log.updates),
+ "log_length": len(ctx.log.logs),
+ "paused": ctx.paused,
+ }
+
+ # Determine if this is a task using multiple methods
+ ctx_path = persist_chat.get_chat_folder_path(ctx.id)
+ is_task = (ctx_path and persist_chat.TASKS_FOLDER in ctx_path)
+
+ # Add to the appropriate list
+ if is_task:
+ tasks.append(context_data)
+ else:
+ ctxs.append(context_data)
+
+ # Mark as processed
+ processed_contexts.add(ctx.id)
# data from this server
return {
"context": context.id,
"contexts": ctxs,
+ "tasks": tasks,
"logs": logs,
"log_guid": context.log.guid,
"log_version": len(context.log.updates),
"log_progress": context.log.progress,
"log_progress_active": context.log.progress_active,
"paused": context.paused,
- }
\ No newline at end of file
+ }
diff --git a/python/helpers/chat_names.py b/python/helpers/chat_names.py
new file mode 100644
index 000000000..ef414cabf
--- /dev/null
+++ b/python/helpers/chat_names.py
@@ -0,0 +1,137 @@
+import json
+import os
+import time
+from typing import Dict, Any
+
+from python.helpers import files
+
+
+class ChatNames:
+ _instance = None
+ _names_file = "chat_names.json"
+ _metadata_file = "chat_metadata.json"
+
+ @classmethod
+ def get_instance(cls):
+ if cls._instance is None:
+ cls._instance = ChatNames()
+ cls._instance._names_file = files.get_abs_path("tmp") + "/" + cls._names_file
+ cls._instance._metadata_file = files.get_abs_path("tmp") + "/" + cls._metadata_file
+ return cls._instance
+
+ def _read_names(self) -> dict:
+ """Read current names from file"""
+ try:
+ if os.path.exists(self._names_file):
+ with open(self._names_file, 'r') as f:
+ return json.load(f)
+ except Exception as e:
+ print(f"Error reading chat names: {e}")
+ return {}
+
+ def _save_names(self, names: dict):
+ """Save names to file"""
+ try:
+ with open(self._names_file, 'w') as f:
+ json.dump(names, f, indent=2)
+ except Exception as e:
+ print(f"Error saving chat names: {e}")
+
+ def _read_metadata(self) -> dict:
+ """Read context metadata from file"""
+ try:
+ if os.path.exists(self._metadata_file):
+ with open(self._metadata_file, 'r') as f:
+ return json.load(f)
+ except Exception as e:
+ print(f"Error reading context metadata: {e}")
+ return {}
+
+ def _save_metadata(self, metadata: dict):
+ """Save metadata to file"""
+ try:
+ with open(self._metadata_file, 'w') as f:
+ json.dump(metadata, f, indent=2)
+ except Exception as e:
+ print(f"Error saving context metadata: {e}")
+
+ def set_name(self, chat_id: str, name: str):
+ """Set name for a chat/task"""
+ names = self._read_names()
+ names[chat_id] = name
+ self._save_names(names)
+
+ # Also update the name in metadata if it exists
+ self.update_metadata(chat_id, {"name": name})
+
+ def get_name(self, chat_id: str) -> str:
+ """Get name for a chat/task"""
+ names = self._read_names()
+ return names.get(chat_id, f"Chat #{chat_id[:8]}")
+
+ def set_metadata(self, chat_id: str, metadata_dict: Dict[str, Any]):
+ """Set complete metadata for a chat/task"""
+ all_metadata = self._read_metadata()
+
+ # Ensure we have created_at timestamp if not provided
+ if "created_at" not in metadata_dict:
+ metadata_dict["created_at"] = int(time.time())
+
+ all_metadata[chat_id] = metadata_dict
+ self._save_metadata(all_metadata)
+
+ # Also update the name in the names file for backward compatibility
+ if "name" in metadata_dict:
+ self.set_name(chat_id, metadata_dict["name"])
+
+ def update_metadata(self, chat_id: str, metadata_update: Dict[str, Any]):
+ """Update specific metadata fields for a chat/task"""
+ all_metadata = self._read_metadata()
+
+ if chat_id in all_metadata:
+ all_metadata[chat_id].update(metadata_update)
+ else:
+ # Initialize with current timestamp if creating new metadata
+ metadata_update["created_at"] = metadata_update.get("created_at", int(time.time()))
+ all_metadata[chat_id] = metadata_update
+
+ self._save_metadata(all_metadata)
+
+ def get_metadata(self, chat_id: str) -> Dict[str, Any]:
+ """Get metadata for a chat/task"""
+ all_metadata = self._read_metadata()
+
+ # Return metadata if it exists
+ if chat_id in all_metadata:
+ return all_metadata[chat_id]
+
+ # Otherwise create default metadata with just the name
+ name = self.get_name(chat_id)
+ default_metadata = {
+ "name": name,
+ "created_at": int(time.time()) # Current time as fallback
+ }
+ return default_metadata
+
+ def get_created_at(self, chat_id: str) -> int:
+ """Get creation timestamp for a chat/task"""
+ metadata = self.get_metadata(chat_id)
+ return metadata.get("created_at", 0)
+
+ def remove_chat(self, chat_id: str):
+ """Remove chat/task and its metadata"""
+ print("Removing chat name and metadata: ", chat_id)
+
+ # Remove from names file
+ names = self._read_names()
+ if chat_id in names:
+ del names[chat_id]
+ print("Chat name removed: ", chat_id)
+ self._save_names(names)
+
+ # Remove from metadata file
+ metadata = self._read_metadata()
+ if chat_id in metadata:
+ del metadata[chat_id]
+ print("Chat metadata removed: ", chat_id)
+ self._save_metadata(metadata)
diff --git a/python/helpers/persist_chat.py b/python/helpers/persist_chat.py
index 6ddeafe1a..ce81a1293 100644
--- a/python/helpers/persist_chat.py
+++ b/python/helpers/persist_chat.py
@@ -9,27 +9,30 @@ from initialize import initialize
from python.helpers.log import Log, LogItem
CHATS_FOLDER = "tmp/chats"
+TASKS_FOLDER = "tmp/task_chats"
LOG_SIZE = 1000
CHAT_FILE_NAME = "chat.json"
-def get_chat_folder_path(ctxid: str):
- return files.get_abs_path(CHATS_FOLDER, ctxid)
+def get_chat_folder_path(ctxid: str, folder: str = CHATS_FOLDER):
+ return files.get_abs_path(folder, ctxid)
-def save_tmp_chat(context: AgentContext):
- path = _get_chat_file_path(context.id)
+
+def save_tmp_chat(context: AgentContext, folder: str = CHATS_FOLDER):
+ path = _get_chat_file_path(context.id, folder)
files.make_dirs(path)
data = _serialize_context(context)
js = _safe_json_serialize(data, ensure_ascii=False)
files.write_file(path, js)
-def load_tmp_chats():
- _convert_v080_chats()
- folders = files.list_files(CHATS_FOLDER, "*")
+def load_tmp_chats(folder: str = CHATS_FOLDER):
+ if folder == CHATS_FOLDER:
+ _convert_v080_chats()
+ folders = files.list_files(folder, "*")
json_files = []
- for folder in folders:
- json_files.append(_get_chat_file_path(folder))
+ for folder_name in folders:
+ json_files.append(_get_chat_file_path(folder_name, folder))
ctxids = []
for file in json_files:
@@ -43,8 +46,8 @@ def load_tmp_chats():
return ctxids
-def _get_chat_file_path(ctxid: str):
- return files.get_abs_path(CHATS_FOLDER, ctxid, CHAT_FILE_NAME)
+def _get_chat_file_path(ctxid: str, folder: str = CHATS_FOLDER):
+ return files.get_abs_path(folder, ctxid, CHAT_FILE_NAME)
def _convert_v080_chats():
@@ -52,12 +55,11 @@ def _convert_v080_chats():
for file in json_files:
path = files.get_abs_path(CHATS_FOLDER, file)
name = file.rstrip(".json")
- fold = files.get_abs_path(CHATS_FOLDER, name)
new = _get_chat_file_path(name)
files.move_file(path, new)
-def load_json_chats(jsons: list[str]):
+def load_json_chats(jsons: list[str], folder: str = CHATS_FOLDER):
ctxids = []
for js in jsons:
data = json.loads(js)
@@ -74,9 +76,25 @@ def export_json_chat(context: AgentContext):
return js
-def remove_chat(ctxid):
- files.delete_dir(get_chat_folder_path(ctxid))
+def remove_chat(ctxid, folder: str = CHATS_FOLDER):
+ files.delete_dir(get_chat_folder_path(ctxid, folder))
+
+
+# Task-specific functions for convenience
+def save_tmp_task(context: AgentContext):
+ save_tmp_chat(context, TASKS_FOLDER)
+
+
+def load_tmp_tasks():
+ return load_tmp_chats(TASKS_FOLDER)
+
+
+def load_json_tasks(jsons: list[str]):
+ return load_json_chats(jsons, TASKS_FOLDER)
+
+def remove_task(ctxid):
+ remove_chat(ctxid, TASKS_FOLDER)
def _serialize_context(context: AgentContext):
diff --git a/python/helpers/task_scheduler.py b/python/helpers/task_scheduler.py
index f3e4a5641..bda20d0d0 100644
--- a/python/helpers/task_scheduler.py
+++ b/python/helpers/task_scheduler.py
@@ -14,14 +14,13 @@ from pydantic import BaseModel, Field, PrivateAttr
from python.helpers.files import get_abs_path, exists, write_file, read_file, make_dirs
from agent import Agent, AgentContext, UserMessage
from initialize import initialize
-from python.helpers.persist_chat import export_json_chat, load_json_chats
+from python.helpers.persist_chat import export_json_chat, load_json_chats, load_tmp_chats, save_tmp_chat
from python.helpers.print_style import PrintStyle
from python.helpers.defer import DeferredTask
-from python.helpers.persist_chat import CHATS_FOLDER
+from python.helpers.persist_chat import CHATS_FOLDER, TASKS_FOLDER
from python.helpers import errors
SCHEDULER_FOLDER = "memory/scheduler"
-TASKS_FOLDER = CHATS_FOLDER
class TaskSchedule(BaseModel):
@@ -37,7 +36,7 @@ class TaskSchedule(BaseModel):
class AdHocTask(BaseModel):
uuid: str = Field(default_factory=lambda: str(uuid.uuid4()))
- state: Literal["idle", "running"] = Field(default="idle")
+ state: Literal["idle", "running", "disabled"] = Field(default="idle")
name: str = Field()
system_prompt: str
prompt: str
@@ -71,7 +70,7 @@ class AdHocTask(BaseModel):
def update(self,
name: str | None = None,
- state: Literal["idle", "running"] | None = None,
+ state: Literal["idle", "running", "disabled"] | None = None,
system_prompt: str | None = None,
prompt: str | None = None,
attachments: list[str] | None = None,
@@ -107,7 +106,7 @@ class AdHocTask(BaseModel):
class ScheduledTask(BaseModel):
uuid: str = Field(default_factory=lambda: str(uuid.uuid4()))
- state: Literal["idle", "running"] = Field(default="idle")
+ state: Literal["idle", "running", "disabled"] = Field(default="idle")
name: str
schedule: TaskSchedule
system_prompt: str
@@ -141,7 +140,7 @@ class ScheduledTask(BaseModel):
def update(self,
name: str | None = None,
- state: Literal["idle", "running"] | None = None,
+ state: Literal["idle", "running", "disabled"] | None = None,
system_prompt: str | None = None,
prompt: str | None = None,
attachments: list[str] | None = None,
@@ -277,44 +276,55 @@ class TaskScheduler:
config = initialize()
context: AgentContext = AgentContext(config)
context.id = task.uuid
- chat_json = export_json_chat(context)
- chat_file = get_abs_path(TASKS_FOLDER, task.uuid, "chat.json")
- make_dirs(chat_file)
- write_file(chat_file, chat_json)
+ # chat_json = export_json_chat(context)
+ # chat_file = get_abs_path(TASKS_FOLDER, task.uuid, "chat.json")
+ # make_dirs(chat_file)
+ # write_file(chat_file, chat_json)
+ save_tmp_chat(context, TASKS_FOLDER)
return context
async def _get_chat_context(self, task: Union[ScheduledTask, AdHocTask]) -> AgentContext:
- chat_file = get_abs_path(TASKS_FOLDER, task.uuid, "chat.json")
- if exists(chat_file):
- chat = read_file(chat_file)
- context = AgentContext.get(load_json_chats([chat])[0])
+ ctxids = load_tmp_chats(TASKS_FOLDER)
+ # chat_file = get_abs_path(TASKS_FOLDER, task.uuid, "chat.json")
+ # if exists(chat_file):
+ if task.uuid in ctxids:
+ # chat = read_file(chat_file)
+ context = AgentContext.get(task.uuid)
if isinstance(context, AgentContext):
self._printer.print(
- f"Scheduler Task {task.name} loaded from chat {task.uuid}"
+ f"Scheduler Task {task.name} loaded from task {task.uuid}, context ok"
)
+ context.id = task.uuid
+ save_tmp_chat(context, TASKS_FOLDER)
return context
else:
self._printer.print(
- f"Scheduler Task {task.name} loaded from chat {task.uuid} but failed to load context"
+ f"Scheduler Task {task.name} loaded from task {task.uuid} but failed to load context"
)
return await self.__new_context(task)
else:
self._printer.print(
- f"Scheduler Task {task.name} loaded from chat {task.uuid} but chat file not found"
+ f"Scheduler Task {task.name} loaded from task {task.uuid} but context not found"
)
return await self.__new_context(task)
async def _persist_chat(self, task: Union[ScheduledTask, AdHocTask], context: AgentContext):
- chat_json = export_json_chat(context)
- chat_file = get_abs_path(TASKS_FOLDER, task.uuid, "chat.json")
- make_dirs(chat_file)
- write_file(chat_file, chat_json)
+ # chat_json = export_json_chat(context)
+ # chat_file = get_abs_path(TASKS_FOLDER, task.uuid, "chat.json")
+ # make_dirs(chat_file)
+ # write_file(chat_file, chat_json)
+ context.id = task.uuid
+ save_tmp_chat(context, TASKS_FOLDER)
async def _run_task(self, task: Union[ScheduledTask, AdHocTask]):
async def _run_task_wrapper(task: Union[ScheduledTask, AdHocTask]):
+ if task.state != "idle":
+ self._printer.print(f"Scheduler Task {task.name} state is '{task.state}', skipping")
+ return
+
if task.state == "running":
- self._printer.print(f"Scheduler Task {task.name} already running")
+ self._printer.print(f"Scheduler Task {task.name} already running, skipping")
return
try:
@@ -359,7 +369,7 @@ class TaskScheduler:
result = await agent.monologue()
task.update(last_result="SUCCESS: " + result)
- self._printer.print(f"Scheduler Task {task.name} completed: {result}")
+ self._printer.print(f"Scheduler Task '{task.name}' completed: {result}")
await self._persist_chat(task, context)
diff --git a/run_ui.py b/run_ui.py
index 6ba620e97..da5e46c84 100644
--- a/run_ui.py
+++ b/run_ui.py
@@ -11,7 +11,6 @@ from python.helpers.extract_tools import load_classes_from_folder
from python.helpers.api import ApiHandler
from python.helpers.print_style import PrintStyle
import sys
-import asyncio
import socket
import struct
@@ -168,6 +167,9 @@ def run():
# initialize contexts from persisted chats
persist_chat.load_tmp_chats()
+ # initialize contexts from persisted tasks
+ persist_chat.load_tmp_tasks()
+
except Exception as e:
PrintStyle().error(errors.format_error(e))
diff --git a/webui/index.css b/webui/index.css
index 95b355f2c..aa36d293b 100644
--- a/webui/index.css
+++ b/webui/index.css
@@ -208,8 +208,57 @@ body,
}
/* Chats container */
+.chat-container {
+ display: flex;
+ align-items: center;
+ position: relative;
+ width: 100%;
+ min-height: 30px;
+ gap: 0;
+}
+
.chat-list-button {
+ display: block;
+ width: 100%;
+ padding: 1px 5px;
+ cursor: pointer;
+ overflow: hidden;
+ position: relative;
+ transition: background-color 0.2s;
+ border-radius: 4px;
+}
+
+/* Subtle background on hover for the entire row */
+.chat-list-button:hover {
+ background-color: rgba(255, 255, 255, 0.03);
+}
+
+.light-mode .chat-list-button:hover {
+ background-color: rgba(0, 0, 0, 0.02);
+}
+
+.chat-name {
+ display: inline-block;
+ max-width: 160px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
cursor: pointer;
+ padding: 3px 8px;
+ border-radius: 4px;
+ transition: background-color 0.2s;
+ margin-right: 60px; /* Make space for buttons */
+ font-size: var(--font-size-small); /* Match config button font size */
+}
+
+/* Add a nice hover effect to just the chat name */
+.chat-name:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+ text-decoration: none;
+}
+
+.light-mode .chat-name:hover {
+ background-color: rgba(0, 0, 0, 0.05);
}
.chats-list-container {
@@ -232,12 +281,26 @@ body,
background: linear-gradient(to bottom, calc(100% - 20px), transparent 100%);
/* Add padding to account for fade */
padding-bottom: 20px;
- scrollbar-width: none;
- -ms-overflow-style: none;
+ scrollbar-width: thin;
+ -ms-overflow-style: auto;
}
.chats-list-container::-webkit-scrollbar {
- width: 0px;
+ width: 5px;
+}
+
+.chats-list-container::-webkit-scrollbar-track {
+ background: rgba(0, 0, 0, 0.2);
+ border-radius: 6px;
+}
+
+.chats-list-container::-webkit-scrollbar-thumb {
+ background-color: var(--color-border);
+ border-radius: 6px;
+}
+
+.chats-list-container::-webkit-scrollbar-thumb:hover {
+ background-color: var(--color-border);
}
/* Chats Section */
@@ -247,7 +310,7 @@ body,
flex-direction: column;
min-height: 0;
flex: 1;
- margin-top: 1.5rem;
+ margin-top: 0.5rem;
}
/* Preferences */
@@ -1178,7 +1241,7 @@ pre {
}
.text-button:active {
- opacity: 0.5;
+ opacity: 0.5;
}
.text-button svg {
@@ -1588,7 +1651,7 @@ input:checked + .slider:before {
display: table;
gap: 0.1rem !important;
}
-
+
.text-button {
max-height: 25px;
}
@@ -1603,7 +1666,7 @@ input:checked + .slider:before {
margin-left: var(--spacing-md);
margin-bottom: var(--spacing-md);
}
-
+
.msg-kvps {
display: flex;
flex-direction: column;
@@ -1669,7 +1732,7 @@ input:checked + .slider:before {
.sidebar-overlay.visible {
display: block;
}
-}
+}
@media (max-width: 768px) {
#left-panel {
@@ -1699,15 +1762,15 @@ input:checked + .slider:before {
-webkit-transition: all 0.3s ease;
transition: all 0.3s ease;
}
-
+
#right-panel.expanded #logo-container {
margin-left: 4.6rem;
}
-
+
#input-section {
align-items: start;
}
-
+
.text-buttons-row {
width: 90%;
display: flex;
@@ -1786,7 +1849,7 @@ input:checked + .slider:before {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
-
+
#chats-section {
min-height: 100%;
}
@@ -2095,4 +2158,265 @@ a:active {
/* Alpine cloak to prevent FOUC */
[x-cloak] {
display: none !important;
-}
\ No newline at end of file
+}
+
+/* Add new styles for reasoning and deepsearchbutton */
+.ml-auto {
+ margin-left: auto;
+}
+
+/* Remove unnecessary specific media query that was causing issues */
+@media (max-width: 480px) {
+ .text-button svg {
+ width: 16px;
+ height: 16px;
+ }
+}
+
+/* Add to the existing .chat-actions class or create it */
+.chat-actions {
+ display: flex;
+ gap: 5px;
+ position: absolute;
+ right: 5px;
+ top: 50%;
+ transform: translateY(-50%);
+ z-index: 2; /* Ensure buttons are above the edit field */
+ min-width: 70px; /* Ensure minimum width for the buttons */
+ justify-content: flex-end;
+}
+
+/* Tasks list container - similar to chats list */
+.tasks-list-container {
+ max-height: 300px;
+ overflow-y: auto;
+ margin-top: 10px;
+ padding-right: 5px;
+ border-radius: 5px;
+ position: relative;
+ scrollbar-width: thin;
+ -ms-overflow-style: auto;
+}
+
+.tasks-list-container::-webkit-scrollbar {
+ width: 5px;
+}
+
+.tasks-list-container::-webkit-scrollbar-track {
+ background: rgba(0, 0, 0, 0.2);
+ border-radius: 6px;
+}
+
+.tasks-list-container::-webkit-scrollbar-thumb {
+ background-color: var(--color-border);
+ border-radius: 6px;
+}
+
+.tasks-list-container::-webkit-scrollbar-thumb:hover {
+ background-color: var(--color-border);
+}
+
+.task-name {
+ display: inline-block;
+ max-width: 160px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ cursor: pointer;
+ padding: 3px 5px;
+ border-radius: 4px;
+ transition: background-color 0.2s;
+ margin-right: 60px; /* Make space for future buttons */
+ font-size: var(--font-size-small); /* Match config button font size */
+}
+
+.task-name:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+ text-decoration: none;
+}
+
+.light-mode .task-name:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+}
+
+/* Dark mode overrides */
+.light-mode .tab.active {
+ color: var(--highlight-pink);
+}
+
+.light-mode .tab.active::after {
+ background-color: var(--highlight-pink);
+ box-shadow: 0 0 8px var(--highlight-pink);
+}
+/* Tabs styling */
+.tabs-container {
+ width: 100%;
+ margin-bottom: 8px; /* Reduced spacing between tabs and list */
+ padding: 0;
+ margin-top: 20px; /* Increased spacing from elements above */
+}
+
+.tabs {
+ display: flex;
+ width: 100%;
+ position: relative;
+ gap: 5px;
+ border-bottom: 3px solid var(--color-border); /* Thicker bottom line */
+ justify-content: center; /* Center the tabs */
+}
+
+.tab {
+ padding: 8px 16px;
+ cursor: pointer;
+ position: relative;
+ color: var(--color-text);
+ border: 2px solid var(--color-border);
+ border-bottom: none;
+ border-radius: 8px 8px 0 0;
+ transition: all 0.3s ease;
+ background-color: var(--color-panel);
+ margin-bottom: -3px; /* Match the thicker border */
+ z-index: 1;
+}
+
+.tab:not(.active) {
+ opacity: 0.8;
+ border-bottom: 3px solid var(--color-border);
+ background-color: rgba(255, 255, 255, 0.03);
+}
+
+.tab.active {
+ color: var(--color-primary);
+ border-color: var(--color-border);
+ box-shadow:
+ 0 -4px 8px -2px var(--color-border),
+ 4px 0 8px -2px var(--color-border),
+ -4px 0 8px -2px var(--color-border);
+ font-weight: bold;
+ background-color: var(--color-panel);
+}
+
+.light-mode .tab.active {
+ color: var(--color-primary);
+ box-shadow:
+ 0 -4px 8px -2px var(--color-border),
+ 4px 0 8px -2px var(--color-border),
+ -4px 0 8px -2px var(--color-border);
+}
+
+.light-mode .tab:not(.active) {
+ background-color: rgba(0, 0, 0, 0.03);
+}
+
+/* Remove previous tab styling that conflicts */
+.tab.active::after {
+ display: none;
+}
+
+/* Empty list message styling enhancement */
+.empty-list-message {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100px;
+ color: var(--color-secondary);
+ text-align: center;
+ opacity: 0.7;
+ font-style: italic;
+}
+
+.light-mode .empty-list-message {
+ color: var(--color-secondary-light);
+}
+
+/* Common scrollbar styling */
+::-webkit-scrollbar {
+ width: 5px;
+ height: 5px;
+}
+
+::-webkit-scrollbar-track {
+ background: rgba(0, 0, 0, 0.2);
+ border-radius: 6px;
+}
+
+::-webkit-scrollbar-thumb {
+ background-color: var(--color-border);
+ border-radius: 6px;
+ transition: background-color 0.2s ease;
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background-color: var(--color-border);
+}
+
+::-webkit-scrollbar-thumb:active {
+ background-color: var(--color-border);
+}
+
+/* Firefox scrollbar */
+* {
+ scrollbar-width: thin;
+ scrollbar-color: var(--color-border) rgba(0, 0, 0, 0.2);
+}
+
+/* Light mode scrollbar */
+.light-mode ::-webkit-scrollbar-track {
+ background: rgba(200, 200, 200, 0.3);
+}
+
+.light-mode ::-webkit-scrollbar-thumb {
+ background-color: var(--color-border);
+}
+
+.light-mode ::-webkit-scrollbar-thumb:hover {
+ background-color: var(--color-border);
+}
+
+.light-mode ::-webkit-scrollbar-thumb:active {
+ background-color: var(--color-border);
+}
+
+.light-mode * {
+ scrollbar-color: var(--color-border) rgba(200, 200, 200, 0.3);
+}
+
+/* Add specific styling for selected chat items */
+.chat-list-button.font-bold {
+ position: relative;
+ background-color: var(--color-border) 0.05;
+}
+
+.chat-list-button.font-bold::before {
+ content: '';
+ position: absolute;
+ left: 0;
+ top: 0;
+ height: 100%;
+ width: 3px;
+ background-color: var(--color-border);
+ border-top-left-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+
+.light-mode .chat-list-button.font-bold {
+ background-color: var(--color-border) 0.05;
+}
+
+.light-mode .chat-list-button.font-bold::before {
+ background-color: var(--color-border);
+}
+
+/* Add some padding to the list items to accommodate the stripe */
+.chat-list-button {
+ padding-left: 5px;
+ border-radius: 4px;
+ transition: background-color 0.2s ease-in-out;
+}
+
+/* Make sure the chat container has proper spacing */
+.chat-container, .task-container {
+ display: flex;
+ align-items: center;
+ width: 100%;
+}
diff --git a/webui/index.html b/webui/index.html
index f13dd1297..29a2a5a26 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -87,22 +87,57 @@
</svg>Settings</button>
</div>
+
+ <!-- Tabs container -->
+ <div class="tabs-container">
+ <div class="tabs">
+ <div class="tab active" id="chats-tab">Chats</div>
+ <div class="tab" id="tasks-tab">Tasks</div>
+ </div>
+ </div>
+
<!-- Chats List -->
<div class="config-section" id="chats-section" x-data="{ contexts: [], selected: '' }"
- x-show="contexts.length > 0">
- <h3>Chats</h3>
+ x-show="contexts.length > 0 || true">
<div class="chats-list-container">
- <ul class="config-list">
+ <ul class="config-list" x-show="contexts.length > 0">
<template x-for="context in contexts">
<li>
- <span :class="{'chat-list-button': true, 'font-bold': context.id === selected}"
+ <div :class="{'chat-list-button': true, 'font-bold': context.id === selected}"
@click="selected = context.id; selectChat(context.id)">
- <span x-text="context.name ? context.name : 'Chat #' + context.no"></span>
- </span>
+ <span class="chat-name" x-text="context.name ? context.name : 'Chat #' + context.no"></span>
+ </div>
<button class="edit-button" @click="killChat(context.id)">X</button>
</li>
</template>
</ul>
+ <div class="empty-list-message" x-show="contexts.length === 0">
+ <p><i>No chats to list.</i></p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tasks List -->
+ <div class="config-section" id="tasks-section" x-data="{ tasks: [], selected: '' }"
+ style="display: none;">
+ <div class="tasks-list-container">
+ <ul class="config-list" x-show="tasks.length > 0">
+ <template x-for="task in tasks">
+ <li>
+ <div :class="{'chat-list-button': true, 'font-bold': task.id === selected}"
+ @click="selected = task.id; selectChat(task.id)">
+ <div class="chat-container">
+ <span class="task-name"
+ x-text="task.name || `Task #${task.id.substring(0,8)}`"
+ :data-task-id="task.id"></span>
+ </div>
+ </div>
+ </li>
+ </template>
+ </ul>
+ <div class="empty-list-message" x-show="tasks.length === 0">
+ <p><i>No tasks to list.</i></p>
+ </div>
</div>
</div>
</div>
@@ -216,19 +251,19 @@
<span id="stop-speech" @click="window.speech.stop()" style="cursor: pointer">Stop Speech</span>
</h4>
</div>
- <div id="input-section" x-data="{
+ <div id="input-section" x-data="{
paused: false,
attachments: [],
hasAttachments: false,
-
+
handleFileUpload(event) {
const files = event.target.files;
-
+
Array.from(files).forEach(file => {
const ext = file.name.split('.').pop().toLowerCase();
-
+
const isImage = ['jpg', 'jpeg', 'png', 'bmp'].includes(ext);
-
+
if (isImage) {
// Handle image preview
const reader = new FileReader();
@@ -298,7 +333,7 @@
<!-- Container for textarea and button -->
<div id="chat-input-container" style="position: relative;">
<textarea id="chat-input" placeholder="Type your message here..." rows="1"></textarea>
-
+
<!-- Expand button inside the textarea container -->
<button id="expand-button" @click="$store.fullScreenInputModal.openModal()" aria-label="Expand input">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
@@ -306,7 +341,7 @@
</svg>
</button>
</div>
-
+
<div id="chat-buttons-wrapper">
<!-- Send button -->
@@ -687,12 +722,12 @@
<!-- Full Screen Input Modal -->
<div id="fullScreenInputModal" x-data="fullScreenInputModalProxy">
<template x-teleport="body">
- <div x-show="isOpen" class="modal-overlay" @click.self="handleClose()"
+ <div x-show="isOpen" class="modal-overlay" @click.self="handleClose()"
@keydown.escape.window="handleClose()" x-transition>
<div class="modal-container full-screen-input-modal">
<div class="modal-content">
<button class="modal-close" @click="handleClose()">&times;</button>
-
+
<!-- Add toolbar -->
<div class="editor-toolbar">
<div class="toolbar-group">
@@ -725,8 +760,8 @@
</div>
</div>
- <textarea id="full-screen-input" x-model="inputText"
- placeholder="Type your message here..."
+ <textarea id="full-screen-input" x-model="inputText"
+ placeholder="Type your message here..."
@keydown.ctrl.enter="handleClose()"
@keydown.ctrl.z.prevent="undo()"
@keydown.ctrl.shift.z.prevent="redo()"
@@ -744,9 +779,9 @@
</div>
<!-- Drag and Drop Overlay -->
- <div id="dragdrop-overlay"
+ <div id="dragdrop-overlay"
x-cloak
- x-data="{ isVisible: false }"
+ x-data="{ isVisible: false }"
x-show="isVisible"
x-transition:enter="transition ease-out duration-300"
x-transition:enter-start="opacity-0"
@@ -762,4 +797,4 @@
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/webui/index.js b/webui/index.js
index eb50e8eb4..b25053e64 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -10,6 +10,7 @@ const sendButton = document.getElementById('send-button');
const inputSection = document.getElementById('input-section');
const statusSection = document.getElementById('status-section');
const chatsSection = document.getElementById('chats-section');
+const tasksSection = document.getElementById('tasks-section');
const progressBar = document.getElementById('progress-bar');
const autoScrollSwitch = document.getElementById('auto-scroll-switch');
const timeDate = document.getElementById('time-date-container');
@@ -20,8 +21,10 @@ let context = "";
let connectionStatus = false
-// Initialize the toggle button
+// Initialize the toggle button
setupSidebarToggle();
+// Initialize tabs
+setupTabs();
function isMobile() {
return window.innerWidth <= 768;
@@ -149,7 +152,7 @@ export async function sendMessage() {
// } else {
// toast("Undefined error.", "error");
// }
- // }
+ // }
else {
setContext(jsonResponse.context);
}
@@ -340,7 +343,12 @@ async function poll() {
let updated = false
try {
const response = await sendJsonData("/poll", { log_from: lastLogVersion, context });
- //console.log(response)
+
+ // Check if the response is valid
+ if (!response) {
+ console.error("Invalid response from poll endpoint");
+ return false;
+ }
if (!context) setContext(response.context)
if (response.context != context) return //skip late polls after context change
@@ -359,6 +367,9 @@ async function poll() {
afterMessagesUpdate(response.logs)
}
+ lastLogVersion = response.log_version;
+ lastLogGuid = response.log_guid;
+
updateProgress(response.log_progress, response.log_progress_active)
//set ui model vars from backend
@@ -368,11 +379,95 @@ async function poll() {
// Update status icon state
setConnectionStatus(true)
+ // Update chats list and sort by created_at time (newer first)
const chatsAD = Alpine.$data(chatsSection);
- chatsAD.contexts = response.contexts;
+ const contexts = response.contexts || [];
+ chatsAD.contexts = contexts.sort((a, b) =>
+ (b.created_at || 0) - (a.created_at || 0)
+ );
+
+ // Update tasks list and sort by creation time (newer first)
+ const tasksSection = document.getElementById('tasks-section');
+ if (tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ let tasks = response.tasks || [];
+
+ // Only update the tasks array if it's actually different
+ // This prevents unnecessary reactivity triggers
+ const currentTaskIds = new Set((tasksAD.tasks || []).map(t => t.id));
+ const newTaskIds = new Set(tasks.map(t => t.id));
+
+ // Check if the sets are different sizes or have different contents
+ const needsUpdate = currentTaskIds.size !== newTaskIds.size ||
+ tasks.some(task => !currentTaskIds.has(task.id));
+
+ if (needsUpdate) {
+ if (tasks.length > 0) {
+ // Sort the tasks by creation time
+ const sortedTasks = [...tasks].sort((a, b) =>
+ (b.created_at || 0) - (a.created_at || 0)
+ );
+
+ // Use a clean array assignment to avoid duplicating elements
+ tasksAD.tasks = sortedTasks;
+ } else {
+ // Make sure to use a new empty array instance
+ tasksAD.tasks = [];
+ }
+ }
+ }
- lastLogVersion = response.log_version;
- lastLogGuid = response.log_guid;
+ // Make sure the active context is properly selected in both lists
+ if (context) {
+ // Update selection in the active tab
+ const activeTab = localStorage.getItem('activeTab') || 'chats';
+
+ if (activeTab === 'chats') {
+ chatsAD.selected = context;
+ localStorage.setItem('lastSelectedChat', context);
+
+ // Check if this context exists in the chats list
+ const contextExists = contexts.some(ctx => ctx.id === context);
+
+ // If it doesn't exist in the chats list but we're in chats tab, try to select the first chat
+ if (!contextExists && contexts.length > 0) {
+ const firstChatId = contexts[0].id;
+ setContext(firstChatId);
+ chatsAD.selected = firstChatId;
+ localStorage.setItem('lastSelectedChat', firstChatId);
+ }
+ } else if (activeTab === 'tasks' && tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ tasksAD.selected = context;
+ localStorage.setItem('lastSelectedTask', context);
+
+ // Check if this context exists in the tasks list
+ const taskExists = response.tasks?.some(task => task.id === context);
+
+ // If it doesn't exist in the tasks list but we're in tasks tab, try to select the first task
+ if (!taskExists && response.tasks?.length > 0) {
+ const firstTaskId = response.tasks[0].id;
+ setContext(firstTaskId);
+ tasksAD.selected = firstTaskId;
+ localStorage.setItem('lastSelectedTask', firstTaskId);
+ }
+ }
+ } else if (response.tasks && response.tasks.length > 0 && localStorage.getItem('activeTab') === 'tasks') {
+ // If we're in tasks tab with no selection but have tasks, select the first one
+ const firstTaskId = response.tasks[0].id;
+ setContext(firstTaskId);
+ if (tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ tasksAD.selected = firstTaskId;
+ localStorage.setItem('lastSelectedTask', firstTaskId);
+ }
+ } else if (contexts.length > 0 && localStorage.getItem('activeTab') === 'chats') {
+ // If we're in chats tab with no selection but have chats, select the first one
+ const firstChatId = contexts[0].id;
+ setContext(firstChatId);
+ chatsAD.selected = firstChatId;
+ localStorage.setItem('lastSelectedChat', firstChatId);
+ }
} catch (error) {
console.error('Error:', error);
@@ -443,45 +538,144 @@ window.newChat = async function () {
}
window.killChat = async function (id) {
+ if (!id) {
+ console.error("No chat ID provided for deletion");
+ return;
+ }
+
+ console.log("Deleting chat with ID:", id);
+
try {
const chatsAD = Alpine.$data(chatsSection);
- let found, other
+ console.log("Current contexts before deletion:", JSON.stringify(chatsAD.contexts.map(c => ({ id: c.id, name: c.name }))));
+
+ // Find an alternate chat to switch to if we're deleting the current one
+ let alternateChat = null;
for (let i = 0; i < chatsAD.contexts.length; i++) {
- if (chatsAD.contexts[i].id == id) {
- found = true
- } else {
- other = chatsAD.contexts[i]
+ if (chatsAD.contexts[i].id !== id) {
+ alternateChat = chatsAD.contexts[i];
+ break;
}
- if (found && other) break
}
- if (context == id && found) {
- if (other) setContext(other.id)
- else setContext(generateGUID())
+ // If we're deleting the currently selected chat, switch to another one first
+ if (context === id) {
+ if (alternateChat) {
+ setContext(alternateChat.id);
+ } else {
+ // If no other chats, create a new empty context
+ setContext(generateGUID());
+ }
}
- if (found) sendJsonData("/chat_remove", { context: id });
+ // Delete the chat on the server
+ await sendJsonData("/chat_remove", { context: id });
- updateAfterScroll()
+ // Update the UI manually to ensure the correct chat is removed
+ // Deep clone the contexts array to prevent reference issues
+ const updatedContexts = chatsAD.contexts.filter(ctx => ctx.id !== id);
+ console.log("Updated contexts after deletion:", JSON.stringify(updatedContexts.map(c => ({ id: c.id, name: c.name }))));
+
+ // Force UI update by creating a new array
+ chatsAD.contexts = [...updatedContexts];
+ updateAfterScroll();
+
+ toast("Chat deleted successfully", "success");
} catch (e) {
- window.toastFetchError("Error creating new chat", e)
+ console.error("Error deleting chat:", e);
+ window.toastFetchError("Error deleting chat", e);
+ }
+}
+
+// Function to ensure proper UI state when switching contexts
+function ensureProperTabSelection(contextId) {
+ // Get current active tab
+ const activeTab = localStorage.getItem('activeTab') || 'chats';
+
+ // First attempt to determine if this is a task or chat based on the task list
+ const tasksSection = document.getElementById('tasks-section');
+ let isTask = false;
+
+ if (tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ if (tasksAD && tasksAD.tasks) {
+ isTask = tasksAD.tasks.some(task => task.id === contextId);
+ }
+ }
+
+ // If we're selecting a task but are in the chats tab, switch to tasks tab
+ if (isTask && activeTab === 'chats') {
+ // Store this as the last selected task before switching
+ localStorage.setItem('lastSelectedTask', contextId);
+ activateTab('tasks');
+ return true;
+ }
+
+ // If we're selecting a chat but are in the tasks tab, switch to chats tab
+ if (!isTask && activeTab === 'tasks') {
+ // Store this as the last selected chat before switching
+ localStorage.setItem('lastSelectedChat', contextId);
+ activateTab('chats');
+ return true;
}
+
+ return false;
}
window.selectChat = async function (id) {
- setContext(id)
- updateAfterScroll()
+ if (id === context) return //already selected
+
+ // Check if we need to switch tabs based on the context type
+ const tabSwitched = ensureProperTabSelection(id);
+
+ // If we didn't switch tabs, proceed with normal selection
+ if (!tabSwitched) {
+ // Switch to the new context - this will clear chat history and reset tracking variables
+ setContext(id);
+
+ // Update both contexts and tasks lists to reflect the selected item
+ const chatsAD = Alpine.$data(chatsSection);
+ const tasksSection = document.getElementById('tasks-section');
+ if (tasksSection) {
+ const tasksAD = Alpine.$data(tasksSection);
+ tasksAD.selected = id;
+ }
+ chatsAD.selected = id;
+
+ // Store this selection in the appropriate localStorage key
+ const activeTab = localStorage.getItem('activeTab') || 'chats';
+ if (activeTab === 'chats') {
+ localStorage.setItem('lastSelectedChat', id);
+ } else if (activeTab === 'tasks') {
+ localStorage.setItem('lastSelectedTask', id);
+ }
+
+ // Trigger an immediate poll to fetch content
+ poll();
+ }
+
+ updateAfterScroll();
}
export const setContext = function (id) {
- if (id == context) return
- context = id
- lastLogGuid = ""
- lastLogVersion = 0
- lastSpokenNo = 0
+ if (id == context) return;
+ context = id;
+ // Always reset the log tracking variables when switching contexts
+ // This ensures we get fresh data from the backend
+ lastLogGuid = "";
+ lastLogVersion = 0;
+ lastSpokenNo = 0;
+
+ // Clear the chat history immediately to avoid showing stale content
+ chatHistory.innerHTML = "";
+
+ // Update both selected states
const chatsAD = Alpine.$data(chatsSection);
- chatsAD.selected = id
+ const tasksAD = Alpine.$data(tasksSection);
+
+ chatsAD.selected = id;
+ tasksAD.selected = id;
}
export const getContext = function () {
@@ -625,7 +819,7 @@ window.loadChats = async function () {
// } else {
// toast("Undefined error.", "error")
// }
- // }
+ // }
else {
setContext(response.ctxids[0])
toast("Chats loaded.", "success")
@@ -905,7 +1099,7 @@ document.addEventListener('DOMContentLoaded', () => {
dragDropOverlay.addEventListener('drop', (e) => {
dragCounter = 0;
Alpine.$data(dragDropOverlay).isVisible = false;
-
+
const inputAD = Alpine.$data(inputSection);
const files = e.dataTransfer.files;
handleFiles(files, inputAD);
@@ -916,9 +1110,9 @@ document.addEventListener('DOMContentLoaded', () => {
function handleFiles(files, inputAD) {
Array.from(files).forEach(file => {
const ext = file.name.split('.').pop().toLowerCase();
-
+
const isImage = ['jpg', 'jpeg', 'png', 'bmp'].includes(ext);
-
+
if (isImage) {
const reader = new FileReader();
reader.onload = e => {
@@ -941,7 +1135,7 @@ function handleFiles(files, inputAD) {
});
inputAD.hasAttachments = true;
}
-
+
});
}
@@ -950,4 +1144,110 @@ window.handleFileUpload = function(event) {
const files = event.target.files;
const inputAD = Alpine.$data(inputSection);
handleFiles(files, inputAD);
-}
\ No newline at end of file
+}
+
+// Setup event handlers once the DOM is fully loaded
+document.addEventListener('DOMContentLoaded', function() {
+ setupSidebarToggle();
+ setupTabs();
+ initializeActiveTab();
+});
+
+// Setup tabs functionality
+function setupTabs() {
+ const chatsTab = document.getElementById('chats-tab');
+ const tasksTab = document.getElementById('tasks-tab');
+
+ if (chatsTab && tasksTab) {
+ chatsTab.addEventListener('click', function() {
+ activateTab('chats');
+ });
+
+ tasksTab.addEventListener('click', function() {
+ activateTab('tasks');
+ });
+ } else {
+ console.error('Tab elements not found');
+ setTimeout(setupTabs, 100); // Retry setup
+ }
+}
+
+function activateTab(tabName) {
+ const chatsTab = document.getElementById('chats-tab');
+ const tasksTab = document.getElementById('tasks-tab');
+ const chatsSection = document.getElementById('chats-section');
+ const tasksSection = document.getElementById('tasks-section');
+
+ // Get current context to preserve before switching
+ const currentContext = context;
+
+ // Store the current selection for the active tab before switching
+ const previousTab = localStorage.getItem('activeTab');
+ if (previousTab === 'chats') {
+ localStorage.setItem('lastSelectedChat', currentContext);
+ } else if (previousTab === 'tasks') {
+ localStorage.setItem('lastSelectedTask', currentContext);
+ }
+
+ // Reset all tabs and sections
+ chatsTab.classList.remove('active');
+ tasksTab.classList.remove('active');
+ chatsSection.style.display = 'none';
+ tasksSection.style.display = 'none';
+
+ // Remember the last active tab in localStorage
+ localStorage.setItem('activeTab', tabName);
+
+ // Activate selected tab and section
+ if (tabName === 'chats') {
+ chatsTab.classList.add('active');
+ chatsSection.style.display = '';
+
+ // Restore previous chat selection
+ const lastSelectedChat = localStorage.getItem('lastSelectedChat');
+ if (lastSelectedChat && lastSelectedChat !== currentContext) {
+ // Only switch if there's a stored selection and it's different from current
+ setContext(lastSelectedChat);
+ }
+ } else if (tabName === 'tasks') {
+ tasksTab.classList.add('active');
+ tasksSection.style.display = 'flex';
+ tasksSection.style.flexDirection = 'column';
+
+ // Restore previous task selection
+ const lastSelectedTask = localStorage.getItem('lastSelectedTask');
+ if (lastSelectedTask && lastSelectedTask !== currentContext) {
+ // Only switch if there's a stored selection and it's different from current
+ setContext(lastSelectedTask);
+ }
+ }
+
+ // Request a poll update
+ poll();
+}
+
+// Add function to initialize active tab and selections from localStorage
+function initializeActiveTab() {
+ // Initialize selection storage if not present
+ if (!localStorage.getItem('lastSelectedChat')) {
+ localStorage.setItem('lastSelectedChat', '');
+ }
+ if (!localStorage.getItem('lastSelectedTask')) {
+ localStorage.setItem('lastSelectedTask', '');
+ }
+
+ const activeTab = localStorage.getItem('activeTab') || 'chats';
+ activateTab(activeTab);
+}
+
+/*
+ * A0 Chat UI
+ *
+ * Tasks tab functionality:
+ * - Tasks are displayed in the Tasks tab with the same mechanics as chats
+ * - Both lists are sorted by creation time (newest first)
+ * - Selection state is preserved across tab switches
+ * - The active tab is remembered across sessions
+ * - Tasks use the same context system as chats for communication with the backend
+ * - Future support for renaming and deletion will be implemented later
+ */