Agent Zero AI framework
feat(pin-to-top): support project folder pins
Alessandroe86f32982ab2
diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex 0e1639a04..11a5cd580 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -94,7 +94,7 @@ Direct child DOX files:| [_office/AGENTS.md](_office/AGENTS.md) | LibreOffice office artifacts and office canvas sessions. || [_onboarding/AGENTS.md](_onboarding/AGENTS.md) | First-time model onboarding wizard. || [_orchestrator/AGENTS.md](_orchestrator/AGENTS.md) | External terminal coding-agent orchestration skill, adapter status, and settings UI. |-| [_pin_to_top/AGENTS.md](_pin_to_top/AGENTS.md) | Built-in chat and task sidebar pinning. |+| [_pin_to_top/AGENTS.md](_pin_to_top/AGENTS.md) | Built-in chat, task, and project-folder sidebar pinning. || [_plugin_installer/AGENTS.md](_plugin_installer/AGENTS.md) | Plugin install and update flows from ZIP, Git, and Plugin Index. || [_plugin_scan/AGENTS.md](_plugin_scan/AGENTS.md) | LLM-guided security scanner for third-party plugins. || [_plugin_validator/AGENTS.md](_plugin_validator/AGENTS.md) | Plugin manifest, structure, convention, and security validator. |diff --git a/plugins/_pin_to_top/AGENTS.md b/plugins/_pin_to_top/AGENTS.mdindex fec73def1..0333ee19a 100644--- a/plugins/_pin_to_top/AGENTS.md+++ b/plugins/_pin_to_top/AGENTS.md@@ -2,18 +2,20 @@## Purpose-- Own built-in pinning for chat and scheduled-task rows in the sidebar.+- Own built-in pinning for chats, scheduled tasks, and project folders in the sidebar.## Ownership- `plugin.yaml` owns the always-enabled plugin metadata.- `helpers/pins.py` and `api/` own persistent pin state and authenticated toggle/read endpoints.-- `webui/pin-to-top-store.js` owns row ordering and divider callbacks.+- `webui/pin-to-top-store.js` owns row ordering, divider callbacks, and the project pin interface used by Folder view.- `extensions/webui/sidebar-row-actions-menu/` owns the dropdown action.## Local Contracts-- Pin state is separated into `chat` and `task` groups and stored under the `plugin_pin_to_top` persistent KVP key.+- Pin state is separated into `chat`, `task`, and `project` groups and stored under the `plugin_pin_to_top` persistent KVP key; older state without `project` remains valid.+- Project keys are validated project directory names. Adding a project pin requires its project header to exist; removing a stale pin remains possible.+- Folder view reads `pins.project`, calls `isProjectPinned(name)` / `toggleProjectPin(name)`, and can sort groups with `sortItems("project", items)` where each item has `id: name`.- The plugin must register sidebar row-list callbacks; it must not patch chat/task stores or inject controls directly into rows.- Pinned items sort before unpinned items, older pins remain first, and existing order is preserved within the unpinned group.- The menu label and icon must reflect whether the active row is pinned.diff --git a/plugins/_pin_to_top/README.md b/plugins/_pin_to_top/README.mdindex b5a6ab53a..fd09f6f01 100644--- a/plugins/_pin_to_top/README.md+++ b/plugins/_pin_to_top/README.md@@ -1,10 +1,11 @@# Pin to Top-Built-in Agent Zero plugin for pinning chats and scheduled tasks to the top of their sidebar lists.+Built-in Agent Zero plugin for pinning chats, scheduled tasks, and project folders to the top of their sidebar lists.- Adds a context-aware **Pin to Top** / **Unpin from Top** action to the sidebar row menu.- Keeps pinned items in pin order and preserves the existing order within the unpinned group.- Separates pinned and unpinned items with the standard sidebar divider.- Persists state in Agent Zero's user key-value storage.+- Folder view uses the same persisted project pins in Chats and Tasks; individual chat and task pins remain independent.The plugin is always enabled and has no configuration screen.diff --git a/plugins/_pin_to_top/api/get_pins.py b/plugins/_pin_to_top/api/get_pins.pyindex 9a948775b..fffe74a80 100644--- a/plugins/_pin_to_top/api/get_pins.py+++ b/plugins/_pin_to_top/api/get_pins.py@@ -3,7 +3,7 @@ from plugins._pin_to_top.helpers.pins import get_pinsclass GetPins(ApiHandler):- """Return persisted chat and task pins."""+ """Return persisted chat, task, and project pins."""async def process(self, input: Input, request: Request) -> Output:return {"ok": True, "pins": get_pins()}diff --git a/plugins/_pin_to_top/api/toggle_pin.py b/plugins/_pin_to_top/api/toggle_pin.pyindex 94536c550..23589a0a3 100644--- a/plugins/_pin_to_top/api/toggle_pin.py+++ b/plugins/_pin_to_top/api/toggle_pin.py@@ -3,7 +3,7 @@ from plugins._pin_to_top.helpers.pins import toggle_pinclass TogglePin(ApiHandler):- """Toggle one chat or task pin."""+ """Toggle one chat, task, or project pin."""async def process(self, input: Input, request: Request) -> Output:try:diff --git a/plugins/_pin_to_top/helpers/pins.py b/plugins/_pin_to_top/helpers/pins.pyindex c454de85e..3750343bd 100644--- a/plugins/_pin_to_top/helpers/pins.py+++ b/plugins/_pin_to_top/helpers/pins.py@@ -1,15 +1,16 @@from __future__ import annotations+import osimport threadingimport timefrom typing import Literal-from helpers import kvp+from helpers import kvp, projects-PinKind = Literal["chat", "task"]+PinKind = Literal["chat", "task", "project"]STORE_KEY = "plugin_pin_to_top"-KINDS: tuple[PinKind, ...] = ("chat", "task")+KINDS: tuple[PinKind, ...] = ("chat", "task", "project")_lock = threading.RLock()@@ -23,6 +24,8 @@ def toggle_pin(kind: str, item_id: str) -> tuple[bool, float]:"""Toggle a pin and return its new state and timestamp."""normalized_kind = _require_kind(kind)normalized_id = _require_item_id(item_id)+ if normalized_kind == "project":+ normalized_id = projects.validate_project_name(normalized_id)with _lock:pins = _normalize(kvp.get_persistent(STORE_KEY, {}))@@ -32,6 +35,10 @@ def toggle_pin(kind: str, item_id: str) -> tuple[bool, float]:timestamp = 0.0pinned = Falseelse:+ if normalized_kind == "project" and not os.path.isfile(+ projects.get_project_meta(normalized_id, projects.PROJECT_HEADER_FILE)+ ):+ raise ValueError("Project not found")timestamp = time.time()kind_pins[normalized_id] = timestamppinned = True@@ -41,7 +48,7 @@ def toggle_pin(kind: str, item_id: str) -> tuple[bool, float]:def _normalize(value: object) -> dict[PinKind, dict[str, float]]:- normalized: dict[PinKind, dict[str, float]] = {"chat": {}, "task": {}}+ normalized: dict[PinKind, dict[str, float]] = {kind: {} for kind in KINDS}if not isinstance(value, dict):return normalized@@ -63,7 +70,7 @@ def _normalize(value: object) -> dict[PinKind, dict[str, float]]:def _require_kind(kind: str) -> PinKind:if kind not in KINDS:- raise ValueError("kind must be 'chat' or 'task'")+ raise ValueError("kind must be 'chat', 'task', or 'project'")return kinddiff --git a/plugins/_pin_to_top/plugin.yaml b/plugins/_pin_to_top/plugin.yamlindex 12dd9a56e..26216b5f7 100644--- a/plugins/_pin_to_top/plugin.yaml+++ b/plugins/_pin_to_top/plugin.yaml@@ -1,7 +1,7 @@name: _pin_to_toptitle: Pin to Top-description: Pin chats and scheduled tasks to the top of their sidebar lists.-version: 1.0.0+description: Pin chats, scheduled tasks, and project folders to the top of their sidebar lists.+version: 1.1.0settings_sections: []per_project_config: falseper_agent_config: falsediff --git a/plugins/_pin_to_top/tests/test_pins.py b/plugins/_pin_to_top/tests/test_pins.pyindex 0eb9ab7da..97f292cf6 100644--- a/plugins/_pin_to_top/tests/test_pins.py+++ b/plugins/_pin_to_top/tests/test_pins.py@@ -1,4 +1,7 @@import asyncio+import shutil+import subprocess+from pathlib import Pathimport pytest@@ -32,6 +35,7 @@ def test_pins_are_persistent_and_separated_by_kind(monkeypatch, persistent_storeassert pins.get_pins() == {"chat": {"chat-1": 100.0},"task": {"task-1": 200.0},+ "project": {},}assert pins.toggle_pin("chat", "chat-1") == (False, 0.0)@@ -55,6 +59,76 @@ def test_toggle_api_returns_a_bad_request_for_invalid_input(persistent_store):assert response.status_code == 400+def test_project_pins_validate_projects_and_preserve_legacy_pins(+ monkeypatch, persistent_store, tmp_path+):+ persistent_store[pins.STORE_KEY] = {"chat": {"chat-1": 100.0}, "task": {"task-1": 200.0}}+ monkeypatch.setattr(pins.projects, "PROJECTS_PARENT_DIR", str(tmp_path))+ monkeypatch.setattr(pins.time, "time", lambda: 300.0)+ header = tmp_path / "my-project" / ".a0proj" / "project.json"+ header.parent.mkdir(parents=True)+ header.write_text("{}")++ assert pins.get_pins()["project"] == {}+ response = asyncio.run(+ TogglePin(None, None).process({"kind": "project", "item_id": "my-project"}, None)+ )+ assert response == {"ok": True, "pinned": True, "timestamp": 300.0}+ assert asyncio.run(GetPins(None, None).process({}, None))["pins"] == {+ "chat": {"chat-1": 100.0},+ "task": {"task-1": 200.0},+ "project": {"my-project": 300.0},+ }+ for name in ("../my-project", "missing-project"):+ response = asyncio.run(+ TogglePin(None, None).process({"kind": "project", "item_id": name}, None)+ )+ assert response.status_code == 400++ header.unlink()+ assert pins.toggle_pin("project", "my-project") == (False, 0.0)+ assert pins.get_pins()["project"] == {}++[email protected](not shutil.which("node"), reason="node is required")+def test_project_pin_store_keeps_order_and_handles_arbitrary_project_names():+ script = """+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { runInNewContext } from 'node:vm';+const source = readFileSync(process.argv[1], 'utf8')+ .replace(/^import .*;$/gm, '')+ .replace('export const store = createStore("pinToTop", model);', 'globalThis.store = model;');+const calls = [];+const context = {+ callJsonApi: async (path, input) => {+ calls.push([path, input]);+ return { pinned: calls.length === 1, timestamp: 300 };+ },+ toastFrontendError: message => { throw new Error(message); },+};+runInNewContext(source, context);+const store = context.store;+const rows = [{ id: 'constructor' }, { id: '__proto__' }, { id: 'other' }];+assert.equal(store.isProjectPinned('__proto__'), false);+await store.toggleProjectPin('__proto__');+assert.equal(calls[0][0], '/plugins/_pin_to_top/toggle_pin');+assert.equal(calls[0][1].kind, 'project');+assert.equal(calls[0][1].item_id, '__proto__');+assert.equal(store.isProjectPinned('__proto__'), true);+assert.equal(store.sortItems('project', rows).map(item => item.id).join(','), '__proto__,constructor,other');+assert.equal(store.isPinned('chat', '__proto__'), false);+await store.toggleProjectPin('__proto__');+assert.equal(store.isProjectPinned('__proto__'), false);+assert.equal(store.sortItems('project', rows).map(item => item.id).join(','), 'constructor,__proto__,other');+await store.toggleFromMenu('task:task-1', 'task');+assert.equal(calls[2][1].kind, 'task');+assert.equal(calls[2][1].item_id, 'task-1');+"""+ store = Path(__file__).resolve().parents[1] / "webui" / "pin-to-top-store.js"+ subprocess.run(["node", "--input-type=module", "-e", script, str(store)], check=True)++def test_pin_endpoints_keep_default_auth_and_csrf_protection():for handler in (GetPins, TogglePin):assert handler.requires_auth() is Truediff --git a/plugins/_pin_to_top/webui/pin-to-top-store.js b/plugins/_pin_to_top/webui/pin-to-top-store.jsindex 16e8578d7..b50302e91 100644--- a/plugins/_pin_to_top/webui/pin-to-top-store.js+++ b/plugins/_pin_to_top/webui/pin-to-top-store.js@@ -6,7 +6,7 @@ import { store as sidebarStore } from "/components/sidebar/sidebar-store.js";const PLUGIN_ID = "_pin_to_top";const model = {- pins: { chat: {}, task: {} },+ pins: { chat: {}, task: {}, project: {} },_initialized: false,async init() {@@ -30,6 +30,7 @@ const model = {this.pins = {chat: { ...(response?.pins?.chat || {}) },task: { ...(response?.pins?.task || {}) },+ project: { ...(response?.pins?.project || {}) },};} catch (error) {void toastFrontendError(error?.message || "Failed to load pinned items.", "Pin to Top");@@ -37,7 +38,18 @@ const model = {},async toggleFromMenu(menuId, kind) {- const itemId = this.itemIdFromMenu(menuId, kind);+ return this.togglePin(kind, this.itemIdFromMenu(menuId, kind));+ },++ isProjectPinned(name) {+ return this.isPinned("project", name);+ },++ async toggleProjectPin(name) {+ return this.togglePin("project", name);+ },++ async togglePin(kind, itemId) {if (!itemId) return;try {@@ -45,9 +57,8 @@ const model = {kind,item_id: itemId,});- const kindPins = { ...(this.pins[kind] || {}) };- if (response?.pinned) kindPins[itemId] = response.timestamp;- else delete kindPins[itemId];+ const kindPins = { ...(this.pins[kind] || {}), [itemId]: response?.timestamp };+ if (!response?.pinned) delete kindPins[itemId];this.pins = { ...this.pins, [kind]: kindPins };} catch (error) {void toastFrontendError(error?.message || "Failed to update the pin.", "Pin to Top");@@ -76,8 +87,8 @@ const model = {.sort((left, right) => {const leftPin = kindPins[left.item.id];const rightPin = kindPins[right.item.id];- const leftPinned = leftPin !== undefined;- const rightPinned = rightPin !== undefined;+ const leftPinned = this.isPinned(kind, left.item.id);+ const rightPinned = this.isPinned(kind, right.item.id);if (leftPinned !== rightPinned) return leftPinned ? -1 : 1;if (leftPinned && leftPin !== rightPin) return leftPin - rightPin;return left.index - right.index;