Connect existing projects to Git from settings

Set the Git origin in place so the project keeps its files, settings, and chat
scope. Exclude project metadata locally when initializing a repository and show
Git status before the first commit.

Move Model preset into Basic info, restore the saved selection when reopening
the editor, and use consistent spacing for the project switches.
This commit is contained in:
Alessandro Frau committed 2026-12-02 15:13:20 +01:00
1 parent c28964d83b
commit 2f150870e2
15 files changed
+409 -139

No files matched your search

+3 -1
View File
@@ -22,6 +22,8 @@ class Projects(ApiHandler):
data = self.create_project(input.get("project", None))
elif action == "clone":
data = self.clone_project(input.get("project", None))
elif action == "connect_git":
data = projects.connect_project_git(input.get("name"), input.get("git_url"))
elif action == "update":
data = self.update_project(input.get("project", None))
elif action == "delete":
@@ -145,4 +147,4 @@ class Projects(ApiHandler):
if settings:
basic_data["file_structure"] = settings # type: ignore
# get structure
return projects.get_file_structure(name, basic_data)
return projects.get_file_structure(name, basic_data)
+1
View File
@@ -27,6 +27,7 @@
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
- `Projects` is an `ApiHandler`.
- `Projects` defines `process(...)`.
- `connect_git` takes `name` and `git_url` for an existing project and returns its updated Git status. It shares the Projects endpoint's standard access checks and the local socket delegation.
- Observed side-effect areas: filesystem deletion, settings/state persistence.
- Imported dependency areas include: `helpers`, `helpers.api`, `helpers.notification`.
+11
View File
@@ -116,6 +116,8 @@ When a project is active, Agent Zero can use:
- project variables and secrets,
- project-specific model settings when configured.
Choose **Model preset** under **Basic info** in the project editor.
Try prompts like:
```text
@@ -143,6 +145,15 @@ right local files, branch state, and project instructions.
For private repositories, use a token when the UI asks for one. Do not paste
tokens into chat messages.
To back an existing project with Git, open its settings and go to **Basic info →
Git Repository**. Enter the remote URL and click **Clone**. Use an
HTTP(S) or SSH URL without a password or token.
Agent Zero initializes Git if needed and sets `origin` in the same project
folder. It preserves your current files and settings. Fetching remote history,
committing local files, and pushing are separate Git steps. When Agent Zero
initializes Git here, it adds `.a0proj` to the repository's local exclude list.
## Variables And Secrets
Projects can store values that only make sense inside that workspace.
+108 -23
View File
@@ -1,14 +1,19 @@
from git import Git, Repo
from git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError
from giturlparse import parse
from datetime import datetime, timezone
from dataclasses import dataclass
import os
from pathlib import Path
import subprocess
import base64
from configparser import Error as ConfigError
import re
import time
from urllib.parse import urlparse, urlunparse
from tempfile import TemporaryDirectory
from urllib.parse import urlparse, urlsplit, urlunparse
from helpers import files
from helpers.file_transfers import rename_no_replace
from helpers.localization import Localization
@@ -19,7 +24,7 @@ def strip_auth_from_url(url: str) -> str:
parsed = urlparse(url)
if not parsed.hostname:
return url
clean_netloc = parsed.hostname
clean_netloc = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
if parsed.port:
clean_netloc += f":{parsed.port}"
return urlunparse((parsed.scheme, clean_netloc, parsed.path, '', '', ''))
@@ -454,6 +459,74 @@ def clone_repo(url: str, dest: str, token: str | None = None):
return Repo(dest)
def _validate_remote_url(value: str) -> str:
message = "Enter an HTTP(S) or SSH Git URL without embedded credentials."
url = value.strip() if isinstance(value, str) else ""
if not url or re.search(r"[\s\x00-\x1f\x7f\\?#]", url):
raise ValueError(message)
if re.fullmatch(r"[\w.-]+@(?:[\w.-]+|\[[0-9a-fA-F:]+\]):(?!:).+", url):
return url
try:
parsed = urlsplit(url)
if (
parsed.scheme in {"http", "https", "ssh"}
and parsed.hostname
and parsed.path.strip("/")
and parsed.password is None
and (parsed.scheme == "ssh" or parsed.username is None)
and parsed.port != 0
):
return url
except ValueError:
pass
raise ValueError(message)
def connect_repo_origin(path: Path, url: str, *, exclude: str) -> None:
"""Set origin locally, initializing Git metadata when needed."""
url = _validate_remote_url(url)
git_dir = path / ".git"
if not os.path.lexists(git_dir):
try:
with Repo(path, expand_vars=False) as repo:
if repo.bare:
raise ValueError("Git metadata must be inside the project folder.")
except InvalidGitRepositoryError:
pass
with TemporaryDirectory(prefix=".git-init-", dir=path) as staging:
with Repo.init(staging, template="", expand_vars=False) as repo:
info = Path(repo.git_dir) / "info"
info.mkdir(exist_ok=True)
(info / "exclude").write_text(f"/{exclude}/\n", encoding="utf-8")
repo.create_remote("origin", url)
try:
rename_no_replace(Path(staging) / ".git", git_dir)
return
except FileExistsError:
pass # Another operation initialized the repository.
if git_dir.is_symlink() or not git_dir.is_dir() or (git_dir / "config").is_symlink():
raise ValueError("Git metadata must be inside the project folder.")
try:
with Repo(path, expand_vars=False) as repo:
if repo.bare or Path(repo.common_dir).resolve() != git_dir.resolve():
raise ValueError("Git metadata must be inside the project folder.")
try:
repo.create_remote("origin", url)
except GitCommandError:
with repo.config_reader("repository") as config:
section = 'remote "origin"'
if not config.has_section(section):
raise
if config.get_values(section, "url", "") != [url]:
raise ValueError("This project already has a Git origin.") from None
except InvalidGitRepositoryError:
raise ValueError("The project's Git metadata is invalid.") from None
class DirtyTreeConflictError(Exception):
"""Raised when a plugin update conflicts with local commits or edits."""
@@ -538,24 +611,31 @@ def update_repo(repo_path: str, auto_stash: bool = True) -> Repo:
return repo
# Files to ignore when checking dirty status (A0 project metadata)
A0_IGNORE_PATTERNS = {".a0proj", ".a0proj/"}
def _repo_origin_url(repo: Repo) -> str:
try:
return strip_auth_from_url(repo.remotes.origin.url)
except (AttributeError, ConfigError, ValueError):
return ""
def get_repo_origin_url(repo_path: str) -> str:
"""Read the origin URL for the repository rooted here, with credentials removed."""
try:
with Repo(repo_path, expand_vars=False) as repo:
return _repo_origin_url(repo)
except (InvalidGitRepositoryError, NoSuchPathError, OSError):
return ""
def get_repo_status(repo_path: str) -> dict:
"""Get Git repository status, ignoring A0 project metadata files."""
try:
repo = Repo(repo_path)
repo = Repo(repo_path, expand_vars=False)
if repo.bare:
return {"is_git_repo": False, "error": "Repository is bare"}
# Remote URL (always strip auth info for security)
remote_url = ""
try:
if repo.remotes:
remote_url = strip_auth_from_url(repo.remotes.origin.url)
except Exception:
pass
remote_url = _repo_origin_url(repo)
# Current branch
try:
@@ -565,10 +645,15 @@ def get_repo_status(repo_path: str) -> dict:
# Check dirty status, excluding A0 metadata
def is_a0_file(path: str) -> bool:
return path.startswith(".a0proj") or path == ".a0proj"
return path.split("/", 1)[0] == ".a0proj"
# Filter out A0 files from diff and untracked
changed_files = [d.a_path for d in repo.index.diff(None)] + [d.a_path for d in repo.index.diff("HEAD")]
head = repo.head.commit if repo.head.is_valid() else None
staged = (
[d.a_path or d.b_path for d in repo.index.diff(head)]
if head else [path for path, _stage in repo.index.entries]
)
changed_files = [d.a_path or d.b_path for d in repo.index.diff(None)] + staged
untracked = repo.untracked_files
real_changes = [f for f in changed_files if not is_a0_file(f)]
@@ -579,16 +664,16 @@ def get_repo_status(repo_path: str) -> dict:
last_commit = None
try:
commit = repo.head.commit
last_commit = {
"hash": commit.hexsha[:7],
"message": str(commit.message).split("\n")[0][:80],
"author": str(commit.author),
"date": datetime.fromtimestamp(
commit.committed_date,
tz=Localization.get().get_tzinfo(),
).strftime('%Y-%m-%d %H:%M %Z')
}
if head:
last_commit = {
"hash": head.hexsha[:7],
"message": str(head.message).split("\n")[0][:80],
"author": str(head.author),
"date": datetime.fromtimestamp(
head.committed_date,
tz=Localization.get().get_tzinfo(),
).strftime('%Y-%m-%d %H:%M %Z')
}
except Exception:
pass
+4 -1
View File
@@ -30,15 +30,18 @@
- `get_version()`
- `is_official_agent_zero_repo() -> bool`: Return True when origin points to agent0ai/agent-zero.
- `clone_repo(url: str, dest: str, token: str | None=...)`: Clone a git repository. Uses http.extraHeader for token auth (never stored in URL/config).
- `connect_repo_origin(path: Path, url: str, *, exclude: str)`: Add an origin locally and initialize Git when the project has no repository.
- `get_repo_origin_url(repo_path: str) -> str`: Read the origin URL for the repo rooted at that path with credentials removed.
- `DirtyTreeConflictError`: Reports the conflicting files when a plugin update is rolled back because local commits or edits conflict with upstream.
- `update_repo(repo_path: str, auto_stash: bool = True) -> Repo`: Fetches the configured tracking branch and rebases local commits, temporarily stashing tracked edits. Aborts its own failed rebase and restores original commits and edits before reporting conflicts; refuses pre-existing Git operations.
- `get_repo_status(repo_path: str) -> dict`: Get Git repository status, ignoring A0 project metadata files.
- Notable constants/configuration names: `A0_IGNORE_PATTERNS`.
## Runtime Contracts
- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.
- Git commit and release timestamp strings produced by `_format_git_timestamp` use UTC and omit a timezone suffix.
- Connecting a repo accepts credential-free HTTP(S) and SSH URLs and performs no network or worktree operations. Fresh Git metadata is published atomically with the specified local exclude. Existing origin and existing exclude rules are preserved. Repositories with Git metadata stored outside the project folder must be configured from Git directly.
- Project status reports the branch and staged or untracked changes in repositories with no commits.
- Update rollback restores staged edits with the stash index and preserves existing stash entries. Tracked A0 metadata participates in stashing so rollback cannot discard it. Rebase disables Git autostash and updates to other branch refs.
- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.
- Observed side-effect areas: filesystem writes, filesystem deletion, network calls, subprocess/runtime control, plugin state, settings/state persistence, secret handling.
+18 -2
View File
@@ -1,4 +1,5 @@
import os
from pathlib import Path
from typing import NotRequired, TypedDict, TYPE_CHECKING, cast
from helpers import files, dirty_json, persist_chat, file_tree, extension
@@ -173,6 +174,18 @@ def load_project_header(name: str):
return header
def connect_project_git(name: str, url: str) -> GitStatusData:
from helpers import git
name = validate_project_name(name)
path = Path(get_project_folder(name))
if path.is_symlink() or not (path / PROJECT_META_DIR / PROJECT_HEADER_FILE).is_file():
raise ValueError("Project folder not found.")
git.connect_repo_origin(path, url, exclude=PROJECT_META_DIR)
return cast(GitStatusData, git.get_repo_status(str(path)))
def _default_file_structure_settings():
try:
gitignore = files.read_file("conf/projects.default.gitignore")
@@ -514,7 +527,10 @@ def deactivate_project_in_chats(name: str):
def build_system_prompt_vars(name: str):
from helpers import git
project_data = load_basic_project_data(name)
project_path = get_project_folder(name)
main_instructions = project_data.get("instructions", "") or ""
include_agents_md = project_data.get("include_agents_md", True)
instruction_files = get_project_instruction_files(
@@ -533,8 +549,8 @@ def build_system_prompt_vars(name: str):
"project_description": project_data.get("description", ""),
"project_instructions": complete_instructions or "",
"include_agents_md": include_agents_md,
"project_path": files.normalize_a0_path(get_project_folder(name)),
"project_git_url": project_data.get("git_url", ""),
"project_path": files.normalize_a0_path(project_path),
"project_git_url": git.get_repo_origin_url(project_path) or project_data.get("git_url", ""),
}
+2
View File
@@ -24,6 +24,7 @@
- `delete_project(name: str)`
- `create_project(name: str, data: BasicProjectData)`
- `clone_git_project(name: str, git_url: str, git_token: str, data: BasicProjectData)`: Clone a git repository as a new A0 project. Token is used only for cloning via http header.
- `connect_project_git(name: str, url: str) -> GitStatusData`: Set the origin of an existing project and return its Git status.
- `load_project_header(name: str)`
- `_default_file_structure_settings()`
- `_normalizeBasicData(data: BasicProjectData) -> BasicProjectData`
@@ -77,6 +78,7 @@
- Active-project AGENTS.md protocol guidance excludes the exact project root AGENTS.md because `build_system_prompt_vars(...)` already loads it into project instructions; prose for that protocol block lives in `prompts/agent.protocol.projects.agents_md.md`.
- Project MCP config uses the same JSON string shape as global MCP settings: an object with `mcpServers`.
- Project MCP load/save paths validate project names as simple folder basenames before touching `.a0proj/mcp_servers.json`.
- Connecting Git validates the existing project folder, leaves project settings on disk alone, and delegates to `helpers.git.connect_repo_origin`. Project prompts prefer the local origin URL and fall back to the legacy header value.
- Activating or deactivating a project preserves the active chat profile when it
is available in the destination scope; otherwise it replaces it with the
configured default profile, then `agent0`, then the first available profile.
+114
View File
@@ -1,11 +1,16 @@
import asyncio
from concurrent.futures import ThreadPoolExecutor
import subprocess
import threading
from pathlib import Path
from types import SimpleNamespace
from flask import Flask
import pytest
import initialize
from agent import AgentConfig, AgentContext
from api.projects import Projects
from helpers import dirty_json, files, persist_chat, projects, subagents
from helpers import state_monitor_integration
@@ -17,6 +22,115 @@ def _prepare_project_tree(monkeypatch, tmp_path: Path) -> None:
(tmp_path / "plugins").mkdir(parents=True, exist_ok=True)
def _git(path: Path, *args: str) -> str:
return subprocess.check_output(["git", "-C", str(path), *args], text=True).strip()
def test_project_git_connect_preserves_files_and_only_sets_local_origin(monkeypatch, tmp_path):
_prepare_project_tree(monkeypatch, tmp_path)
_git(tmp_path, "init", "--quiet")
projects.create_project("demo", {"title": "Demo"})
path = Path(projects.get_project_folder("demo"))
(path / "draft.md").write_text("My work", encoding="utf-8")
header = path / ".a0proj" / "project.json"
saved_settings = header.read_bytes()
url = "https://example.test/team/demo.git"
handler = Projects(Flask(__name__), threading.Lock())
payload = {"action": "connect_git", "name": "demo", "git_url": url}
result = asyncio.run(handler.process(payload, None))
assert result["ok"]
assert result["data"] == projects.load_edit_project_data("demo")["git_status"]
assert result["data"]["remote_url"] == url
assert result["data"]["current_branch"] == _git(path, "branch", "--show-current")
assert result["data"]["untracked_count"] == 1
assert result["data"]["last_commit"] is None
assert projects.build_system_prompt_vars("demo")["project_git_url"] == url
assert _git(path, "remote", "get-url", "origin") == url
assert _git(path, "ls-files") == ""
assert _git(path, "check-ignore", ".a0proj/project.json") == ".a0proj/project.json"
assert _git(tmp_path, "remote") == ""
assert header.read_bytes() == saved_settings
assert (path / "draft.md").read_text(encoding="utf-8") == "My work"
_git(path, "add", "draft.md")
status = projects.connect_project_git("demo", url)
assert status["untracked_count"] == 0
assert status["is_dirty"]
def test_project_git_connect_preserves_existing_history_and_origin(monkeypatch, tmp_path):
_prepare_project_tree(monkeypatch, tmp_path)
projects.create_project("demo", {"title": "Demo"})
path = Path(projects.get_project_folder("demo"))
_git(path, "init", "--quiet")
_git(path, "-c", "user.name=Tester", "-c", "user.email=test@example.test", "commit", "--allow-empty", "-m", "Initial")
head = _git(path, "rev-parse", "HEAD")
exclude = path / ".git" / "info" / "exclude"
exclude.parent.mkdir(exist_ok=True)
exclude.write_text("/scratch\n", encoding="utf-8")
url = "git@example.test:team/demo.git"
status = projects.connect_project_git("demo", url)
assert status["last_commit"]["hash"] == head[:7]
assert projects.connect_project_git("demo", url) == status
with pytest.raises(ValueError, match="already has a Git origin"):
projects.connect_project_git("demo", "https://example.test/team/other.git")
assert _git(path, "remote", "get-url", "origin") == url
assert _git(path, "rev-parse", "HEAD") == head
assert exclude.read_text(encoding="utf-8") == "/scratch\n"
def test_project_git_connect_publishes_one_origin_when_requests_race(monkeypatch, tmp_path):
_prepare_project_tree(monkeypatch, tmp_path)
projects.create_project("demo", {"title": "Demo"})
ready = threading.Barrier(2)
def connect(url):
ready.wait(timeout=5)
try:
return projects.connect_project_git("demo", url)["remote_url"]
except ValueError as error:
assert "already has a Git origin" in str(error)
return None
urls = ("https://example.test/team/one.git", "https://example.test/team/two.git")
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(connect, urls))
origin = _git(Path(projects.get_project_folder("demo")), "remote", "get-url", "origin")
assert origin in urls
assert set(results) == {origin, None}
@pytest.mark.parametrize("url", ["", "file:///tmp/repo", "../repo", "ext::tool", "https://token@example.test/demo.git", "ssh://user:token@example.test/demo.git"])
def test_project_git_connect_rejects_unsupported_urls_before_initialization(monkeypatch, tmp_path, url):
_prepare_project_tree(monkeypatch, tmp_path)
projects.create_project("demo", {"title": "Demo"})
with pytest.raises(ValueError, match="Git URL"):
projects.connect_project_git("demo", url)
assert not (Path(projects.get_project_folder("demo")) / ".git").exists()
def test_project_git_connect_rejects_linked_project_folders_and_git_metadata(monkeypatch, tmp_path):
_prepare_project_tree(monkeypatch, tmp_path)
projects.create_project("demo", {"title": "Demo"})
path = Path(projects.get_project_folder("demo"))
(path.parent / "alias").symlink_to(path, target_is_directory=True)
url = "https://example.test/team/demo.git"
with pytest.raises(ValueError, match="Project folder not found"):
projects.connect_project_git("alias", url)
with pytest.raises(ValueError, match="Invalid project name"):
projects.connect_project_git("../demo", url)
_git(tmp_path, "init", "--quiet")
(path / ".git").write_text(f"gitdir: {tmp_path / '.git'}\n", encoding="utf-8")
with pytest.raises(ValueError, match="inside the project folder"):
projects.connect_project_git("demo", url)
assert _git(tmp_path, "remote") == ""
@pytest.mark.parametrize(
"destination_project", ["project-y", None], ids=["project", "global"]
)
+3 -1
View File
@@ -14,14 +14,16 @@
## Local Contracts
- Keep project API payloads synchronized with backend project handlers.
- The Git Repository section in Basic info connects projects that have no origin. The Clone button saves the remote immediately and replaces only the editor's Git status, so other unsaved settings stay in the form.
- `loadProjectsList()` retains the current list when response values are unchanged, avoiding sidebar regrouping on window focus. Changed project values and ordering still replace the list.
- Do not expose project secrets in logs, URLs, or long-lived frontend state unnecessarily.
- Preserve scoped settings interactions with plugins, models, skills, and MCP servers.
- Project model settings select a global `_model_config` preset; they do not own copied model dictionaries or project-local preset definitions.
- Basic info shows Model preset and its Presets button above Git Repository. Model preset selects a global `_model_config` preset; project settings do not own copied model dictionaries or project-local preset definitions.
- Agent Editor owns profile-scoped availability mutations. Project edit payloads
do not include that state, so unrelated project saves cannot restore stale
toggle values.
- Project form textareas keep their vertical resize grip; the shared settings stylesheet forces `resize: none` on every textarea, so the shared `.projects-form-textarea` rule re-enables it for description, instructions, file-structure, and secrets fields. The same rule disables the shared all-properties transition so dragging the grip stays instant.
- Project switches use the shared form-group spacing to stack the title, description, and switch. Each checkbox references its title and description.
- `project-selector.html` caps its dropdown with `--project-dropdown-available-height`, recomputed from the trigger's viewport position on open and on window resize, so the menu never extends past the window bottom and its rows stay scrollable in short windows. The cap floors at zero like the model switcher, so a trigger near the bottom edge yields a collapsed menu instead of a menu outside the viewport; the shared `.dropdown-menu` `overflow-y: auto` provides the scrolling.
- `#time-date-container` stacks above the composer `#input-section`, so the open project dropdown paints over the chat input; the mobile sidebar overlay stays one layer above the container. Do not lower the container below the composer again.
@@ -59,79 +59,112 @@
</div>
</div>
<!-- Git Status Section -->
<template x-if="!$store.projects.selectedProject._meta.creating && $store.projects.selectedProject.git_status?.is_git_repo">
<template x-if="!$store.projects.selectedProject._meta.creating">
<x-component path="projects/project-edit-llm.html"></x-component>
</template>
<template x-if="!$store.projects.selectedProject._meta.creating">
<div class="projects-form-group git-status-section">
<label class="projects-form-label">
<div class="projects-form-label">
<x-icon class="git-icon" name="commit"></x-icon>
Git Status
</label>
<div class="git-status-card">
<!-- Repository URL -->
<template x-if="$store.projects.selectedProject.git_status.remote_url">
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="link"></x-icon>
Repository
</span>
<div class="git-status-value-with-action">
<span class="git-status-value git-url" x-text="$store.projects.selectedProject.git_status.remote_url"></span>
<a class="git-action-link" :href="$store.projects.selectedProject.git_status.remote_url" target="_blank" rel="noopener noreferrer" title="Open in browser">
<x-icon name="open_in_new"></x-icon>
</a>
</div>
</div>
</template>
<!-- Branch -->
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="fork_right"></x-icon>
Branch
</span>
<span class="git-status-value git-branch" x-text="$store.projects.selectedProject.git_status.current_branch"></span>
</div>
<!-- Status -->
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="info"></x-icon>
Status
</span>
<span class="git-status-value"
:class="$store.projects.selectedProject.git_status.is_dirty ? 'git-dirty' : 'git-clean'">
<template x-if="!$store.projects.selectedProject.git_status.is_dirty">
<span>✓ Clean</span>
</template>
<template x-if="$store.projects.selectedProject.git_status.is_dirty">
<span>
● Has uncommitted changes
<template x-if="$store.projects.selectedProject.git_status.untracked_count > 0">
<span x-text="'(' + $store.projects.selectedProject.git_status.untracked_count + ' untracked)'"></span>
</template>
</span>
</template>
</span>
</div>
<!-- Last Commit -->
<template x-if="$store.projects.selectedProject.git_status.last_commit">
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="history"></x-icon>
Last Commit
</span>
<div class="git-commit-info">
<span class="git-commit-hash" x-text="$store.projects.selectedProject.git_status.last_commit.hash"></span>
<span class="git-commit-message" x-text="$store.projects.selectedProject.git_status.last_commit.message"></span>
<span class="git-commit-meta">
by <span x-text="$store.projects.selectedProject.git_status.last_commit.author"></span>
on <span x-text="$store.projects.selectedProject.git_status.last_commit.date"></span>
</span>
</div>
</div>
</template>
Git Repository
</div>
<template x-if="!$store.projects.selectedProject.git_status?.remote_url">
<form x-data="{ gitUrl: '', gitError: '', connecting: false }"
@submit.prevent="
if (connecting || !gitUrl.trim()) return;
connecting = true;
gitError = '';
try { await $store.projects.connectGitRemote(gitUrl); }
catch (error) { gitError = error.message; }
finally { connecting = false; }
">
<div class="projects-input-with-button-wrapper">
<input class="projects-form-input" type="text" x-model="gitUrl"
placeholder="https://github.com/user/repo.git" autocomplete="off" autocapitalize="none"
spellcheck="false" aria-label="Git repository URL" :disabled="connecting">
<button class="button" type="submit" :disabled="connecting || !gitUrl.trim()"
:aria-busy="connecting">Clone</button>
</div>
<p class="projects-form-description" role="alert" x-show="gitError" x-text="gitError"></p>
</form>
</template>
<template x-if="$store.projects.selectedProject.git_status?.is_git_repo">
<div class="git-status-card">
<!-- Repository URL -->
<template x-if="$store.projects.selectedProject.git_status.remote_url">
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="link"></x-icon>
Repository
</span>
<div class="git-status-value-with-action">
<span class="git-status-value git-url" x-text="$store.projects.selectedProject.git_status.remote_url"></span>
<template x-if="/^https?:\/\//i.test($store.projects.selectedProject.git_status.remote_url)">
<a class="git-action-link" :href="$store.projects.selectedProject.git_status.remote_url" target="_blank" rel="noopener noreferrer" aria-label="Open repository in browser" title="Open in browser">
<x-icon name="open_in_new"></x-icon>
</a>
</template>
</div>
</div>
</template>
<!-- Branch -->
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="fork_right"></x-icon>
Branch
</span>
<span class="git-status-value git-branch" x-text="$store.projects.selectedProject.git_status.current_branch"></span>
</div>
<!-- Status -->
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="info"></x-icon>
Status
</span>
<span class="git-status-value"
:class="$store.projects.selectedProject.git_status.is_dirty ? 'git-dirty' : 'git-clean'">
<template x-if="!$store.projects.selectedProject.git_status.is_dirty">
<span>✓ Clean</span>
</template>
<template x-if="$store.projects.selectedProject.git_status.is_dirty">
<span>
● Has uncommitted changes
<template x-if="$store.projects.selectedProject.git_status.untracked_count > 0">
<span x-text="'(' + $store.projects.selectedProject.git_status.untracked_count + ' untracked)'"></span>
</template>
</span>
</template>
</span>
</div>
<!-- Last Commit -->
<template x-if="$store.projects.selectedProject.git_status.last_commit">
<div class="git-status-row">
<span class="git-status-label">
<x-icon name="history"></x-icon>
Last Commit
</span>
<div class="git-commit-info">
<span class="git-commit-hash" x-text="$store.projects.selectedProject.git_status.last_commit.hash"></span>
<span class="git-commit-message" x-text="$store.projects.selectedProject.git_status.last_commit.message"></span>
<span class="git-commit-meta">
by <span x-text="$store.projects.selectedProject.git_status.last_commit.author"></span>
on <span x-text="$store.projects.selectedProject.git_status.last_commit.date"></span>
</span>
</div>
</div>
</template>
<template x-if="!$store.projects.selectedProject.git_status.last_commit">
<div class="git-status-row">
<span class="git-status-label"><x-icon name="history"></x-icon> Last Commit</span>
<span class="git-status-value">No commits yet</span>
</div>
</template>
</div>
</template>
</div>
</template>
</div>
@@ -374,4 +407,4 @@
</style>
</html>
</html>
@@ -17,19 +17,16 @@
</div> -->
<div class="projects-setting-row" style="padding: 1rem 0;">
<div class="projects-setting-text">
<label class="projects-form-label">Inject project structure into context window</label>
<span class="projects-form-description">When turned on, the project file structure will be
injected into the context window of the agent. This is useful for agents that need to
have an overview of project folders and files at all times.</span>
</div>
<div class="projects-setting-control">
<label class="toggle">
<input type="checkbox" x-model="$store.projects.selectedProject.file_structure.enabled">
<span class="toggler"></span>
</label>
</div>
<div class="projects-form-group">
<label class="projects-form-label" for="project-inject-file-structure">Inject project structure into context window</label>
<span class="projects-form-description" id="project-inject-file-structure-description">When turned on,
the project file structure will be injected into the context window of the agent. This is useful
for agents that need to have an overview of project folders and files at all times.</span>
<label class="toggle">
<input type="checkbox" id="project-inject-file-structure" aria-describedby="project-inject-file-structure-description"
x-model="$store.projects.selectedProject.file_structure.enabled">
<span class="toggler"></span>
</label>
</div>
<div x-show="$store.projects.selectedProject.file_structure.enabled">
@@ -99,4 +96,4 @@
<style>
</style>
</html>
</html>
@@ -33,18 +33,16 @@
placeholder="Enter project instructions"></textarea>
</div>
<div class="projects-setting-row" style="padding: 1rem 0;">
<div class="projects-setting-text">
<label class="projects-form-label">Include top-level AGENTS.md</label>
<span class="projects-form-description">When turned on, Agent Zero will include the project's
top-level AGENTS.md file in the active project instructions when that file exists.</span>
</div>
<div class="projects-setting-control">
<label class="toggle">
<input type="checkbox" x-model="$store.projects.selectedProject.include_agents_md">
<span class="toggler"></span>
</label>
</div>
<div class="projects-form-group">
<label class="projects-form-label" for="project-include-agents-md">Include top-level AGENTS.md</label>
<span class="projects-form-description" id="project-include-agents-md-description">When turned on,
Agent Zero will include the project's top-level AGENTS.md file in the active project instructions
when that file exists.</span>
<label class="toggle">
<input type="checkbox" id="project-include-agents-md" aria-describedby="project-include-agents-md-description"
x-model="$store.projects.selectedProject.include_agents_md">
<span class="toggler"></span>
</label>
</div>
<div class="projects-form-group">
@@ -11,20 +11,22 @@
<div x-data>
<template x-if="$store.projects && $store.projects.selectedProject && $store.projects.selectedProject.llm">
<div class="project-llm-preset-row">
<div class="projects-form-group project-llm-preset-field">
<label class="projects-form-label">Model preset</label>
<div class="projects-form-group">
<label class="projects-form-label" for="project-model-preset">Model preset</label>
<div class="projects-input-with-button-wrapper project-llm-preset-controls">
<select class="projects-form-select"
<select id="project-model-preset" class="projects-form-select"
x-model="$store.projects.selectedProject.llm.preset_key"
@change="$store.projects.applySelectedLlmPreset()">
<template x-for="preset in $store.projects.selectedProject.llm.global_presets" :key="$store.projects.getLlmPresetKey(preset)">
<option :value="$store.projects.getLlmPresetKey(preset)" x-text="preset.name"></option>
<option :value="$store.projects.getLlmPresetKey(preset)"
:selected="$store.projects.selectedProject.llm.preset_key === $store.projects.getLlmPresetKey(preset)"
x-text="preset.name"></option>
</template>
</select>
<button type="button" class="button icon-button project-llm-edit-presets"
@click="$store.projects.editSelectedProjectPresets()">
<x-icon class="icon" name="tune"></x-icon>
<span>Edit Presets</span>
<span>Presets</span>
</button>
</div>
</div>
@@ -37,10 +39,6 @@
max-width: 100%;
}
.project-llm-preset-field {
margin-bottom: 0;
}
.project-llm-preset-controls {
align-items: stretch;
}
+2 -5
View File
@@ -34,16 +34,13 @@
</x-component>
<div class="settings-advanced-section project-advanced-section" x-data="{ advOpen: false }">
<button type="button" class="settings-advanced-toggle" @click="advOpen = !advOpen">
<button type="button" class="settings-advanced-toggle" :aria-expanded="advOpen" @click="advOpen = !advOpen">
<x-icon class="settings-advanced-toggle-icon"
:style="advOpen ? 'transform:rotate(90deg)' : ''" name="chevron_right"></x-icon>
<span>Advanced Settings</span>
</button>
<div class="settings-advanced-body" x-show="advOpen" x-transition.opacity style="display: none;">
<x-component path="projects/project-edit-llm.html">
</x-component>
</div>
<div class="settings-advanced-body" x-show="advOpen" x-transition.opacity style="display: none;"></div>
</div>
</div>
@@ -206,6 +206,17 @@ const model = {
await modals.closeModal(editModal);
},
async connectGitRemote(gitUrl) {
const project = this.selectedProject;
const response = await api.callJsonApi("projects", {
action: "connect_git",
name: project.name,
git_url: gitUrl.trim(),
});
if (!response.ok) throw new Error(response.error || "Could not connect repository.");
project.git_status = response.data;
},
async activateProject(name) {
try {
const response = await api.callJsonApi("projects", {