Skip to content

Agent Zero AI framework

frontend file browsers, css colors, litellm update, reqs split

frdel70814791932b
diff --git a/docker/run/fs/ins/install_A0.sh b/docker/run/fs/ins/install_A0.sh
index 7b5d0d807..0aeaf13ff 100644
--- a/docker/run/fs/ins/install_A0.sh
+++ b/docker/run/fs/ins/install_A0.sh
@@ -36,6 +36,8 @@ fi
# Install remaining A0 python packages
uv pip install -r /git/agent-zero/requirements.txt
+# override for packages that have unnecessarily strict dependencies
+uv pip install -r /git/agent-zero/requirements2.txt
# install playwright
bash /ins/install_playwright.sh "$@"
diff --git a/python/api/chat_files_path_get.py b/python/api/chat_files_path_get.py
new file mode 100644
index 000000000..b230d31f7
--- /dev/null
+++ b/python/api/chat_files_path_get.py
@@ -0,0 +1,23 @@
+from python.helpers.api import ApiHandler, Request, Response
+from python.helpers import files, memory, notification, projects, notification, runtime
+import os
+from werkzeug.utils import secure_filename
+
+
+class GetChatFilesPath(ApiHandler):
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ ctxid = input.get("ctxid", "")
+ if not ctxid:
+ raise Exception("No context id provided")
+ context = self.use_context(ctxid)
+
+ project_name = projects.get_context_project_name(context)
+ if project_name:
+ folder = files.normalize_a0_path(projects.get_project_folder(project_name))
+ else:
+ folder = "/root" # root in container
+
+ return {
+ "ok": True,
+ "path": folder,
+ }
\ No newline at end of file
diff --git a/python/api/knowledge_path_get.py b/python/api/knowledge_path_get.py
new file mode 100644
index 000000000..dadf0a692
--- /dev/null
+++ b/python/api/knowledge_path_get.py
@@ -0,0 +1,25 @@
+from python.helpers.api import ApiHandler, Request, Response
+from python.helpers import files, memory, notification, projects, notification
+import os
+from werkzeug.utils import secure_filename
+
+
+class GetKnowledgePath(ApiHandler):
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ ctxid = input.get("ctxid", "")
+ if not ctxid:
+ raise Exception("No context id provided")
+ context = self.use_context(ctxid)
+
+ project_name = projects.get_context_project_name(context)
+ if project_name:
+ knowledge_folder = projects.get_project_meta_folder(project_name, "knowledge")
+ else:
+ knowledge_folder = memory.get_custom_knowledge_subdir_abs(context.agent0)
+
+ knowledge_folder = files.normalize_a0_path(knowledge_folder)
+
+ return {
+ "ok": True,
+ "path": knowledge_folder,
+ }
\ No newline at end of file
diff --git a/python/api/knowledge_reindex.py b/python/api/knowledge_reindex.py
new file mode 100644
index 000000000..b86eafeaf
--- /dev/null
+++ b/python/api/knowledge_reindex.py
@@ -0,0 +1,21 @@
+from python.helpers.api import ApiHandler, Request, Response
+from python.helpers import files, memory, notification, projects, notification
+import os
+from werkzeug.utils import secure_filename
+
+
+class ReindexKnowledge(ApiHandler):
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ ctxid = input.get("ctxid", "")
+ if not ctxid:
+ raise Exception("No context id provided")
+ context = self.use_context(ctxid)
+
+ # reload memory to re-import knowledge
+ await memory.Memory.reload(context.agent0)
+ context.log.set_initial_progress()
+
+ return {
+ "ok": True,
+ "message": "Knowledge re-indexed",
+ }
diff --git a/python/api/poll.py b/python/api/poll.py
index eb021c2f2..bdb083bab 100644
--- a/python/api/poll.py
+++ b/python/api/poll.py
@@ -20,7 +20,10 @@ class Poll(ApiHandler):
# context instance - get or create only if ctxid is provided
if ctxid:
- context = self.use_context(ctxid, create_if_not_exists=False)
+ try:
+ context = self.use_context(ctxid, create_if_not_exists=False)
+ except Exception as e:
+ context = None
else:
context = None
diff --git a/python/helpers/api.py b/python/helpers/api.py
index 6a40e1347..6c90c6e56 100644
--- a/python/helpers/api.py
+++ b/python/helpers/api.py
@@ -95,3 +95,6 @@ class ApiHandler:
if create_if_not_exists:
context = AgentContext(config=initialize_agent(), id=ctxid, set_current=True)
return context
+ else:
+ raise Exception(f"Context {ctxid} not found")
+
diff --git a/python/helpers/files.py b/python/helpers/files.py
index ef8587ec6..ba220ce71 100644
--- a/python/helpers/files.py
+++ b/python/helpers/files.py
@@ -530,3 +530,17 @@ def read_text_files_in_dir(
except Exception:
continue
return result
+
+def list_files_in_dir_recursively(relative_path: str) -> list[str]:
+ abs_path = get_abs_path(relative_path)
+ if not os.path.exists(abs_path):
+ return []
+ result = []
+ for root, dirs, files in os.walk(abs_path):
+ for file in files:
+ file_path = os.path.join(root, file)
+ # Return relative path from the base directory
+ rel_path = os.path.relpath(file_path, abs_path)
+ result.append(rel_path)
+ return result
+
\ No newline at end of file
diff --git a/python/helpers/knowledge_import.py b/python/helpers/knowledge_import.py
index 445765050..a68fe9b82 100644
--- a/python/helpers/knowledge_import.py
+++ b/python/helpers/knowledge_import.py
@@ -36,6 +36,7 @@ def load_knowledge(
index: Dict[str, KnowledgeImport],
metadata: dict[str, Any] = {},
filename_pattern: str = "**/*",
+ recursive: bool = True,
) -> Dict[str, KnowledgeImport]:
"""
Load knowledge files from a directory with change detection and metadata enhancement.
@@ -96,7 +97,7 @@ def load_knowledge(
# Fetch all files in the directory with specified extensions
try:
- kn_files = glob.glob(os.path.join(knowledge_dir, filename_pattern), recursive=True)
+ kn_files = glob.glob(os.path.join(knowledge_dir, filename_pattern), recursive=recursive)
kn_files = [f for f in kn_files if os.path.isfile(f) and not os.path.basename(f).startswith('.')]
except Exception as e:
PrintStyle(font_color="red").print(f"Error scanning knowledge directory {knowledge_dir}: {e}")
diff --git a/python/helpers/memory.py b/python/helpers/memory.py
index bc3f1cf20..8c8785c5a 100644
--- a/python/helpers/memory.py
+++ b/python/helpers/memory.py
@@ -77,10 +77,11 @@ class Memory:
)
Memory.index[memory_subdir] = db
wrap = Memory(db, memory_subdir=memory_subdir)
- if agent.config.knowledge_subdirs:
- await wrap.preload_knowledge(
- log_item, agent.config.knowledge_subdirs, memory_subdir
- )
+ knowledge_subdirs = get_knowledge_subdirs_by_memory_subdir(
+ memory_subdir, agent.config.knowledge_subdirs or []
+ )
+ if knowledge_subdirs:
+ await wrap.preload_knowledge(log_item, knowledge_subdirs, memory_subdir)
return wrap
else:
return Memory(
@@ -106,16 +107,20 @@ class Memory:
in_memory=False,
)
wrap = Memory(db, memory_subdir=memory_subdir)
- if preload_knowledge and agent_config.knowledge_subdirs:
- await wrap.preload_knowledge(
- log_item, agent_config.knowledge_subdirs, memory_subdir
+ if preload_knowledge:
+ knowledge_subdirs = get_knowledge_subdirs_by_memory_subdir(
+ memory_subdir, agent_config.knowledge_subdirs or []
)
+ if knowledge_subdirs:
+ await wrap.preload_knowledge(
+ log_item, knowledge_subdirs, memory_subdir
+ )
Memory.index[memory_subdir] = db
return Memory(db=Memory.index[memory_subdir], memory_subdir=memory_subdir)
@staticmethod
async def reload(agent: Agent):
- memory_subdir = agent.config.memory_subdir or "default"
+ memory_subdir = get_agent_memory_subdir(agent)
if Memory.index.get(memory_subdir):
del Memory.index[memory_subdir]
return await Memory.get(agent)
@@ -298,12 +303,24 @@ class Memory:
):
# load knowledge folders, subfolders by area
for kn_dir in kn_dirs:
+ # everything in the root of the knowledge goes to main
+ index = knowledge_import.load_knowledge(
+ log_item,
+ abs_knowledge_dir(kn_dir),
+ index,
+ {"area": Memory.Area.MAIN},
+ filename_pattern="*",
+ recursive=False,
+ )
+ # subdirectories go to their folders
for area in Memory.Area:
index = knowledge_import.load_knowledge(
log_item,
- files.get_abs_path("knowledge", kn_dir, area.value),
+ # files.get_abs_path("knowledge", kn_dir, area.value),
+ abs_knowledge_dir(kn_dir, area.value),
index,
{"area": area.value},
+ recursive=True,
)
# load instruments descriptions
@@ -313,6 +330,7 @@ class Memory:
index,
{"area": Memory.Area.INSTRUMENTS.value},
filename_pattern="**/*.md",
+ recursive=True,
)
return index
@@ -484,6 +502,18 @@ def abs_db_dir(memory_subdir: str) -> str:
return files.get_abs_path("memory", memory_subdir)
+def abs_knowledge_dir(knowledge_subdir: str, *sub_dirs: str) -> str:
+ # patch for projects, this way we don't need to re-work the structure of knowledge subdirs
+ if knowledge_subdir.startswith("projects/"):
+ from python.helpers.projects import get_project_meta_folder
+
+ return files.get_abs_path(
+ get_project_meta_folder(knowledge_subdir[9:]), "knowledge", *sub_dirs
+ )
+ # standard subdirs
+ return files.get_abs_path("knowledge", knowledge_subdir, *sub_dirs)
+
+
def get_memory_subdir_abs(agent: Agent) -> str:
subdir = get_agent_memory_subdir(agent)
return abs_db_dir(subdir)
@@ -496,7 +526,9 @@ def get_agent_memory_subdir(agent: Agent) -> str:
def get_context_memory_subdir(context: AgentContext) -> str:
# if project is active, use project memory subdir
- from python.helpers.projects import get_context_memory_subdir as get_project_memory_subdir
+ from python.helpers.projects import (
+ get_context_memory_subdir as get_project_memory_subdir,
+ )
memory_subdir = get_project_memory_subdir(context)
if memory_subdir:
@@ -505,23 +537,39 @@ def get_context_memory_subdir(context: AgentContext) -> str:
# no project, regular memory subdir
return context.config.memory_subdir or "default"
+
def get_existing_memory_subdirs() -> list[str]:
try:
- from python.helpers.projects import get_project_meta_folder, get_projects_parent_folder
+ from python.helpers.projects import (
+ get_project_meta_folder,
+ get_projects_parent_folder,
+ )
+
# Get subdirectories from memory folder
subdirs = files.get_subdirectories("memory", exclude="embeddings")
project_subdirs = files.get_subdirectories(get_projects_parent_folder())
for project_subdir in project_subdirs:
- if files.exists(get_project_meta_folder(project_subdir), "memory", "index.faiss"):
+ if files.exists(
+ get_project_meta_folder(project_subdir), "memory", "index.faiss"
+ ):
subdirs.append(f"projects/{project_subdir}")
# Ensure 'default' is always available
if "default" not in subdirs:
subdirs.insert(0, "default")
-
+
return subdirs
except Exception as e:
PrintStyle.error(f"Failed to get memory subdirectories: {str(e)}")
return ["default"]
-
\ No newline at end of file
+
+
+def get_knowledge_subdirs_by_memory_subdir(
+ memory_subdir: str, default: list[str]
+) -> list[str]:
+ if memory_subdir.startswith("projects/"):
+ from python.helpers.projects import get_project_meta_folder
+
+ default.append(get_project_meta_folder(memory_subdir[9:], "knowledge"))
+ return default
diff --git a/python/helpers/playwright.py b/python/helpers/playwright.py
index 34f851ab6..c352407b2 100644
--- a/python/helpers/playwright.py
+++ b/python/helpers/playwright.py
@@ -1,4 +1,6 @@
+import os
+import sys
from pathlib import Path
import subprocess
from python.helpers import files
@@ -9,8 +11,14 @@ from python.helpers import files
def get_playwright_binary():
pw_cache = Path(get_playwright_cache_dir())
- headless_shell = next(pw_cache.glob("chromium_headless_shell-*/chrome-*/headless_shell"), None)
- return headless_shell
+ for pattern in (
+ "chromium_headless_shell-*/chrome-*/headless_shell",
+ "chromium_headless_shell-*/chrome-*/headless_shell.exe",
+ ):
+ binary = next(pw_cache.glob(pattern), None)
+ if binary:
+ return binary
+ return None
def get_playwright_cache_dir():
return files.get_abs_path("tmp/playwright")
@@ -19,7 +27,6 @@ def ensure_playwright_binary():
bin = get_playwright_binary()
if not bin:
cache = get_playwright_cache_dir()
- import os
env = os.environ.copy()
env["PLAYWRIGHT_BROWSERS_PATH"] = cache
subprocess.check_call(
diff --git a/python/helpers/projects.py b/python/helpers/projects.py
index 943db5385..75ae35138 100644
--- a/python/helpers/projects.py
+++ b/python/helpers/projects.py
@@ -11,6 +11,7 @@ if TYPE_CHECKING:
PROJECTS_PARENT_DIR = "usr/projects"
PROJECT_META_DIR = ".a0proj"
PROJECT_INSTRUCTIONS_DIR = "instructions"
+PROJECT_KNOWLEDGE_DIR = "knowledge"
PROJECT_HEADER_FILE = "project.json"
CONTEXT_DATA_KEY_PROJECT = "project"
@@ -21,13 +22,15 @@ class BasicProjectData(TypedDict):
description: str
instructions: str
color: str
- memory: Literal["own", "global"] # in the future we can add cutom and point to another existing folder
-
+ memory: Literal[
+ "own", "global"
+ ] # in the future we can add cutom and point to another existing folder
class EditProjectData(BasicProjectData):
name: str
instruction_files_count: int
+ knowledge_files_count: int
variables: str
secrets: str
@@ -39,8 +42,9 @@ def get_projects_parent_folder():
def get_project_folder(name: str):
return files.get_abs_path(get_projects_parent_folder(), name)
-def get_project_meta_folder(name: str):
- return files.get_abs_path(get_project_folder(name), PROJECT_META_DIR)
+
+def get_project_meta_folder(name: str, *sub_dirs: str):
+ return files.get_abs_path(get_project_folder(name), PROJECT_META_DIR, *sub_dirs)
def delete_project(name: str):
@@ -54,9 +58,7 @@ def create_project(name: str, data: BasicProjectData):
abs_path = files.create_dir_safe(
files.get_abs_path(PROJECTS_PARENT_DIR, name), rename_format="{name}_{number}"
)
- files.create_dir(
- files.get_abs_path(abs_path, PROJECT_META_DIR, PROJECT_INSTRUCTIONS_DIR)
- )
+ create_project_meta_folders(name)
data = _normalizeBasicData(data)
save_project_header(name, data)
return name
@@ -80,6 +82,7 @@ def _normalizeBasicData(data: BasicProjectData):
memory=data.get("memory", "own"),
)
+
def _normalizeEditData(data: EditProjectData):
return EditProjectData(
name=data.get("name", ""),
@@ -89,16 +92,19 @@ def _normalizeEditData(data: EditProjectData):
variables=data.get("variables", ""),
color=data.get("color", ""),
instruction_files_count=data.get("instruction_files_count", 0),
+ knowledge_files_count=data.get("knowledge_files_count", 0),
secrets=data.get("secrets", ""),
memory=data.get("memory", "own"),
)
+
def _edit_data_to_basic_data(data: EditProjectData):
return _normalizeBasicData(data)
+
def _basic_data_to_edit_data(data: BasicProjectData):
- return _normalizeEditData(data) # type: ignore
-
+ return _normalizeEditData(data) # type: ignore
+
def update_project(name: str, data: EditProjectData):
# merge with current state
@@ -117,6 +123,7 @@ def update_project(name: str, data: EditProjectData):
reactivate_project_in_chats(name)
return name
+
def load_basic_project_data(name: str) -> BasicProjectData:
data = BasicProjectData(**load_project_header(name))
normalized = _normalizeBasicData(data)
@@ -130,10 +137,12 @@ def load_edit_project_data(name: str) -> EditProjectData:
) # for additional info
variables = load_project_variables(name)
secrets = load_project_secrets_masked(name)
+ knowledge_files_count = get_knowledge_files_count(name)
data = EditProjectData(
**data,
name=name,
instruction_files_count=len(additional_instructions),
+ knowledge_files_count=knowledge_files_count,
variables=variables,
secrets=secrets,
)
@@ -254,34 +263,38 @@ def get_additional_instructions_files(name: str):
)
return files.read_text_files_in_dir(instructions_folder)
+
def get_context_project_name(context: "AgentContext") -> str | None:
return context.get_data(CONTEXT_DATA_KEY_PROJECT)
+
def load_project_variables(name: str):
try:
- abs_path = files.get_abs_path(
- get_project_meta_folder(name), "variables.env"
- )
+ abs_path = files.get_abs_path(get_project_meta_folder(name), "variables.env")
return files.read_file(abs_path)
except Exception:
return ""
+
def save_project_variables(name: str, variables: str):
- abs_path = files.get_abs_path(
- get_project_meta_folder(name), "variables.env"
- )
+ abs_path = files.get_abs_path(get_project_meta_folder(name), "variables.env")
files.write_file(abs_path, variables)
-def load_project_secrets_masked(name:str, merge_with_global=False):
+
+def load_project_secrets_masked(name: str, merge_with_global=False):
from python.helpers import secrets
+
mgr = secrets.get_project_secrets_manager(name, merge_with_global)
return mgr.get_masked_secrets()
+
def save_project_secrets(name: str, secrets: str):
from python.helpers.secrets import get_project_secrets_manager
+
secrets_manager = get_project_secrets_manager(name)
secrets_manager.save_secrets_with_merge(secrets)
+
def get_context_memory_subdir(context: "AgentContext") -> str | None:
# if a project is active and has memory isolation set, return the project memory subdir
project_name = get_context_project_name(context)
@@ -289,4 +302,25 @@ def get_context_memory_subdir(context: "AgentContext") -> str | None:
project_data = load_basic_project_data(project_name)
if project_data["memory"] == "own":
return "projects/" + project_name
- return None # no memory override
\ No newline at end of file
+ return None # no memory override
+
+
+def create_project_meta_folders(name: str):
+ # create instructions folder
+ files.create_dir(get_project_meta_folder(name, PROJECT_INSTRUCTIONS_DIR))
+
+ # create knowledge folders
+ files.create_dir(get_project_meta_folder(name, PROJECT_KNOWLEDGE_DIR))
+ from python.helpers import memory
+
+ for memory_type in memory.Memory.Area:
+ files.create_dir(
+ get_project_meta_folder(name, PROJECT_KNOWLEDGE_DIR, memory_type.value)
+ )
+
+
+def get_knowledge_files_count(name: str):
+ knowledge_folder = files.get_abs_path(
+ get_project_meta_folder(name, PROJECT_KNOWLEDGE_DIR)
+ )
+ return len(files.list_files_in_dir_recursively(knowledge_folder))
diff --git a/requirements.txt b/requirements.txt
index f0391d266..a06a8c1bd 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -33,7 +33,6 @@ unstructured-client==0.31.0
webcolors==24.6.0
nest-asyncio==1.6.0
crontab==1.0.1
-litellm==1.75.0
markdownify==1.1.0
pymupdf==1.25.3
pytesseract==0.3.13
diff --git a/requirements2.txt b/requirements2.txt
new file mode 100644
index 000000000..bb132bdaa
--- /dev/null
+++ b/requirements2.txt
@@ -0,0 +1,2 @@
+litellm==1.79.0
+openai==1.99.5
\ No newline at end of file
diff --git a/webui/components/chat/input/bottom-actions.html b/webui/components/chat/input/bottom-actions.html
index 646095b2b..5c603314e 100644
--- a/webui/components/chat/input/bottom-actions.html
+++ b/webui/components/chat/input/bottom-actions.html
@@ -4,7 +4,6 @@
import { store } from "/components/chat/input/input-store.js";
import { store as historyStore } from "/components/modals/history/history-store.js";
import { store as contextStore } from "/components/modals/context/context-store.js";
- import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";
</script>
</head>
<body>
@@ -32,7 +31,7 @@
<p>Import knowledge</p>
</button>
- <button class="text-button" id="work_dir_browser" @click="$store.fileBrowser.open()">
+ <button class="text-button" id="work_dir_browser" @click="$store.chatInput.browseFiles()">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 123.37 92.59">
<path d="m5.72,11.5l-3.93,8.73h119.77s-3.96-8.73-3.96-8.73h-60.03c-1.59,0-2.88-1.29-2.88-2.88V1.75H13.72v6.87c0,1.59-1.29,2.88-2.88,2.88h-5.12Z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="7"></path>
<path d="m6.38,20.23H1.75l7.03,67.03c.11,1.07.55,2.02,1.2,2.69.55.55,1.28.89,2.11.89h97.1c.82,0,1.51-.33,2.05-.87.68-.68,1.13-1.67,1.28-2.79l9.1-66.94H6.38Z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="8"></path>
diff --git a/webui/components/chat/input/input-store.js b/webui/components/chat/input/input-store.js
index 31b0d2046..0741be179 100644
--- a/webui/components/chat/input/input-store.js
+++ b/webui/components/chat/input/input-store.js
@@ -1,4 +1,6 @@
import { createStore } from "/js/AlpineStore.js";
+import * as shortcuts from "/js/shortcuts.js";
+import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";
const model = {
paused: false,
@@ -28,7 +30,8 @@ const model = {
this.paused = paused;
try {
const context = globalThis.getContext?.();
- if (!globalThis.sendJsonData) throw new Error("sendJsonData not available");
+ if (!globalThis.sendJsonData)
+ throw new Error("sendJsonData not available");
await globalThis.sendJsonData("/pause", { paused, context });
} catch (e) {
this.paused = prev;
@@ -50,6 +53,55 @@ const model = {
},
async loadKnowledge() {
+ try {
+ const resp = await shortcuts.callJsonApi("/knowledge_path_get", {
+ ctxid: shortcuts.getCurrentContextId(),
+ });
+ if (!resp.ok) throw new Error("Error getting knowledge path");
+ const path = resp.path;
+
+ // open file browser and wait for it to close
+ await fileBrowserStore.open(path);
+
+ // progress notification
+ shortcuts.frontendNotification({
+ type: shortcuts.NotificationType.PROGRESS,
+ message: "Loading knowledge...",
+ priority: shortcuts.NotificationPriority.NORMAL,
+ displayTime: 999,
+ group: "knowledge_load",
+ frontendOnly: true,
+ });
+
+ // then reindex knowledge
+ await globalThis.sendJsonData("/knowledge_reindex", {
+ ctxid: shortcuts.getCurrentContextId(),
+ });
+
+ // finished notification
+ shortcuts.frontendNotification({
+ type: shortcuts.NotificationType.SUCCESS,
+ message: "Knowledge loaded successfully",
+ priority: shortcuts.NotificationPriority.NORMAL,
+ displayTime: 2,
+ group: "knowledge_load",
+ frontendOnly: true,
+ });
+ } catch (e) {
+ // error notification
+ shortcuts.frontendNotification({
+ type: shortcuts.NotificationType.ERROR,
+ message: "Error loading knowledge",
+ priority: shortcuts.NotificationPriority.NORMAL,
+ displayTime: 5,
+ group: "knowledge_load",
+ frontendOnly: true,
+ });
+ }
+ },
+
+ // previous implementation without projects
+ async _loadKnowledge() {
const input = document.createElement("input");
input.type = "file";
input.accept = ".txt,.pdf,.csv,.html,.json,.md";
@@ -70,7 +122,8 @@ const model = {
});
if (!response.ok) {
- if (globalThis.toast) globalThis.toast(await response.text(), "error");
+ if (globalThis.toast)
+ globalThis.toast(await response.text(), "error");
} else {
const data = await response.json();
if (globalThis.toast) {
@@ -89,9 +142,22 @@ const model = {
input.click();
},
+
+ async browseFiles(path) {
+ if (!path) {
+ try {
+ const resp = await shortcuts.callJsonApi("/chat_files_path_get", {
+ ctxid: shortcuts.getCurrentContextId(),
+ });
+ if (resp.ok) path = resp.path;
+ } catch (_e) {
+ console.error("Error getting chat files path", _e);
+ }
+ }
+ await fileBrowserStore.open(path);
+ },
};
const store = createStore("chatInput", model);
export { store };
-
diff --git a/webui/components/notifications/notification-store.js b/webui/components/notifications/notification-store.js
index 260d53ed5..dbe96a929 100644
--- a/webui/components/notifications/notification-store.js
+++ b/webui/components/notifications/notification-store.js
@@ -733,6 +733,50 @@ const model = {
frontendOnly
);
},
+
+ async frontendProgress(
+ message,
+ title = "Progress",
+ display_time = 3,
+ group = "",
+ priority = defaultPriority,
+ frontendOnly = false
+ ) {
+ return await this.addFrontendToast(
+ NotificationType.PROGRESS,
+ message,
+ title,
+ display_time,
+ group,
+ priority,
+ frontendOnly
+ );
+ },
+
+ // NEW: Enhanced frontend toast with object parameters and type annotations
+ /**
+ * Adds a frontend toast notification with object parameters.
+ * @param {Object} options - The options for the toast notification.
+ * @param {string} options.type - The type of notification (e.g., info, success, error).
+ * @param {string} options.message - The message content of the notification.
+ * @param {string} [options.title=''] - The title of the notification.
+ * @param {number} [options.displayTime=5] - The display duration in seconds.
+ * @param {string} [options.group=''] - The group identifier for the notification.
+ * @param {string} [options.priority='medium'] - The priority of the notification.
+ * @param {boolean} [options.frontendOnly=false] - Whether to show only on frontend.
+ * @returns {Promise<string>} The ID of the added notification.
+ */
+ async frontendNotification({
+ type,
+ message,
+ title = '',
+ displayTime = 5,
+ group = '',
+ priority = defaultPriority,
+ frontendOnly = false
+ }) {
+ return await this.addFrontendToast(type, message, title, displayTime, group, priority, frontendOnly);
+ },
};
// Create and export the store
@@ -744,12 +788,14 @@ const toastFrontendInfo = store.frontendInfo.bind(store);
const toastFrontendSuccess = store.frontendSuccess.bind(store);
const toastFrontendWarning = store.frontendWarning.bind(store);
const toastFrontendError = store.frontendError.bind(store);
+const toastFrontendProgress = store.frontendProgress.bind(store);
export {
toastFrontendInfo,
toastFrontendSuccess,
toastFrontendWarning,
toastFrontendError,
+ toastFrontendProgress,
};
// add toasts to global for backward compatibility with older scripts
@@ -757,3 +803,4 @@ globalThis.toastFrontendInfo = toastFrontendInfo;
globalThis.toastFrontendSuccess = toastFrontendSuccess;
globalThis.toastFrontendWarning = toastFrontendWarning;
globalThis.toastFrontendError = toastFrontendError;
+globalThis.toastFrontendProgress = toastFrontendProgress;
diff --git a/webui/components/projects/project-edit-memory.html b/webui/components/projects/project-edit-memory.html
index 2e8bacbdf..6a58b7d46 100644
--- a/webui/components/projects/project-edit-memory.html
+++ b/webui/components/projects/project-edit-memory.html
@@ -17,7 +17,9 @@
<label class="projects-form-label">Project-specific memory</label>
<span class="projects-form-description">When turned on, the agent's memory while working on this
project will be isolated from the global memory. The memory will be stored in <strong><span
- x-text="$store.projects.getSelectedAbsPath('.a0proj','memory')"></span></strong>.</span>
+ x-text="$store.projects.getSelectedAbsPath('.a0proj','memory')"></span></strong>.
+ <br>
+ Project-specific knowledge files can be used only when project-specific memory is turned on.</span>
</div>
<div class="projects-setting-control">
<label class="toggle">
@@ -27,6 +29,22 @@
</div>
</div>
+ <div class="projects-form-group" x-show="$store.projects.selectedProject._ownMemory">
+ <label class="projects-form-label">Knowledge files</label>
+ <div class="projects-input-with-button-wrapper">
+ <span class="projects-form-description">Additional knowledge files in <strong><span
+ x-text="$store.projects.getSelectedAbsPath('.a0proj','knowledge')"></span></strong>.
+ Knowledge files are imported into memory and are used when relevant based on the context of the conversation.</span>
+ <span class="projects-form-description">Currently there are <strong><span
+ x-text="$store.projects.selectedProject.knowledge_files_count || 0"></span></strong>
+ knowledge files.</span>
+ <button class="button icon-button" x-on:click="$store.projects.browseKnowledgeFiles()">
+ <span class="icon material-symbols-outlined">folder</span>
+ <span>Browse</span>
+ </button>
+ </div>
+ </div>
+
<style>
.projects-setting-row {
display: flex;
@@ -34,15 +52,18 @@
justify-content: space-between;
gap: 2rem;
}
+
.projects-setting-text {
flex-grow: 1;
flex-shrink: 1;
min-width: 0;
}
+
.projects-setting-control {
flex-grow: 0;
flex-shrink: 0;
}
+
.projects-form-label {
display: block;
}
diff --git a/webui/components/projects/project-selector.html b/webui/components/projects/project-selector.html
index c1b8eb3d7..bd2ea151d 100644
--- a/webui/components/projects/project-selector.html
+++ b/webui/components/projects/project-selector.html
@@ -8,38 +8,107 @@
</head>
<body>
- <div x-data>
+ <div x-data="{ open: false }" @click.away="open = false" class="project-dropdown-container">
<template x-if="$store.projects && $store.chats && $store.chats.selectedContext">
<div>
<template x-if="$store.chats.selectedContext.project?.name">
- <button @click="$store.projects.openProjectsModal()" type="button" class="button project-button">
+ <button @click="open = !open" type="button" class="button project-dropdown-button">
<span class="project-color-ball" :style="$store.chats.selectedContext.project.color ? { backgroundColor: $store.chats.selectedContext.project.color } : { border: '1px solid var(--color-border)' }"></span>
- <span x-text="$store.chats.selectedContext.project.name"></span>
+ <span x-text="$store.chats.selectedContext.project.title"></span>
+ <span class="icon material-symbols-outlined">arrow_drop_down</span>
</button>
</template>
<template x-if="!$store.chats.selectedContext.project?.name">
- <button @click="$store.projects.openProjectsModal()" type="button" class="button project-button">
- No project</button>
+ <button @click="open = !open" type="button" class="button project-dropdown-button">
+ No project
+ <span class="icon material-symbols-outlined">arrow_drop_down</span>
+ </button>
</template>
+
+ <div x-show="open" x-init="$store.projects.loadProjectsList()" class="project-dropdown-menu" style="display: none;" x-transition>
+ <a href="#" @click.prevent="$store.projects.openProjectsModal(); open = false;" class="project-dropdown-item"><span class="icon material-symbols-outlined">snippet_folder</span> <span class="project-selector-item-text">Edit Projects</span></a>
+ <a x-show="$store.chats.selectedContext.project?.name" href="#" @click.prevent="$store.projects.deactivateProject(); open = false;" class="project-dropdown-item"><span class="icon material-symbols-outlined">close</span> <span class="project-selector-item-text">Deactivate</span></a>
+ <!-- <a href="#" @click.prevent="$store.projects.openProjectsModal(); $store.projects.openCreateModal(); open = false;" class="project-dropdown-item">Create Project</a> -->
+
+ <hr x-show=" $store.projects.projectList.length > 0" class="project-dropdown-divider">
+ <template x-for="project in $store.projects.projectList" :key="project.name">
+ <a href="#" @click.prevent="$store.projects.activateProject(project.name); open = false;" class="project-dropdown-item">
+ <span class="project-color-ball" :style="project.color ? { backgroundColor: project.color } : { border: '1px solid var(--color-border)' }"></span>
+ <span class="project-selector-item-text" x-text="project.title"></span>
+ </a>
+ </template>
+ </div>
</div>
</template>
</div>
</body>
<style>
- .project-button {
- display: inline-flex;
- align-items: center;
- gap: 0.3em;
- padding-left: 0.5em;
- padding-right: 0.5em;
- }
- .project-color-ball {
- width: 0.6em;
- height: 0.6em;
- border-radius: 50%;
- display: inline-block;
- box-sizing: border-box;
- }
+ .project-dropdown-container {
+ position: relative;
+ display: inline-block;
+ }
+
+ .project-dropdown-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3em;
+ padding-left: 0.5em;
+ padding-right: 0.5em;
+ }
+
+ .project-color-ball {
+ width: 0.6em;
+ height: 0.6em;
+ border-radius: 50%;
+ display: inline-block;
+ box-sizing: border-box;
+ flex-shrink: 0;
+ }
+
+ .project-dropdown-menu {
+ position: absolute;
+ top: 100%;
+ right: 0;
+ z-index: 1000;
+ background-color: var(--color-panel);
+ border: 1px solid var(--color-border);
+ border-radius: 4px;
+ padding: 0.5em 0;
+ min-width: 10rem;
+ max-width: 20em;
+ max-height: 70vh;
+ overflow-y: auto;
+ margin-top: 0.25rem;
+ }
+
+ .project-dropdown-item {
+ display: flex;
+ align-items: center;
+ margin: 0.25em 0.5em 0.25em 0.5em;
+ padding: 0.5em 1em;
+ color: var(--color-text-primary);
+ border-radius: var(--spacing-xs);
+ text-decoration: none;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ .project-dropdown-item:hover {
+ background-color: var(--color-background-hover);
+ }
+
+ .project-dropdown-divider {
+ height: 1px;
+ margin: 0.5rem 0;
+ overflow: hidden;
+ background-color: var(--color-border);
+ border: 0;
+ }
+
+ .project-selector-item-text {
+ margin-left: 0.5em;
+ }
</style>
-</html>
\ No newline at end of file
+</html>
diff --git a/webui/components/projects/projects-store.js b/webui/components/projects/projects-store.js
index 420fc21e7..fcba1c1b5 100644
--- a/webui/components/projects/projects-store.js
+++ b/webui/components/projects/projects-store.js
@@ -4,6 +4,7 @@ import * as modals from "/js/modals.js";
import * as notifications from "/components/notifications/notification-store.js";
import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
import { store as browserStore } from "/components/modals/file-browser/file-browser-store.js";
+import * as shortcuts from "/js/shortcuts.js";
const listModal = "projects/project-list.html";
const createModal = "projects/project-create.html";
@@ -322,6 +323,56 @@ const model = {
}
},
+ async browseKnowledgeFiles() {
+ await this.browseSelected(".a0proj", "knowledge");
+ // refresh and reindex project
+ try {
+ // progress notification
+ shortcuts.frontendNotification({
+ type: shortcuts.NotificationType.PROGRESS,
+ message: "Loading knowledge...",
+ priority: shortcuts.NotificationPriority.NORMAL,
+ displayTime: 999,
+ group: "knowledge_load",
+ frontendOnly: true,
+ });
+
+ // call reindex knowledge
+ const reindexCall = api.callJsonApi("/knowledge_reindex", {
+ ctxid: shortcuts.getCurrentContextId(),
+ });
+
+ const newData = await this._createEditProjectData(
+ this.selectedProject.name
+ );
+ this.selectedProject.knowledge_files_count =
+ newData.knowledge_files_count;
+
+ // wait for reindex to finish
+ await reindexCall;
+
+ // finished notification
+ shortcuts.frontendNotification({
+ type: shortcuts.NotificationType.SUCCESS,
+ message: "Knowledge loaded successfully",
+ priority: shortcuts.NotificationPriority.NORMAL,
+ displayTime: 2,
+ group: "knowledge_load",
+ frontendOnly: true,
+ });
+ } catch (error) {
+ // error notification
+ shortcuts.frontendNotification({
+ type: shortcuts.NotificationType.ERROR,
+ message: "Error loading knowledge",
+ priority: shortcuts.NotificationPriority.NORMAL,
+ displayTime: 5,
+ group: "knowledge_load",
+ frontendOnly: true,
+ });
+ }
+ },
+
getSelectedAbsPath(...relPath) {
return ["/a0/usr/projects", this.selectedProject.name, ...relPath]
.join("/")
diff --git a/webui/components/sidebar/chats/chats-list.html b/webui/components/sidebar/chats/chats-list.html
index 9d22c8049..7a11ec98f 100644
--- a/webui/components/sidebar/chats/chats-list.html
+++ b/webui/components/sidebar/chats/chats-list.html
@@ -14,9 +14,11 @@
<ul class="config-list chats-config-list" x-show="$store.chats.contexts.length > 0">
<template x-for="context in $store.chats.contexts" :key="context.id">
<li>
- <div :class="{'chat-container': true, 'chat-selected': context.id === $store.chats.selected}" @click="$store.chats.selectChat(context.id)">
+ <div :class="{'chat-container': true, 'chat-selected': context.id === $store.chats.selected}"
+ @click="$store.chats.selectChat(context.id)">
<div class="chat-list-button">
- <span class="project-color-ball" :style="context.project?.color ? { backgroundColor: context.project.color } : { border: '1px solid var(--color-border)' }"></span>
+ <span class="project-color-ball"
+ :style="context.project?.color ? { backgroundColor: context.project.color } : { border: '1px solid var(--color-border)' }"></span>
<span class="chat-name" :title="context.name ? context.name : 'Chat #' + context.no"
x-text="context.name ? context.name : 'Chat #' + context.no"></span>
</div>
@@ -80,7 +82,7 @@
}
.chat-container:hover {
- background-color: rgba(255, 255, 255, 0.03);
+ background-color: var(--color-background-hover);
}
.chat-list-button {
@@ -149,7 +151,7 @@
/* Selected chat accent */
.chat-selected {
- background-color: rgba(var(--color-border-rgb, 50, 50, 50), 0.5);
+ background-color: var(--color-background-hover);
}
.chat-selected .chat-name {
diff --git a/webui/components/sidebar/tasks/tasks-list.html b/webui/components/sidebar/tasks/tasks-list.html
index c795fd765..bf51bfabe 100644
--- a/webui/components/sidebar/tasks/tasks-list.html
+++ b/webui/components/sidebar/tasks/tasks-list.html
@@ -149,7 +149,7 @@
}
.task-container:hover {
- background-color: rgba(255, 255, 255, 0.03);
+ background-color: var(--color-background-hover);
}
@@ -157,7 +157,7 @@
/* Selected task accent */
.task-selected {
- background-color: rgba(var(--color-border-rgb, 50, 50, 50), 0.5);
+ background-color: var(--color-background-hover);
}
.task-selected .task-name {
diff --git a/webui/index.css b/webui/index.css
index 5d6555526..9a5db9eac 100644
--- a/webui/index.css
+++ b/webui/index.css
@@ -49,6 +49,7 @@
--color-border: var(--color-border-dark);
--color-input: var(--color-input-dark);
--color-input-focus: var(--color-input-focus-dark);
+ --color-background-hover: color-mix(in srgb, var(--color-border) 50%, transparent);
/* Spacing variables */
--spacing-xxs: 0.15rem;
@@ -88,6 +89,7 @@
--color-border: var(--color-border-light);
--color-input: var(--color-input-light);
--color-input-focus: var(--color-input-focus-light);
+ --color-background-hover: color-mix(in srgb, var(--color-border) 50%, transparent);
}
/* Reset and Base Styles */
diff --git a/webui/js/shortcuts.js b/webui/js/shortcuts.js
new file mode 100644
index 000000000..9a70f7799
--- /dev/null
+++ b/webui/js/shortcuts.js
@@ -0,0 +1,24 @@
+import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
+import { callJsonApi } from "/js/api.js";
+import {
+ NotificationType,
+ NotificationPriority,
+ store as notificationStore
+} from "/components/notifications/notification-store.js";
+
+// shortcuts utils for convenience
+
+// api
+export { callJsonApi };
+
+// notifications
+export {
+ NotificationType,
+ NotificationPriority,
+}
+export const frontendNotification = notificationStore.frontendNotification.bind(notificationStore);
+
+// chat context
+export function getCurrentContextId() {
+ return chatsStore.getSelectedChatId();
+}